> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tensorone.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Cluster Proxy & Port Management

> Manage proxy URLs, port forwarding, and network access for GPU clusters

## Overview

Cluster Proxy and Port Management provides secure access to cluster services through HTTPS proxy URLs, port forwarding configurations, and network access controls. Essential for accessing web applications, APIs, and development tools running on GPU clusters.

## Endpoints

### Get Proxy Configuration

```bash curl
GET https://api.tensorone.ai/v1/clusters/{cluster_id}/proxy
```

### Update Proxy Settings

```bash curl
PUT https://api.tensorone.ai/v1/clusters/{cluster_id}/proxy
```

### Manage Port Mappings

```bash curl
POST https://api.tensorone.ai/v1/clusters/{cluster_id}/proxy/ports
PUT https://api.tensorone.ai/v1/clusters/{cluster_id}/proxy/ports/{port_id}
DELETE https://api.tensorone.ai/v1/clusters/{cluster_id}/proxy/ports/{port_id}
```

### Configure Access Control

```bash curl
PUT https://api.tensorone.ai/v1/clusters/{cluster_id}/proxy/access
```

## Get Proxy Configuration

### Query Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `include_health` | boolean | No | Include health check status for mapped ports |
| `include_access_logs` | boolean | No | Include recent access logs |
| `include_ssl_info` | boolean | No | Include SSL certificate information |

### Request Examples

```bash curl
# Get complete proxy configuration
curl -X GET "https://api.tensorone.ai/v1/clusters/cluster_abc123/proxy?include_health=true" \
  -H "Authorization: Bearer YOUR_API_KEY"

# Get proxy config with access logs
curl -X GET "https://api.tensorone.ai/v1/clusters/cluster_abc123/proxy?include_access_logs=true" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

```python Python
import requests

def get_proxy_config(cluster_id, include_health=True, include_logs=False):
    """Get cluster proxy configuration"""
    
    params = {}
    if include_health:
        params["include_health"] = "true"
    if include_logs:
        params["include_access_logs"] = "true"
    
    response = requests.get(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/proxy",
        headers={"Authorization": f"Bearer {API_KEY}"},
        params=params
    )
    
    return response.json()

def get_accessible_services(cluster_id):
    """Get list of accessible services with their URLs"""
    
    config = get_proxy_config(cluster_id, include_health=True)
    
    if not config["success"]:
        return {"error": "Failed to get proxy config"}
    
    proxy_data = config["data"]
    services = []
    
    for port_mapping in proxy_data.get("port_mappings", []):
        if port_mapping["status"] == "active":
            services.append({
                "name": port_mapping["description"],
                "url": port_mapping["url"],
                "port": port_mapping["external_port"],
                "protocol": port_mapping["protocol"],
                "health": port_mapping.get("health_status", "unknown")
            })
    
    return {
        "cluster_id": cluster_id,
        "proxy_url": proxy_data["proxy_url"],
        "services": services,
        "total_active_services": len(services)
    }

# Example usage
proxy_config = get_proxy_config("cluster_abc123")
services = get_accessible_services("cluster_abc123")

print(f"Found {services['total_active_services']} active services:")
for service in services["services"]:
    print(f"  {service['name']}: {service['url']} (Health: {service['health']})")
```

```javascript JavaScript
async function getProxyConfig(clusterId, options = {}) {
  const params = new URLSearchParams();
  
  if (options.includeHealth) {
    params.append('include_health', 'true');
  }
  if (options.includeLogs) {
    params.append('include_access_logs', 'true');
  }
  if (options.includeSsl) {
    params.append('include_ssl_info', 'true');
  }
  
  const response = await fetch(
    `https://api.tensorone.ai/v1/clusters/${clusterId}/proxy?${params}`,
    {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }
  );
  
  return await response.json();
}

// Service discovery helper
async function discoverClusterServices(clusterId) {
  const config = await getProxyConfig(clusterId, { includeHealth: true });
  
  if (!config.success) {
    throw new Error(`Failed to get proxy config: ${config.error.message}`);
  }
  
  const services = config.data.port_mappings
    .filter(mapping => mapping.status === 'active')
    .map(mapping => ({
      name: mapping.description,
      url: mapping.url,
      internalPort: mapping.internal_port,
      externalPort: mapping.external_port,
      protocol: mapping.protocol,
      health: mapping.health_status || 'unknown',
      lastAccessed: mapping.last_accessed,
      accessCount: mapping.access_count || 0
    }));
  
  return {
    clusterId: clusterId,
    proxyBaseUrl: config.data.proxy_url,
    totalServices: services.length,
    healthyServices: services.filter(s => s.health === 'healthy').length,
    services: services,
    accessControl: config.data.access_control
  };
}

// Usage
const clusterServices = await discoverClusterServices('cluster_abc123');
console.log(`Discovered ${clusterServices.totalServices} services on cluster`);

clusterServices.services.forEach(service => {
  console.log(`🌐 ${service.name}: ${service.url}`);
  console.log(`   Health: ${service.health}, Access Count: ${service.accessCount}`);
});
```

## Response Schema

```json Proxy Configuration Response
{
  "success": true,
  "data": {
    "cluster_id": "cluster_abc123",
    "proxy_url": "https://cluster-abc123.tensorone.ai",
    "proxy_status": "active",
    "ssl_certificate": {
      "issuer": "TensorOne CA",
      "valid_from": "2024-01-01T00:00:00Z",
      "valid_until": "2025-01-01T00:00:00Z",
      "status": "valid"
    },
    "port_mappings": [
      {
        "id": "port_123",
        "internal_port": 8888,
        "external_port": 32001,
        "protocol": "tcp",
        "description": "Jupyter Lab",
        "url": "https://cluster-abc123.tensorone.ai:32001",
        "status": "active",
        "health_status": "healthy",
        "health_check": {
          "enabled": true,
          "path": "/lab",
          "interval_seconds": 30,
          "timeout_seconds": 10,
          "last_check": "2024-01-15T16:45:00Z",
          "consecutive_failures": 0
        },
        "access_control": {
          "authentication_required": true,
          "allowed_users": ["ml_engineer", "data_scientist"],
          "ip_whitelist": ["203.0.113.0/24"],
          "rate_limit": {
            "requests_per_minute": 100,
            "burst_size": 20
          }
        },
        "usage_statistics": {
          "total_requests": 1247,
          "unique_visitors": 8,
          "last_accessed": "2024-01-15T16:30:00Z",
          "avg_response_time_ms": 245
        },
        "created_at": "2024-01-15T14:30:00Z",
        "updated_at": "2024-01-15T16:00:00Z"
      },
      {
        "id": "port_124",
        "internal_port": 6006,
        "external_port": 32002,
        "protocol": "tcp",
        "description": "TensorBoard",
        "url": "https://cluster-abc123.tensorone.ai:32002",
        "status": "active",
        "health_status": "healthy",
        "health_check": {
          "enabled": true,
          "path": "/",
          "interval_seconds": 60,
          "timeout_seconds": 15,
          "last_check": "2024-01-15T16:44:00Z",
          "consecutive_failures": 0
        },
        "access_control": {
          "authentication_required": false,
          "public_access": true
        },
        "usage_statistics": {
          "total_requests": 456,
          "unique_visitors": 12,
          "last_accessed": "2024-01-15T16:25:00Z",
          "avg_response_time_ms": 180
        },
        "created_at": "2024-01-15T14:35:00Z"
      }
    ],
    "access_control": {
      "default_authentication": true,
      "session_timeout_minutes": 480,
      "max_concurrent_sessions": 10,
      "ip_whitelist": ["203.0.113.0/24", "198.51.100.0/24"],
      "blocked_ips": [],
      "rate_limiting": {
        "global_limit": {
          "requests_per_minute": 1000,
          "burst_size": 100
        },
        "per_user_limit": {
          "requests_per_minute": 200,
          "burst_size": 50
        }
      }
    },
    "network_configuration": {
      "load_balancer": {
        "enabled": true,
        "algorithm": "round_robin",
        "health_check_enabled": true
      },
      "ssl_termination": "proxy",
      "websocket_support": true,
      "compression": {
        "enabled": true,
        "algorithms": ["gzip", "br"]
      }
    },
    "access_logs": [
      {
        "timestamp": "2024-01-15T16:30:15Z",
        "client_ip": "203.0.113.42",
        "user": "ml_engineer",
        "method": "GET",
        "path": "/lab/tree",
        "status_code": 200,
        "response_time_ms": 156,
        "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
      }
    ]
  },
  "meta": {
    "last_updated": "2024-01-15T16:45:00Z",
    "total_port_mappings": 2,
    "active_port_mappings": 2,
    "proxy_version": "2.1.0"
  }
}
```

## Create Port Mapping

### Request Body

| Parameter | Type | Required | Description |
| - | - | - | - |
| `internal_port` | integer | Yes | Internal port number (1-65535) |
| `external_port` | integer | No | External port number (auto-assigned if not specified) |
| `protocol` | string | No | Protocol: `tcp`, `udp` (default: `tcp`) |
| `description` | string | Yes | Human-readable description of the service |
| `health_check` | object | No | Health check configuration |
| `access_control` | object | No | Access control settings |
| `custom_domain` | string | No | Custom domain for the service |

### Request Examples

```bash curl
# Create Jupyter Lab port mapping
curl -X POST "https://api.tensorone.ai/v1/clusters/cluster_abc123/proxy/ports" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "internal_port": 8888,
    "description": "Jupyter Lab Interface",
    "health_check": {
      "enabled": true,
      "path": "/lab",
      "interval_seconds": 30
    },
    "access_control": {
      "authentication_required": true,
      "allowed_users": ["ml_engineer", "data_scientist"]
    }
  }'

# Create API endpoint with custom domain
curl -X POST "https://api.tensorone.ai/v1/clusters/cluster_abc123/proxy/ports" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "internal_port": 8000,
    "external_port": 443,
    "description": "ML Model API",
    "custom_domain": "api.ml-project.com",
    "health_check": {
      "enabled": true,
      "path": "/health",
      "interval_seconds": 15,
      "timeout_seconds": 5
    },
    "access_control": {
      "authentication_required": false,
      "rate_limit": {
        "requests_per_minute": 500,
        "burst_size": 100
      }
    }
  }'
```

```python Python
def create_port_mapping(cluster_id, port_config):
    """Create a new port mapping for cluster services"""
    
    response = requests.post(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/proxy/ports",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json=port_config
    )
    
    return response.json()

def setup_ml_services(cluster_id):
    """Set up common ML service port mappings"""
    
    services = [
        {
            "name": "Jupyter Lab",
            "internal_port": 8888,
            "description": "Interactive Jupyter Lab environment",
            "health_check": {
                "enabled": True,
                "path": "/lab",
                "interval_seconds": 30,
                "timeout_seconds": 10
            },
            "access_control": {
                "authentication_required": True,
                "allowed_users": ["ml_engineer", "data_scientist", "researcher"]
            }
        },
        {
            "name": "TensorBoard",
            "internal_port": 6006,
            "description": "TensorBoard visualization dashboard",
            "health_check": {
                "enabled": True,
                "path": "/",
                "interval_seconds": 60,
                "timeout_seconds": 15
            },
            "access_control": {
                "authentication_required": False,
                "public_access": True
            }
        },
        {
            "name": "MLflow UI",
            "internal_port": 5000,
            "description": "MLflow experiment tracking interface",
            "health_check": {
                "enabled": True,
                "path": "/health",
                "interval_seconds": 45
            },
            "access_control": {
                "authentication_required": True,
                "allowed_users": ["ml_engineer", "data_scientist"]
            }
        },
        {
            "name": "Model API",
            "internal_port": 8000,
            "description": "REST API for model inference",
            "health_check": {
                "enabled": True,
                "path": "/health",
                "interval_seconds": 15,
                "timeout_seconds": 5,
                "expected_status": 200
            },
            "access_control": {
                "authentication_required": False,
                "rate_limit": {
                    "requests_per_minute": 300,
                    "burst_size": 50
                },
                "ip_whitelist": ["203.0.113.0/24"]  # Allow only from specific network
            }
        }
    ]
    
    created_mappings = []
    
    for service in services:
        print(f"Creating port mapping for {service['name']}...")
        
        # Extract service-specific config
        config = {
            "internal_port": service["internal_port"],
            "description": service["description"],
            "health_check": service["health_check"],
            "access_control": service["access_control"]
        }
        
        result = create_port_mapping(cluster_id, config)
        
        if result["success"]:
            mapping_info = result["data"]
            created_mappings.append({
                "service_name": service["name"],
                "internal_port": service["internal_port"],
                "external_port": mapping_info["external_port"],
                "url": mapping_info["url"],
                "status": mapping_info["status"]
            })
            print(f"✅ {service['name']} available at: {mapping_info['url']}")
        else:
            print(f"❌ Failed to create {service['name']}: {result['error']['message']}")
    
    return created_mappings

def setup_development_environment(cluster_id, user_preferences):
    """Set up personalized development environment ports"""
    
    dev_services = []
    
    # Jupyter Lab (always included)
    jupyter_config = {
        "internal_port": 8888,
        "description": f"Jupyter Lab for {user_preferences.get('username', 'user')}",
        "health_check": {
            "enabled": True,
            "path": "/lab",
            "interval_seconds": 30
        },
        "access_control": {
            "authentication_required": True,
            "allowed_users": [user_preferences.get("username")]
        }
    }
    
    dev_services.append(("Jupyter Lab", jupyter_config))
    
    # VSCode Server (if requested)
    if user_preferences.get("include_vscode", False):
        vscode_config = {
            "internal_port": 8080,
            "description": "VSCode Server",
            "health_check": {
                "enabled": True,
                "path": "/",
                "interval_seconds": 45
            },
            "access_control": {
                "authentication_required": True,
                "allowed_users": [user_preferences.get("username")]
            }
        }
        dev_services.append(("VSCode Server", vscode_config))
    
    # Custom application port (if specified)
    if user_preferences.get("custom_app_port"):
        custom_config = {
            "internal_port": user_preferences["custom_app_port"],
            "description": user_preferences.get("custom_app_description", "Custom Application"),
            "health_check": {
                "enabled": user_preferences.get("custom_health_check", False),
                "path": user_preferences.get("custom_health_path", "/"),
                "interval_seconds": 60
            },
            "access_control": {
                "authentication_required": user_preferences.get("custom_auth_required", True),
                "allowed_users": [user_preferences.get("username")]
            }
        }
        dev_services.append(("Custom Application", custom_config))
    
    # Create all port mappings
    created_services = []
    for service_name, config in dev_services:
        result = create_port_mapping(cluster_id, config)
        if result["success"]:
            created_services.append({
                "name": service_name,
                "url": result["data"]["url"],
                "port": result["data"]["external_port"]
            })
    
    return created_services

# Example usage
# Set up standard ML services
ml_services = setup_ml_services("cluster_abc123")
print(f"Created {len(ml_services)} ML service mappings")

# Set up personalized development environment
user_prefs = {
    "username": "ml_engineer",
    "include_vscode": True,
    "custom_app_port": 3000,
    "custom_app_description": "React Development Server",
    "custom_health_check": True,
    "custom_health_path": "/",
    "custom_auth_required": True
}

dev_services = setup_development_environment("cluster_dev_001", user_prefs)
print(f"Development environment ready with {len(dev_services)} services")
```

```javascript JavaScript
async function createPortMapping(clusterId, config) {
  const response = await fetch(
    `https://api.tensorone.ai/v1/clusters/${clusterId}/proxy/ports`,
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(config)
    }
  );
  
  return await response.json();
}

// Advanced service setup with monitoring
class ServiceManager {
  constructor(clusterId) {
    this.clusterId = clusterId;
    this.services = new Map();
  }
  
  async setupProductionAPI(apiConfig) {
    console.log('Setting up production API with advanced configuration...');
    
    const config = {
      internal_port: apiConfig.port || 8000,
      description: apiConfig.description || 'Production API',
      health_check: {
        enabled: true,
        path: apiConfig.healthPath || '/health',
        interval_seconds: 15,
        timeout_seconds: 5,
        expected_status: 200,
        retries: 3
      },
      access_control: {
        authentication_required: apiConfig.requireAuth !== false,
        rate_limit: {
          requests_per_minute: apiConfig.rateLimit || 1000,
          burst_size: apiConfig.burstSize || 200
        },
        ip_whitelist: apiConfig.allowedIPs || [],
        cors: {
          enabled: true,
          allowed_origins: apiConfig.corsOrigins || ['*'],
          allowed_methods: ['GET', 'POST', 'PUT', 'DELETE'],
          allowed_headers: ['Content-Type', 'Authorization']
        }
      },
      custom_domain: apiConfig.customDomain,
      ssl_redirect: true,
      compression: {
        enabled: true,
        level: 6,
        types: ['application/json', 'text/plain', 'text/html']
      }
    };
    
    const result = await createPortMapping(this.clusterId, config);
    
    if (result.success) {
      this.services.set('production_api', {
        name: 'Production API',
        url: result.data.url,
        port: result.data.external_port,
        health_endpoint: `${result.data.url}${config.health_check.path}`,
        config: config
      });
      
      console.log(`✅ Production API available at: ${result.data.url}`);
      
      // Set up monitoring
      await this.setupHealthMonitoring('production_api');
      
      return result.data;
    } else {
      throw new Error(`Failed to setup production API: ${result.error.message}`);
    }
  }
  
  async setupDevelopmentServices(devConfig) {
    console.log('Setting up development services...');
    
    const services = [
      {
        key: 'jupyter',
        name: 'Jupyter Lab',
        internal_port: 8888,
        description: 'Interactive development environment',
        health_path: '/lab',
        auth_required: true
      },
      {
        key: 'tensorboard',
        name: 'TensorBoard',
        internal_port: 6006,
        description: 'Training visualization dashboard',
        health_path: '/',
        auth_required: false
      }
    ];
    
    // Add optional services based on config
    if (devConfig.includeVSCode) {
      services.push({
        key: 'vscode',
        name: 'VSCode Server',
        internal_port: 8080,
        description: 'Web-based code editor',
        health_path: '/',
        auth_required: true
      });
    }
    
    if (devConfig.streamlitPort) {
      services.push({
        key: 'streamlit',
        name: 'Streamlit App',
        internal_port: devConfig.streamlitPort,
        description: 'Streamlit web application',
        health_path: '/',
        auth_required: devConfig.streamlitAuth !== false
      });
    }
    
    const setupPromises = services.map(async (service) => {
      const config = {
        internal_port: service.internal_port,
        description: service.description,
        health_check: {
          enabled: true,
          path: service.health_path,
          interval_seconds: 30,
          timeout_seconds: 10
        },
        access_control: {
          authentication_required: service.auth_required,
          allowed_users: devConfig.allowedUsers || ['developer'],
          session_timeout_minutes: 480
        }
      };
      
      try {
        const result = await createPortMapping(this.clusterId, config);
        
        if (result.success) {
          this.services.set(service.key, {
            name: service.name,
            url: result.data.url,
            port: result.data.external_port,
            health_endpoint: `${result.data.url}${service.health_path}`,
            config: config
          });
          
          console.log(`✅ ${service.name} available at: ${result.data.url}`);
          return { success: true, service: service.key, url: result.data.url };
        } else {
          console.error(`❌ Failed to setup ${service.name}: ${result.error.message}`);
          return { success: false, service: service.key, error: result.error.message };
        }
      } catch (error) {
        console.error(`❌ Error setting up ${service.name}:`, error);
        return { success: false, service: service.key, error: error.message };
      }
    });
    
    const results = await Promise.all(setupPromises);
    
    const successful = results.filter(r => r.success);
    const failed = results.filter(r => !r.success);
    
    console.log(`Development setup complete: ${successful.length} services created, ${failed.length} failed`);
    
    return {
      successful: successful.map(r => ({ service: r.service, url: r.url })),
      failed: failed.map(r => ({ service: r.service, error: r.error })),
      totalServices: this.services.size
    };
  }
  
  async setupHealthMonitoring(serviceKey) {
    const service = this.services.get(serviceKey);
    if (!service || !service.health_endpoint) {
      console.warn(`No health endpoint configured for service: ${serviceKey}`);
      return;
    }
    
    console.log(`Setting up health monitoring for ${service.name}...`);
    
    const checkHealth = async () => {
      try {
        const response = await fetch(service.health_endpoint, {
          method: 'GET',
          timeout: 10000
        });
        
        const isHealthy = response.ok;
        const responseTime = Date.now() - startTime;
        
        // Update service status
        service.lastHealthCheck = {
          timestamp: new Date().toISOString(),
          healthy: isHealthy,
          responseTime: responseTime,
          statusCode: response.status
        };
        
        if (!isHealthy) {
          console.warn(`⚠️  Health check failed for ${service.name}: ${response.status}`);
        }
        
        return isHealthy;
      } catch (error) {
        console.error(`❌ Health check error for ${service.name}:`, error.message);
        service.lastHealthCheck = {
          timestamp: new Date().toISOString(),
          healthy: false,
          error: error.message
        };
        return false;
      }
    };
    
    // Initial health check
    const startTime = Date.now();
    await checkHealth();
    
    // Set up periodic health checks
    const healthCheckInterval = setInterval(checkHealth, 60000); // Check every minute
    
    service.healthCheckInterval = healthCheckInterval;
    
    return healthCheckInterval;
  }
  
  async getServiceStatus() {
    const status = {
      clusterId: this.clusterId,
      totalServices: this.services.size,
      services: []
    };
    
    for (const [key, service] of this.services) {
      status.services.push({
        key: key,
        name: service.name,
        url: service.url,
        port: service.port,
        lastHealthCheck: service.lastHealthCheck || null,
        healthy: service.lastHealthCheck?.healthy ?? 'unknown'
      });
    }
    
    return status;
  }
  
  async cleanup() {
    console.log('Cleaning up service monitoring...');
    
    for (const [key, service] of this.services) {
      if (service.healthCheckInterval) {
        clearInterval(service.healthCheckInterval);
      }
    }
    
    this.services.clear();
  }
}

// Usage examples
async function setupMLTrainingEnvironment(clusterId) {
  const serviceManager = new ServiceManager(clusterId);
  
  // Setup development services
  const devResult = await serviceManager.setupDevelopmentServices({
    includeVSCode: true,
    streamlitPort: 8501,
    streamlitAuth: false,
    allowedUsers: ['ml_engineer', 'data_scientist']
  });
  
  console.log('Development services ready:', devResult.successful);
  
  // Setup production API for model serving
  const apiConfig = {
    port: 8000,
    description: 'ML Model Inference API',
    healthPath: '/health',
    requireAuth: false,
    rateLimit: 500,
    burstSize: 100,
    allowedIPs: ['203.0.113.0/24'],
    corsOrigins: ['https://ml-dashboard.company.com'],
    customDomain: 'api.ml-model.company.com'
  };
  
  await serviceManager.setupProductionAPI(apiConfig);
  
  // Monitor service health
  setTimeout(async () => {
    const status = await serviceManager.getServiceStatus();
    console.log('Service Health Status:', status);
  }, 5000);
  
  return serviceManager;
}

// Setup complete ML environment
const serviceManager = await setupMLTrainingEnvironment('cluster_ml_001');

// Cleanup after use
process.on('exit', () => {
  serviceManager.cleanup();
});
```

## Update Port Mapping

```bash curl
# Update port mapping configuration
curl -X PUT "https://api.tensorone.ai/v1/clusters/cluster_abc123/proxy/ports/port_123" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "description": "Updated Jupyter Lab Environment",
    "health_check": {
      "enabled": true,
      "path": "/lab/tree",
      "interval_seconds": 15,
      "timeout_seconds": 8
    },
    "access_control": {
      "authentication_required": true,
      "allowed_users": ["ml_engineer", "data_scientist", "researcher"],
      "rate_limit": {
        "requests_per_minute": 150,
        "burst_size": 30
      }
    }
  }'
```

```python Python
def update_port_mapping(cluster_id, port_id, updates):
    """Update existing port mapping configuration"""
    
    response = requests.put(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/proxy/ports/{port_id}",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json=updates
    )
    
    return response.json()

def scale_service_access(cluster_id, service_mappings, traffic_multiplier=2.0):
    """Scale service access limits based on expected traffic"""
    
    results = []
    
    for mapping in service_mappings:
        current_limit = mapping.get("access_control", {}).get("rate_limit", {}).get("requests_per_minute", 100)
        new_limit = int(current_limit * traffic_multiplier)
        
        updates = {
            "access_control": {
                **mapping.get("access_control", {}),
                "rate_limit": {
                    "requests_per_minute": new_limit,
                    "burst_size": int(new_limit * 0.2)  # 20% burst capacity
                }
            }
        }
        
        result = update_port_mapping(cluster_id, mapping["id"], updates)
        results.append({
            "port_id": mapping["id"],
            "description": mapping["description"],
            "old_limit": current_limit,
            "new_limit": new_limit,
            "success": result["success"]
        })
    
    return results
```

## Access Control Configuration

```bash curl
# Configure cluster-wide access control
curl -X PUT "https://api.tensorone.ai/v1/clusters/cluster_abc123/proxy/access" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "default_authentication": true,
    "session_timeout_minutes": 240,
    "max_concurrent_sessions": 20,
    "ip_whitelist": ["203.0.113.0/24", "198.51.100.0/24"],
    "rate_limiting": {
      "global_limit": {
        "requests_per_minute": 2000,
        "burst_size": 500
      },
      "per_user_limit": {
        "requests_per_minute": 300,
        "burst_size": 100
      }
    },
    "security_headers": {
      "hsts_enabled": true,
      "content_security_policy": "default-src self; script-src self unsafe-inline",
      "x_frame_options": "SAMEORIGIN"
    }
  }'
```

## Use Cases

### ML Development Environment

Set up comprehensive development environment with multiple tools.

```python
def setup_comprehensive_ml_environment(cluster_id, team_config):
    """Set up a complete ML development environment"""
    
    environment_services = {
        "core_services": [
            {
                "name": "Jupyter Lab",
                "port": 8888,
                "path": "/lab",
                "priority": "high",
                "auth_required": True
            },
            {
                "name": "TensorBoard",
                "port": 6006,
                "path": "/",
                "priority": "high",
                "auth_required": False
            }
        ],
        "development_tools": [
            {
                "name": "VSCode Server",
                "port": 8080,
                "path": "/",
                "priority": "medium",
                "auth_required": True
            },
            {
                "name": "MLflow UI",
                "port": 5000,
                "path": "/",
                "priority": "medium",
                "auth_required": True
            }
        ],
        "monitoring_services": [
            {
                "name": "Prometheus Metrics",
                "port": 9090,
                "path": "/metrics",
                "priority": "low",
                "auth_required": True
            },
            {
                "name": "Grafana Dashboard",
                "port": 3000,
                "path": "/",
                "priority": "low",
                "auth_required": True
            }
        ]
    }
    
    setup_results = {
        "cluster_id": cluster_id,
        "team": team_config["team_name"],
        "services_created": [],
        "services_failed": [],
        "access_summary": {}
    }
    
    # Create services by priority
    for category, services in environment_services.items():
        print(f"\nSetting up {category}...")
        
        for service in services:
            config = {
                "internal_port": service["port"],
                "description": f"{service['name']} for {team_config['team_name']} team",
                "health_check": {
                    "enabled": True,
                    "path": service["path"],
                    "interval_seconds": 30 if service["priority"] == "high" else 60,
                    "timeout_seconds": 10
                },
                "access_control": {
                    "authentication_required": service["auth_required"],
                    "allowed_users": team_config.get("team_members", []),
                    "session_timeout_minutes": 480,  # 8 hours
                    "rate_limit": {
                        "requests_per_minute": 200 if service["priority"] == "high" else 100,
                        "burst_size": 50 if service["priority"] == "high" else 25
                    }
                }
            }
            
            result = create_port_mapping(cluster_id, config)
            
            if result["success"]:
                service_info = {
                    "name": service["name"],
                    "category": category,
                    "url": result["data"]["url"],
                    "port": result["data"]["external_port"],
                    "priority": service["priority"],
                    "auth_required": service["auth_required"]
                }
                setup_results["services_created"].append(service_info)
                print(f"✅ {service['name']}: {result['data']['url']}")
            else:
                setup_results["services_failed"].append({
                    "name": service["name"],
                    "error": result["error"]["message"]
                })
                print(f"❌ Failed to create {service['name']}: {result['error']['message']}")
    
    # Generate access summary for team
    setup_results["access_summary"] = {
        "total_services": len(setup_results["services_created"]),
        "authenticated_services": len([s for s in setup_results["services_created"] if s["auth_required"]]),
        "public_services": len([s for s in setup_results["services_created"] if not s["auth_required"]]),
        "team_access_urls": {s["name"]: s["url"] for s in setup_results["services_created"]}
    }
    
    return setup_results

# Example team configuration
team_config = {
    "team_name": "ML Research Team",
    "team_members": ["alice_researcher", "bob_engineer", "carol_scientist"],
    "project_focus": "NLP Research",
    "security_level": "standard"
}

# Set up environment
ml_environment = setup_comprehensive_ml_environment("cluster_research_001", team_config)

print(f"\n🎉 ML Environment Setup Complete!")
print(f"Created {ml_environment['access_summary']['total_services']} services for {team_config['team_name']}")
print("\nQuick Access URLs:")
for service_name, url in ml_environment["access_summary"]["team_access_urls"].items():
    print(f"  {service_name}: {url}")
```

### Production Model Serving

Set up production-ready model serving infrastructure.

```javascript
class ProductionModelServer {
  constructor(clusterId, modelConfig) {
    this.clusterId = clusterId;
    this.modelConfig = modelConfig;
    this.services = new Map();
  }
  
  async deployModel() {
    console.log(`Deploying ${this.modelConfig.name} model to production...`);
    
    // Main API endpoint
    const apiConfig = {
      internal_port: this.modelConfig.apiPort || 8000,
      description: `${this.modelConfig.name} Model API`,
      health_check: {
        enabled: true,
        path: '/health',
        interval_seconds: 10,
        timeout_seconds: 5,
        expected_status: 200,
        retries: 3
      },
      access_control: {
        authentication_required: this.modelConfig.requireAuth !== false,
        rate_limit: {
          requests_per_minute: this.modelConfig.rateLimit || 1000,
          burst_size: this.modelConfig.burstSize || 200
        },
        ip_whitelist: this.modelConfig.allowedIPs || [],
        cors: {
          enabled: true,
          allowed_origins: this.modelConfig.corsOrigins || ['*'],
          allowed_methods: ['GET', 'POST'],
          allowed_headers: ['Content-Type', 'Authorization']
        }
      },
      custom_domain: this.modelConfig.customDomain,
      ssl_redirect: true
    };
    
    const apiResult = await createPortMapping(this.clusterId, apiConfig);
    
    if (!apiResult.success) {
      throw new Error(`Failed to create API endpoint: ${apiResult.error.message}`);
    }
    
    this.services.set('api', {
      name: 'Model API',
      url: apiResult.data.url,
      port: apiResult.data.external_port,
      type: 'api'
    });
    
    // Metrics endpoint
    if (this.modelConfig.enableMetrics !== false) {
      const metricsConfig = {
        internal_port: this.modelConfig.metricsPort || 9090,
        description: `${this.modelConfig.name} Model Metrics`,
        health_check: {
          enabled: true,
          path: '/metrics',
          interval_seconds: 30
        },
        access_control: {
          authentication_required: true,
          allowed_users: ['ops_team', 'ml_engineer'],
          ip_whitelist: this.modelConfig.monitoringIPs || []
        }
      };
      
      const metricsResult = await createPortMapping(this.clusterId, metricsConfig);
      
      if (metricsResult.success) {
        this.services.set('metrics', {
          name: 'Model Metrics',
          url: metricsResult.data.url,
          port: metricsResult.data.external_port,
          type: 'monitoring'
        });
      }
    }
    
    // Admin dashboard (if enabled)
    if (this.modelConfig.enableDashboard) {
      const dashboardConfig = {
        internal_port: this.modelConfig.dashboardPort || 8080,
        description: `${this.modelConfig.name} Admin Dashboard`,
        health_check: {
          enabled: true,
          path: '/dashboard',
          interval_seconds: 60
        },
        access_control: {
          authentication_required: true,
          allowed_users: ['admin', 'ml_engineer'],
          session_timeout_minutes: 120
        }
      };
      
      const dashboardResult = await createPortMapping(this.clusterId, dashboardConfig);
      
      if (dashboardResult.success) {
        this.services.set('dashboard', {
          name: 'Admin Dashboard',
          url: dashboardResult.data.url,
          port: dashboardResult.data.external_port,
          type: 'admin'
        });
      }
    }
    
    console.log(`✅ Model deployment complete for ${this.modelConfig.name}`);
    return this.getDeploymentSummary();
  }
  
  async setupLoadBalancing() {
    if (this.modelConfig.replicas && this.modelConfig.replicas > 1) {
      console.log(`Setting up load balancing for ${this.modelConfig.replicas} replicas...`);
      
      // Configure load balancer settings
      const lbConfig = {
        algorithm: 'round_robin',
        health_check_enabled: true,
        health_check_path: '/health',
        session_affinity: false,
        timeout_seconds: 30,
        retries: 3
      };
      
      // Update the main API service with load balancing
      const apiService = this.services.get('api');
      if (apiService) {
        const updateConfig = {
          load_balancer: lbConfig,
          scaling: {
            min_replicas: 1,
            max_replicas: this.modelConfig.replicas,
            target_cpu_utilization: 70,
            target_memory_utilization: 80
          }
        };
        
        // Note: This would update the existing port mapping
        // Implementation depends on the specific load balancing API
        console.log('Load balancing configured for API endpoint');
      }
    }
  }
  
  async setupMonitoring() {
    console.log('Setting up comprehensive monitoring...');
    
    const monitoringServices = [];
    
    // Health check monitoring
    const healthMonitor = setInterval(async () => {
      for (const [key, service] of this.services) {
        if (service.type === 'api') {
          try {
            const response = await fetch(`${service.url}/health`, {
              method: 'GET',
              timeout: 5000
            });
            
            const isHealthy = response.ok;
            const timestamp = new Date().toISOString();
            
            if (!isHealthy) {
              console.warn(`⚠️  API health check failed: ${service.url} (${response.status})`);
              // Could trigger alerts here
            }
            
            service.lastHealthCheck = { timestamp, healthy: isHealthy, status: response.status };
          } catch (error) {
            console.error(`❌ Health check error for ${service.name}:`, error.message);
            service.lastHealthCheck = { timestamp: new Date().toISOString(), healthy: false, error: error.message };
          }
        }
      }
    }, 30000); // Check every 30 seconds
    
    monitoringServices.push(healthMonitor);
    
    // Performance monitoring (if metrics endpoint exists)
    const metricsService = this.services.get('metrics');
    if (metricsService) {
      const performanceMonitor = setInterval(async () => {
        try {
          const response = await fetch(`${metricsService.url}/metrics`);
          if (response.ok) {
            const metrics = await response.text();
            // Parse and analyze metrics
            this.analyzePerformanceMetrics(metrics);
          }
        } catch (error) {
          console.error('Error fetching performance metrics:', error.message);
        }
      }, 60000); // Check every minute
      
      monitoringServices.push(performanceMonitor);
    }
    
    this.monitoringServices = monitoringServices;
    return monitoringServices.length;
  }
  
  analyzePerformanceMetrics(metricsText) {
    // Simple metrics analysis
    const lines = metricsText.split('\n');
    const metrics = {};
    
    lines.forEach(line => {
      if (line.startsWith('http_requests_total')) {
        const match = line.match(/http_requests_total{.*?} (\d+)/);
        if (match) metrics.totalRequests = parseInt(match[1]);
      } else if (line.startsWith('http_request_duration_seconds')) {
        const match = line.match(/http_request_duration_seconds{.*?} ([0-9.]+)/);
        if (match) metrics.avgResponseTime = parseFloat(match[1]);
      }
    });
    
    // Simple alerting logic
    if (metrics.avgResponseTime && metrics.avgResponseTime > 2.0) {
      console.warn(`⚠️  High response time detected: ${metrics.avgResponseTime}s`);
    }
    
    if (metrics.totalRequests && this.lastRequestCount) {
      const requestRate = (metrics.totalRequests - this.lastRequestCount) / 60; // per second
      if (requestRate > this.modelConfig.alertThresholds?.maxRequestsPerSecond || 100) {
        console.warn(`⚠️  High request rate: ${requestRate} req/s`);
      }
    }
    
    this.lastRequestCount = metrics.totalRequests;
  }
  
  getDeploymentSummary() {
    const summary = {
      modelName: this.modelConfig.name,
      clusterId: this.clusterId,
      deploymentTime: new Date().toISOString(),
      services: {},
      endpoints: {},
      configuration: {
        authentication: this.modelConfig.requireAuth !== false,
        rateLimit: this.modelConfig.rateLimit || 1000,
        customDomain: this.modelConfig.customDomain || null,
        replicas: this.modelConfig.replicas || 1
      }
    };
    
    for (const [key, service] of this.services) {
      summary.services[key] = {
        name: service.name,
        type: service.type,
        url: service.url,
        port: service.port
      };
      
      summary.endpoints[service.name] = service.url;
    }
    
    return summary;
  }
  
  async cleanup() {
    console.log('Cleaning up monitoring services...');
    
    if (this.monitoringServices) {
      this.monitoringServices.forEach(service => {
        if (typeof service === 'number') {
          clearInterval(service);
        }
      });
    }
    
    this.services.clear();
  }
}

// Usage example
async function deployProductionModel() {
  const modelConfig = {
    name: 'GPT-3.5 Fine-tuned',
    apiPort: 8000,
    metricsPort: 9090,
    dashboardPort: 8080,
    requireAuth: true,
    rateLimit: 500,
    burstSize: 100,
    enableMetrics: true,
    enableDashboard: true,
    replicas: 3,
    customDomain: 'api.gpt-model.company.com',
    allowedIPs: ['203.0.113.0/24'],
    corsOrigins: ['https://app.company.com'],
    monitoringIPs: ['198.51.100.0/24'],
    alertThresholds: {
      maxRequestsPerSecond: 50,
      maxResponseTimeSeconds: 2.0
    }
  };
  
  const modelServer = new ProductionModelServer('cluster_prod_001', modelConfig);
  
  try {
    // Deploy the model services
    const deployment = await modelServer.deployModel();
    console.log('Deployment Summary:', deployment);
    
    // Set up load balancing
    await modelServer.setupLoadBalancing();
    
    // Start monitoring
    const monitoringCount = await modelServer.setupMonitoring();
    console.log(`Started ${monitoringCount} monitoring services`);
    
    return modelServer;
  } catch (error) {
    console.error('Deployment failed:', error);
    await modelServer.cleanup();
    throw error;
  }
}

// Deploy the model
const productionModel = await deployProductionModel();

// Cleanup on exit
process.on('exit', () => {
  productionModel.cleanup();
});
```

## Error Handling

```json Port Already in Use
{
  "success": false,
  "error": {
    "code": "PORT_ALREADY_MAPPED",
    "message": "Internal port 8888 is already mapped",
    "details": {
      "internal_port": 8888,
      "existing_mapping_id": "port_456",
      "existing_description": "Existing Jupyter Lab",
      "suggestion": "Use a different internal port or update the existing mapping"
    }
  }
}
```

```json Invalid Health Check
{
  "success": false,
  "error": {
    "code": "INVALID_HEALTH_CHECK",
    "message": "Health check configuration is invalid",
    "details": {
      "path": "/invalid-path",
      "error": "Health check path returned 404",
      "suggestion": "Verify the health check path is accessible"
    }
  }
}
```

```json Access Control Error
{
  "success": false,
  "error": {
    "code": "ACCESS_CONTROL_ERROR",
    "message": "Invalid access control configuration",
    "details": {
      "allowed_users": ["invalid_user"],
      "error": "User 'invalid_user' does not exist",
      "suggestion": "Verify all users exist in the system"
    }
  }
}
```

## Security Considerations

* **HTTPS Only**: All proxy connections use HTTPS with valid SSL certificates
* **Authentication**: Implement proper authentication for sensitive services
* **Rate Limiting**: Configure appropriate rate limits to prevent abuse
* **IP Whitelisting**: Restrict access to trusted IP ranges when possible
* **Session Management**: Use secure session timeouts and proper session handling

## Best Practices

1. **Service Organization**: Use descriptive names and organize services logically
2. **Health Monitoring**: Implement comprehensive health checks for all services
3. **Access Control**: Apply principle of least privilege for service access
4. **Performance Monitoring**: Monitor service performance and response times
5. **SSL/TLS**: Always use HTTPS for production services
6. **Load Balancing**: Implement load balancing for high-availability services


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.