CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-azure-mgmt-iothub

Microsoft Azure IoT Hub Management Client Library for programmatic management of Azure IoT Hub resources through the Azure Resource Manager API

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

monitoring-quotas.mddocs/

Monitoring & Quotas

Comprehensive monitoring capabilities including IoT Hub quota management, usage metrics, endpoint health monitoring, and subscription-level quota tracking for capacity planning and operational oversight of IoT Hub deployments at scale.

Capabilities

IoT Hub Quota Metrics

Monitor IoT Hub resource usage against configured limits including message quotas, device limits, and feature-specific usage for capacity planning and threshold management.

def get_quota_metrics(resource_group_name: str, resource_name: str, **kwargs) -> ItemPaged[IotHubQuotaMetricInfo]:
    """
    Get quota usage metrics for the IoT hub including message limits and device counts.
    
    Args:
        resource_group_name: Name of the resource group
        resource_name: Name of the IoT hub resource
        
    Returns:
        ItemPaged[IotHubQuotaMetricInfo]: Paginated quota metrics with current usage and limits
    """

SKU and Capacity Information

Retrieve available pricing tiers and capacity options for IoT Hub scaling and cost optimization decisions.

def get_valid_skus(resource_group_name: str, resource_name: str, **kwargs) -> ItemPaged[IotHubSkuDescription]:
    """
    Get valid SKU options available for the IoT hub for scaling operations.
    
    Args:
        resource_group_name: Name of the resource group
        resource_name: Name of the IoT hub resource
        
    Returns:
        ItemPaged[IotHubSkuDescription]: Available SKU tiers with capacity and pricing information
    """

Endpoint Health Monitoring

Monitor the health status of routing endpoints including Event Hubs, Service Bus, and Storage endpoints to ensure reliable message delivery and identify connectivity issues.

def get_endpoint_health(resource_group_name: str, iot_hub_name: str, **kwargs) -> Iterable[EndpointHealthData]:
    """
    Get health status of all routing endpoints configured for the IoT hub.
    
    Args:
        resource_group_name: Name of the resource group
        iot_hub_name: Name of the IoT hub resource
        
    Returns:
        Iterable[EndpointHealthData]: Health status for each endpoint with error details and timestamps
    """

Subscription Quota Management

Monitor subscription-level quotas and limits for IoT Hub services to understand regional capacity constraints and plan multi-hub deployments.

def get_subscription_quota() -> UserSubscriptionQuotaListResult:
    """
    Get subscription quota information for IoT Hub services.
    
    Returns:
        UserSubscriptionQuotaListResult: Subscription-level quotas and usage limits for IoT Hub deployment
    """

Usage Examples

Monitoring IoT Hub quotas and usage

from azure.identity import DefaultAzureCredential
from azure.mgmt.iothub import IotHubClient

# Initialize client
credential = DefaultAzureCredential()
client = IotHubClient(credential, "subscription-id")

resource_group = "myResourceGroup"
hub_name = "myIoTHub"

# Get comprehensive quota metrics
print(f"IoT Hub Quota Metrics for {hub_name}:")
print("=" * 50)

quota_metrics = client.iot_hub_resource.get_quota_metrics(resource_group, hub_name)
for metric in quota_metrics:
    usage_percentage = (metric.current_value / metric.max_value * 100) if metric.max_value > 0 else 0
    
    print(f"Metric: {metric.name}")
    print(f"  Current Usage: {metric.current_value:,}")
    print(f"  Maximum Limit: {metric.max_value:,}")
    print(f"  Usage Percentage: {usage_percentage:.1f}%")
    
    # Alert on high usage
    if usage_percentage > 80:
        print(f"  ⚠️  HIGH USAGE WARNING: {usage_percentage:.1f}%")
    elif usage_percentage > 90:
        print(f"  🚨 CRITICAL USAGE ALERT: {usage_percentage:.1f}%")
    
    print()

# Check subscription-level quotas
print("Subscription Quota Information:")
print("=" * 40)
try:
    subscription_quotas = client.resource_provider_common.get_subscription_quota()
    for quota in subscription_quotas.value:
        print(f"Quota Type: {quota.name}")
        print(f"  Limit: {quota.limit}")
        print(f"  Current Usage: {quota.current_value}")
        if quota.unit:
            print(f"  Unit: {quota.unit}")
        print()
except Exception as e:
    print(f"Could not retrieve subscription quotas: {e}")

SKU analysis and scaling recommendations

def analyze_sku_options(resource_group: str, hub_name: str):
    """Analyze available SKUs and provide scaling recommendations."""
    
    print(f"SKU Analysis for {hub_name}:")
    print("=" * 40)
    
    # Get current hub configuration
    current_hub = client.iot_hub_resource.get(resource_group, hub_name)
    current_sku = current_hub.sku
    
    print(f"Current SKU: {current_sku.name}")
    print(f"Current Capacity: {current_sku.capacity} units")
    print(f"Current Tier: {current_sku.tier}")
    print()
    
    # Get available SKU options
    print("Available SKU Options:")
    valid_skus = client.iot_hub_resource.get_valid_skus(resource_group, hub_name)
    
    sku_recommendations = []
    for sku_info in valid_skus:
        sku = sku_info.sku
        capacity = sku_info.capacity
        
        recommendation = {
            "name": sku.name,
            "tier": sku.tier,
            "capacity": capacity.minimum if capacity else "N/A",
            "max_capacity": capacity.maximum if capacity else "N/A",
            "scale_type": capacity.scale_type if capacity else "N/A"
        }
        sku_recommendations.append(recommendation)
        
        print(f"  - {sku.name} ({sku.tier})")
        if capacity:
            print(f"    Capacity Range: {capacity.minimum} - {capacity.maximum}")
            print(f"    Scale Type: {capacity.scale_type}")
        print()
    
    return sku_recommendations

# Analyze SKU options
sku_analysis = analyze_sku_options(resource_group, hub_name)

# Provide scaling recommendations based on usage
quota_metrics = list(client.iot_hub_resource.get_quota_metrics(resource_group, hub_name))
high_usage_metrics = [m for m in quota_metrics if (m.current_value / m.max_value * 100) > 75]

if high_usage_metrics:
    print("Scaling Recommendations:")
    print("=" * 30)
    for metric in high_usage_metrics:
        usage_pct = m.current_value / m.max_value * 100
        print(f"⚠️  {metric.name}: {usage_pct:.1f}% usage")
    
    print("\nConsider upgrading to a higher SKU tier or increasing capacity units")
else:
    print("✅ Current capacity appears sufficient based on usage metrics")

Comprehensive endpoint health monitoring

def monitor_endpoint_health(resource_group: str, hub_name: str):
    """Monitor health of all routing endpoints with detailed reporting."""
    
    print(f"Endpoint Health Report for {hub_name}:")
    print("=" * 50)
    
    try:
        endpoint_health = client.iot_hub_resource.get_endpoint_health(resource_group, hub_name)
        
        healthy_endpoints = []
        unhealthy_endpoints = []
        
        for endpoint in endpoint_health:
            endpoint_info = {
                "id": endpoint.endpoint_id,
                "status": endpoint.health_status,
                "last_error": endpoint.last_known_error,
                "last_error_time": endpoint.last_known_error_time,
                "last_success": endpoint.last_successful_send_attempt_time,
                "last_attempt": endpoint.last_send_attempt_time
            }
            
            if endpoint.health_status == "Healthy":
                healthy_endpoints.append(endpoint_info)
            else:
                unhealthy_endpoints.append(endpoint_info)
            
            print(f"Endpoint: {endpoint.endpoint_id}")
            print(f"  Status: {endpoint.health_status}")
            
            if endpoint.last_known_error:
                print(f"  Last Error: {endpoint.last_known_error}")
                if endpoint.last_known_error_time:
                    print(f"  Error Time: {endpoint.last_known_error_time}")
            
            if endpoint.last_successful_send_attempt_time:
                print(f"  Last Success: {endpoint.last_successful_send_attempt_time}")
            
            if endpoint.last_send_attempt_time:
                print(f"  Last Attempt: {endpoint.last_send_attempt_time}")
            
            print()
        
        # Summary
        total_endpoints = len(healthy_endpoints) + len(unhealthy_endpoints)
        print(f"Health Summary:")
        print(f"  Total Endpoints: {total_endpoints}")
        print(f"  Healthy: {len(healthy_endpoints)}")
        print(f"  Unhealthy: {len(unhealthy_endpoints)}")
        
        if unhealthy_endpoints:
            print(f"\n🚨 Unhealthy Endpoints Requiring Attention:")
            for endpoint in unhealthy_endpoints:
                print(f"  - {endpoint['id']}: {endpoint['status']}")
                if endpoint['last_error']:
                    print(f"    Error: {endpoint['last_error']}")
        else:
            print(f"\n✅ All endpoints are healthy")
            
        return {"healthy": healthy_endpoints, "unhealthy": unhealthy_endpoints}
        
    except Exception as e:
        print(f"Failed to retrieve endpoint health: {e}")
        return None

# Monitor endpoint health
health_report = monitor_endpoint_health(resource_group, hub_name)

Automated monitoring and alerting setup

import json
from datetime import datetime, timedelta

def create_monitoring_report(resource_group: str, hub_name: str):
    """Create comprehensive monitoring report with alerts and recommendations."""
    
    report = {
        "hub_name": hub_name,
        "timestamp": datetime.utcnow().isoformat(),
        "quota_metrics": {},
        "endpoint_health": {},
        "alerts": [],
        "recommendations": []
    }
    
    # Collect quota metrics
    quota_metrics = list(client.iot_hub_resource.get_quota_metrics(resource_group, hub_name))
    for metric in quota_metrics:
        usage_pct = (metric.current_value / metric.max_value * 100) if metric.max_value > 0 else 0
        
        report["quota_metrics"][metric.name] = {
            "current": metric.current_value,
            "maximum": metric.max_value,
            "usage_percentage": usage_pct
        }
        
        # Generate alerts
        if usage_pct > 90:
            report["alerts"].append({
                "severity": "critical",
                "type": "quota_usage", 
                "metric": metric.name,
                "message": f"Critical usage: {usage_pct:.1f}%"
            })
        elif usage_pct > 80:
            report["alerts"].append({
                "severity": "warning",
                "type": "quota_usage",
                "metric": metric.name, 
                "message": f"High usage: {usage_pct:.1f}%"
            })
    
    # Collect endpoint health
    try:
        endpoint_health = list(client.iot_hub_resource.get_endpoint_health(resource_group, hub_name))
        for endpoint in endpoint_health:
            report["endpoint_health"][endpoint.endpoint_id] = {
                "status": endpoint.health_status,
                "last_error": endpoint.last_known_error,
                "last_success": endpoint.last_successful_send_attempt_time.isoformat() if endpoint.last_successful_send_attempt_time else None
            }
            
            if endpoint.health_status != "Healthy":
                report["alerts"].append({
                    "severity": "warning",
                    "type": "endpoint_health",
                    "endpoint": endpoint.endpoint_id,
                    "message": f"Endpoint unhealthy: {endpoint.health_status}"
                })
    except Exception as e:
        report["endpoint_health_error"] = str(e)
    
    # Generate recommendations
    high_usage_metrics = [name for name, data in report["quota_metrics"].items() 
                         if data["usage_percentage"] > 75]
    if high_usage_metrics:
        report["recommendations"].append({
            "type": "scaling",
            "message": "Consider upgrading SKU or increasing capacity",
            "affected_metrics": high_usage_metrics
        })
    
    unhealthy_endpoints = [endpoint for endpoint, data in report["endpoint_health"].items()
                          if data["status"] != "Healthy"]
    if unhealthy_endpoints:
        report["recommendations"].append({
            "type": "endpoint_maintenance",
            "message": "Investigate and repair unhealthy endpoints",
            "affected_endpoints": unhealthy_endpoints
        })
    
    return report

# Generate monitoring report
monitoring_report = create_monitoring_report(resource_group, hub_name)

# Save report to file
with open(f"iot_hub_monitoring_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json", "w") as f:
    json.dump(monitoring_report, f, indent=2, default=str)

# Print summary
print("Monitoring Report Summary:")
print(f"  Alerts: {len(monitoring_report['alerts'])}")
print(f"  Recommendations: {len(monitoring_report['recommendations'])}")

if monitoring_report['alerts']:
    print("\nActive Alerts:")
    for alert in monitoring_report['alerts']:
        print(f"  {alert['severity'].upper()}: {alert['message']}")

Types

IotHubQuotaMetricInfo

Quota usage information including current consumption and maximum limits for capacity planning and threshold monitoring.

class IotHubQuotaMetricInfo:
    """IoT Hub quota and usage metrics."""
    name: str           # Metric name (e.g., "TotalMessages", "TotalDeviceCount")
    current_value: int  # Current usage value
    max_value: int      # Maximum allowed value for this metric

IotHubSkuDescription

Available SKU options with capacity constraints and scaling capabilities for IoT Hub tier management.

class IotHubSkuDescription:
    """IoT Hub SKU availability and capacity information."""
    resource_type: str              # Resource type identifier
    sku: IotHubSkuInfo             # SKU details including name and tier
    capacity: IotHubCapacity       # Capacity constraints and scaling options

IotHubCapacity

Capacity configuration including minimum, maximum, and scaling type constraints for hub sizing decisions.

class IotHubCapacity:
    """IoT Hub capacity constraints."""
    minimum: int                # Minimum capacity units
    maximum: int                # Maximum capacity units  
    default: int                # Default capacity units
    scale_type: IotHubScaleType # Scaling type: Manual, Automatic, or None

EndpointHealthData

Health monitoring information for routing endpoints including status, error details, and timing information.

class EndpointHealthData:
    """Routing endpoint health status and monitoring data."""
    endpoint_id: str                              # Endpoint identifier
    health_status: EndpointHealthStatus           # Health status: Healthy, Unhealthy, Degraded, Dead, Unknown
    last_known_error: str                         # Last error message if any
    last_known_error_time: datetime               # Timestamp of last error
    last_successful_send_attempt_time: datetime   # Timestamp of last successful message send
    last_send_attempt_time: datetime              # Timestamp of last send attempt

UserSubscriptionQuotaListResult

Subscription-level quota information for IoT Hub service limits and regional capacity constraints.

class UserSubscriptionQuotaListResult:
    """Subscription quota information."""
    value: List[UserSubscriptionQuota]  # List of subscription-level quota entries
    next_link: str                      # Link to next page if paginated

UserSubscriptionQuota

Individual subscription quota entry with limit and usage information for service capacity management.

class UserSubscriptionQuota:
    """Individual subscription quota details."""
    name: str           # Quota name and identifier
    limit: int          # Maximum allowed value
    current_value: int  # Current usage against quota
    unit: str           # Unit of measurement

Install with Tessl CLI

npx tessl i tessl/pypi-azure-mgmt-iothub

docs

device-operations.md

event-hub-consumer-groups.md

failover-operations.md

index.md

message-routing.md

monitoring-quotas.md

private-networking.md

resource-management.md

security-management.md

utility-operations.md

tile.json