Microsoft Azure Service Bus Management Client Library for programmatic control of Service Bus namespaces, queues, topics, subscriptions, and authorization rules
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Standard to Premium namespace migration operations and operational monitoring through operation listings and private networking. This includes migrating existing Standard namespaces to Premium tier for enhanced performance and features, as well as monitoring Service Bus operations.
Migrate existing Standard tier namespaces to Premium tier with minimal downtime and preserved configurations.
def list(
self,
resource_group_name: str,
namespace_name: str
) -> ItemPaged[MigrationConfigProperties]:
"""List migration configurations for a namespace.
Args:
resource_group_name (str): Name of the resource group.
namespace_name (str): Name of the source namespace.
Returns:
ItemPaged[MigrationConfigProperties]: Iterable of migration configurations.
"""
def create_and_start_migration(
self,
resource_group_name: str,
namespace_name: str,
config_name: str,
parameters: MigrationConfigProperties
) -> LROPoller[MigrationConfigProperties]:
"""Create and start a migration from Standard to Premium namespace.
Args:
resource_group_name (str): Name of the resource group.
namespace_name (str): Name of the source Standard namespace.
config_name (str): Name of the migration configuration.
parameters (MigrationConfigProperties): Migration configuration parameters.
Returns:
LROPoller[MigrationConfigProperties]: Long-running operation poller for the migration.
"""
def get(
self,
resource_group_name: str,
namespace_name: str,
config_name: str
) -> MigrationConfigProperties:
"""Get migration configuration details.
Args:
resource_group_name (str): Name of the resource group.
namespace_name (str): Name of the source namespace.
config_name (str): Name of the migration configuration.
Returns:
MigrationConfigProperties: The migration configuration.
"""
def delete(
self,
resource_group_name: str,
namespace_name: str,
config_name: str
) -> None:
"""Delete a migration configuration.
Args:
resource_group_name (str): Name of the resource group.
namespace_name (str): Name of the source namespace.
config_name (str): Name of the migration configuration.
"""
def complete_migration(
self,
resource_group_name: str,
namespace_name: str,
config_name: str
) -> None:
"""Complete the migration process.
Args:
resource_group_name (str): Name of the resource group.
namespace_name (str): Name of the source namespace.
config_name (str): Name of the migration configuration.
Note:
This finalizes the migration and makes the Premium namespace the primary.
"""
def revert(
self,
resource_group_name: str,
namespace_name: str,
config_name: str
) -> None:
"""Revert a migration back to the Standard namespace.
Args:
resource_group_name (str): Name of the resource group.
namespace_name (str): Name of the source namespace.
config_name (str): Name of the migration configuration.
"""List and monitor available Service Bus management operations and their status.
def list(self) -> ItemPaged[Operation]:
"""List available Service Bus management operations.
Returns:
ItemPaged[Operation]: Iterable of available operations.
"""from azure.mgmt.servicebus import ServiceBusManagementClient
from azure.mgmt.servicebus.models import MigrationConfigProperties, SBNamespace, SBSku
from azure.identity import DefaultAzureCredential
client = ServiceBusManagementClient(DefaultAzureCredential(), subscription_id)
# First, create a Premium namespace in the same region as the Standard namespace
premium_namespace_params = SBNamespace(
location="East US", # Same location as Standard namespace
sku=SBSku(
name="Premium",
tier="Premium",
capacity=1 # 1, 2, or 4 messaging units
),
tags={"migration": "target", "tier": "premium"}
)
premium_namespace = client.namespaces.create_or_update(
resource_group_name="my-resource-group",
namespace_name="my-premium-namespace",
parameters=premium_namespace_params
)
print(f"Premium namespace created: {premium_namespace.name}")
# Configure the migration
migration_config = MigrationConfigProperties(
target_namespace="/subscriptions/{subscription-id}/resourceGroups/my-resource-group/providers/Microsoft.ServiceBus/namespaces/my-premium-namespace",
post_migration_name="my-standard-namespace-migrated"
)
# Start the migration (this is a long-running operation)
migration_poller = client.migration_configs.create_and_start_migration(
resource_group_name="my-resource-group",
namespace_name="my-standard-namespace", # Source Standard namespace
config_name="$default", # Standard configuration name
parameters=migration_config
)
print("Migration started...")
# Wait for migration to complete
migration_result = migration_poller.result()
print(f"Migration configuration: {migration_result.provisioning_state}")import time
from azure.mgmt.servicebus.models import ProvisioningStateDR
def monitor_migration_progress(resource_group_name, namespace_name, config_name="$default"):
"""Monitor the progress of a Standard to Premium migration"""
while True:
try:
migration_status = client.migration_configs.get(
resource_group_name=resource_group_name,
namespace_name=namespace_name,
config_name=config_name
)
print(f"Migration Status: {migration_status.provisioning_state}")
print(f"Target Namespace: {migration_status.target_namespace}")
print(f"Pending Operations: {migration_status.pending_replication_operations_count}")
if migration_status.provisioning_state == "Succeeded":
print("Migration preparation completed successfully!")
print("You can now complete the migration or revert if needed.")
break
elif migration_status.provisioning_state == "Failed":
print("Migration failed!")
break
else:
print("Migration in progress...")
time.sleep(30) # Wait 30 seconds before checking again
except Exception as e:
print(f"Error monitoring migration: {e}")
break
# Monitor the migration
monitor_migration_progress("my-resource-group", "my-standard-namespace")# Once migration preparation is complete, you need to complete the migration
try:
# Complete the migration - this switches traffic to the Premium namespace
client.migration_configs.complete_migration(
resource_group_name="my-resource-group",
namespace_name="my-standard-namespace",
config_name="$default"
)
print("Migration completed successfully!")
print("Traffic is now directed to the Premium namespace.")
print("The Standard namespace is renamed with the post_migration_name.")
# Verify the migration completion
migration_status = client.migration_configs.get(
resource_group_name="my-resource-group",
namespace_name="my-standard-namespace",
config_name="$default"
)
print(f"Final migration state: {migration_status.provisioning_state}")
except Exception as e:
print(f"Failed to complete migration: {e}")# If you need to revert the migration back to the Standard namespace
try:
# Revert the migration - this switches traffic back to Standard namespace
client.migration_configs.revert(
resource_group_name="my-resource-group",
namespace_name="my-standard-namespace",
config_name="$default"
)
print("Migration reverted successfully!")
print("Traffic is now directed back to the Standard namespace.")
# Check the status
migration_status = client.migration_configs.get(
resource_group_name="my-resource-group",
namespace_name="my-standard-namespace",
config_name="$default"
)
print(f"Revert state: {migration_status.provisioning_state}")
except Exception as e:
print(f"Failed to revert migration: {e}")def manage_complete_migration_lifecycle():
"""Complete migration lifecycle management"""
try:
# 1. List existing migration configurations
migrations = client.migration_configs.list(
resource_group_name="my-resource-group",
namespace_name="my-standard-namespace"
)
print("Existing migrations:")
for migration in migrations:
print(f"- Config: {migration.name}")
print(f" State: {migration.provisioning_state}")
print(f" Target: {migration.target_namespace}")
# 2. Create Premium namespace if it doesn't exist
premium_params = SBNamespace(
location="East US",
sku=SBSku(name="Premium", tier="Premium", capacity=1)
)
try:
premium_ns = client.namespaces.create_or_update(
resource_group_name="my-resource-group",
namespace_name="migration-target-premium",
parameters=premium_params
)
print(f"Premium namespace ready: {premium_ns.name}")
except Exception as e:
print(f"Premium namespace may already exist: {e}")
# 3. Start migration
migration_config = MigrationConfigProperties(
target_namespace="/subscriptions/{subscription-id}/resourceGroups/my-resource-group/providers/Microsoft.ServiceBus/namespaces/migration-target-premium",
post_migration_name="original-standard-backup"
)
migration_poller = client.migration_configs.create_and_start_migration(
resource_group_name="my-resource-group",
namespace_name="my-standard-namespace",
config_name="$default",
parameters=migration_config
)
# 4. Wait for preparation to complete
migration_result = migration_poller.result()
print(f"Migration preparation: {migration_result.provisioning_state}")
# 5. In a real scenario, you would test the Premium namespace here
# before completing the migration
# 6. Complete the migration
client.migration_configs.complete_migration(
resource_group_name="my-resource-group",
namespace_name="my-standard-namespace",
config_name="$default"
)
print("Migration completed successfully!")
# 7. Clean up migration configuration after completion
time.sleep(60) # Wait for completion to settle
client.migration_configs.delete(
resource_group_name="my-resource-group",
namespace_name="my-standard-namespace",
config_name="$default"
)
print("Migration configuration cleaned up")
except Exception as e:
print(f"Migration lifecycle error: {e}")
# Try to revert if something went wrong
try:
client.migration_configs.revert(
resource_group_name="my-resource-group",
namespace_name="my-standard-namespace",
config_name="$default"
)
print("Migration reverted due to error")
except:
print("Could not revert migration")
# Run the complete migration lifecycle
manage_complete_migration_lifecycle()# List all available Service Bus management operations
operations = client.operations.list()
print("Available Service Bus Management Operations:")
for operation in operations:
print(f"Operation: {operation.name}")
if operation.display:
print(f" Provider: {operation.display.provider}")
print(f" Resource: {operation.display.resource}")
print(f" Operation: {operation.display.operation}")
print(f" Description: {operation.display.description}")
print()
# Filter operations by category
namespace_operations = [op for op in operations if 'namespace' in op.name.lower()]
queue_operations = [op for op in operations if 'queue' in op.name.lower()]
topic_operations = [op for op in operations if 'topic' in op.name.lower()]
print(f"Namespace operations: {len(namespace_operations)}")
print(f"Queue operations: {len(queue_operations)}")
print(f"Topic operations: {len(topic_operations)}")def validate_migration_readiness(standard_namespace_name, premium_namespace_name):
"""Validate that namespaces are ready for migration"""
validation_results = {
"ready_for_migration": True,
"issues": [],
"recommendations": []
}
try:
# Get Standard namespace details
standard_ns = client.namespaces.get(
resource_group_name="my-resource-group",
namespace_name=standard_namespace_name
)
# Get Premium namespace details
premium_ns = client.namespaces.get(
resource_group_name="my-resource-group",
namespace_name=premium_namespace_name
)
# Validate SKU compatibility
if standard_ns.sku.name != "Standard":
validation_results["ready_for_migration"] = False
validation_results["issues"].append(f"Source namespace is {standard_ns.sku.name}, must be Standard")
if premium_ns.sku.name != "Premium":
validation_results["ready_for_migration"] = False
validation_results["issues"].append(f"Target namespace is {premium_ns.sku.name}, must be Premium")
# Validate same region
if standard_ns.location != premium_ns.location:
validation_results["ready_for_migration"] = False
validation_results["issues"].append(f"Namespaces in different regions: {standard_ns.location} vs {premium_ns.location}")
# Check namespace status
if standard_ns.status != "Active":
validation_results["ready_for_migration"] = False
validation_results["issues"].append(f"Standard namespace status: {standard_ns.status}")
if premium_ns.status != "Active":
validation_results["ready_for_migration"] = False
validation_results["issues"].append(f"Premium namespace status: {premium_ns.status}")
# Add recommendations
validation_results["recommendations"].extend([
"Backup all authorization rules and access keys",
"Test applications with Premium namespace connection strings",
"Plan for brief connectivity interruption during completion",
"Monitor migration progress and have rollback plan ready"
])
except Exception as e:
validation_results["ready_for_migration"] = False
validation_results["issues"].append(f"Validation error: {e}")
return validation_results
# Validate migration readiness
validation = validate_migration_readiness("my-standard-namespace", "my-premium-namespace")
if validation["ready_for_migration"]:
print("✅ Ready for migration!")
else:
print("❌ Migration issues found:")
for issue in validation["issues"]:
print(f" - {issue}")
print("\nRecommendations:")
for rec in validation["recommendations"]:
print(f" - {rec}")class MigrationConfigProperties:
def __init__(self, **kwargs): ...
# Migration configuration
id: Optional[str]
name: Optional[str]
type: Optional[str]
# Migration properties
provisioning_state: Optional[str]
pending_replication_operations_count: Optional[int]
target_namespace: Optional[str] # ARM resource ID of target Premium namespace
post_migration_name: Optional[str] # Name for Standard namespace after migration
migration_state: Optional[str]
class MigrationConfigListResult:
def __init__(self, **kwargs): ...
value: Optional[List[MigrationConfigProperties]]
next_link: Optional[str]
class Operation:
def __init__(self, **kwargs): ...
# Operation details
name: Optional[str]
is_data_action: Optional[bool]
display: Optional[OperationDisplay]
origin: Optional[str]
properties: Optional[Dict[str, Any]]
class OperationDisplay:
def __init__(self, **kwargs): ...
provider: Optional[str] # Resource provider name
resource: Optional[str] # Resource type
operation: Optional[str] # Operation name
description: Optional[str] # Operation description
class OperationListResult:
def __init__(self, **kwargs): ...
value: Optional[List[Operation]]
next_link: Optional[str]Preparation Phase
Replication Phase
Completion Phase
post_migration_nameCleanup Phase
What Gets Migrated:
What Doesn't Get Migrated:
Best Practices:
revert() operationpending_replication_operations_count during migrationInstall with Tessl CLI
npx tessl i tessl/pypi-azure-mgmt-servicebus