|
| 1 | +# -------------------------------------------------------------------------------------------- |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +# Licensed under the MIT License. See License.txt in the project root for license information. |
| 4 | +# -------------------------------------------------------------------------------------------- |
| 5 | + |
| 6 | +""" |
| 7 | +Protected item listing utilities for Azure Migrate local replication. |
| 8 | +""" |
| 9 | + |
| 10 | +from knack.util import CLIError |
| 11 | +from knack.log import get_logger |
| 12 | + |
| 13 | +logger = get_logger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +def get_vault_name_from_project(cmd, resource_group_name, |
| 17 | + project_name, subscription_id): |
| 18 | + """ |
| 19 | + Get the vault name from the Azure Migrate project solution. |
| 20 | +
|
| 21 | + Args: |
| 22 | + cmd: The CLI command context |
| 23 | + resource_group_name (str): Resource group name |
| 24 | + project_name (str): Migrate project name |
| 25 | + subscription_id (str): Subscription ID |
| 26 | +
|
| 27 | + Returns: |
| 28 | + str: The vault name |
| 29 | +
|
| 30 | + Raises: |
| 31 | + CLIError: If the solution or vault is not found |
| 32 | + """ |
| 33 | + from azext_migrate.helpers._utils import get_resource_by_id, APIVersion |
| 34 | + |
| 35 | + # Get the migration solution |
| 36 | + solution_name = "Servers-Migration-ServerMigration_DataReplication" |
| 37 | + solution_uri = ( |
| 38 | + f"/subscriptions/{subscription_id}/" |
| 39 | + f"resourceGroups/{resource_group_name}/" |
| 40 | + f"providers/Microsoft.Migrate/migrateProjects/{project_name}/" |
| 41 | + f"solutions/{solution_name}" |
| 42 | + ) |
| 43 | + |
| 44 | + logger.info( |
| 45 | + "Retrieving solution '%s' from project '%s'", |
| 46 | + solution_name, project_name) |
| 47 | + |
| 48 | + try: |
| 49 | + solution = get_resource_by_id( |
| 50 | + cmd, |
| 51 | + solution_uri, |
| 52 | + APIVersion.Microsoft_Migrate.value |
| 53 | + ) |
| 54 | + |
| 55 | + if not solution: |
| 56 | + raise CLIError( |
| 57 | + f"Solution '{solution_name}' not found in project " |
| 58 | + f"'{project_name}'. Please run 'az migrate local replication " |
| 59 | + f"init' to initialize replication infrastructure.") |
| 60 | + |
| 61 | + # Extract vault ID from solution extended details |
| 62 | + properties = solution.get('properties', {}) |
| 63 | + details = properties.get('details', {}) |
| 64 | + extended_details = details.get('extendedDetails', {}) |
| 65 | + vault_id = extended_details.get('vaultId') |
| 66 | + |
| 67 | + if not vault_id: |
| 68 | + raise CLIError( |
| 69 | + "Vault ID not found in solution. The replication " |
| 70 | + "infrastructure may not be initialized. Please run " |
| 71 | + "'az migrate local replication init'.") |
| 72 | + |
| 73 | + # Parse vault name from vault ID |
| 74 | + vault_id_parts = vault_id.split("/") |
| 75 | + if len(vault_id_parts) < 9: |
| 76 | + raise CLIError(f"Invalid vault ID format: {vault_id}") |
| 77 | + |
| 78 | + vault_name = vault_id_parts[8] |
| 79 | + return vault_name |
| 80 | + |
| 81 | + except CLIError: |
| 82 | + raise |
| 83 | + except Exception as e: |
| 84 | + logger.error( |
| 85 | + "Error retrieving vault from project '%s': %s", |
| 86 | + project_name, str(e)) |
| 87 | + raise CLIError( |
| 88 | + f"Failed to retrieve vault information: {str(e)}") |
| 89 | + |
| 90 | + |
| 91 | +def list_protected_items(cmd, subscription_id, resource_group_name, vault_name): |
| 92 | + """ |
| 93 | + List all protected items in a replication vault. |
| 94 | +
|
| 95 | + Args: |
| 96 | + cmd: The CLI command context |
| 97 | + subscription_id (str): Subscription ID |
| 98 | + resource_group_name (str): Resource group name |
| 99 | + vault_name (str): Vault name |
| 100 | +
|
| 101 | + Returns: |
| 102 | + list: List of formatted protected items |
| 103 | +
|
| 104 | + Raises: |
| 105 | + CLIError: If protected items cannot be listed |
| 106 | + """ |
| 107 | + from azext_migrate.helpers._utils import ( |
| 108 | + send_get_request, |
| 109 | + APIVersion |
| 110 | + ) |
| 111 | + |
| 112 | + if not vault_name: |
| 113 | + raise CLIError( |
| 114 | + "Unable to determine vault name. Please check your project " |
| 115 | + "configuration.") |
| 116 | + |
| 117 | + protected_items_uri = ( |
| 118 | + f"/subscriptions/{subscription_id}/" |
| 119 | + f"resourceGroups/{resource_group_name}/" |
| 120 | + f"providers/Microsoft.DataReplication/" |
| 121 | + f"replicationVaults/{vault_name}/" |
| 122 | + f"protectedItems?api-version={APIVersion.Microsoft_DataReplication.value}" |
| 123 | + ) |
| 124 | + |
| 125 | + request_uri = ( |
| 126 | + f"{cmd.cli_ctx.cloud.endpoints.resource_manager}{protected_items_uri}") |
| 127 | + |
| 128 | + logger.info( |
| 129 | + "Listing protected items from vault '%s'", vault_name) |
| 130 | + |
| 131 | + try: |
| 132 | + response = send_get_request(cmd, request_uri) |
| 133 | + |
| 134 | + if not response: |
| 135 | + logger.warning("Empty response received when listing protected items") |
| 136 | + return [] |
| 137 | + |
| 138 | + response_data = response.json() if hasattr(response, 'json') else {} |
| 139 | + |
| 140 | + if not response_data: |
| 141 | + logger.warning("No data in response when listing protected items") |
| 142 | + return [] |
| 143 | + |
| 144 | + protected_items = response_data.get('value', []) |
| 145 | + |
| 146 | + if not protected_items: |
| 147 | + logger.info("No protected items found in vault '%s'", vault_name) |
| 148 | + print(f"No replicating servers found in project.") |
| 149 | + return [] |
| 150 | + |
| 151 | + # Handle pagination if nextLink is present |
| 152 | + while response_data and response_data.get('nextLink'): |
| 153 | + next_link = response_data['nextLink'] |
| 154 | + response = send_get_request(cmd, next_link) |
| 155 | + response_data = response.json() if ( |
| 156 | + response and hasattr(response, 'json')) else {} |
| 157 | + if response_data and response_data.get('value'): |
| 158 | + protected_items.extend(response_data['value']) |
| 159 | + |
| 160 | + logger.info( |
| 161 | + "Retrieved %d protected items from vault '%s'", |
| 162 | + len(protected_items), vault_name) |
| 163 | + |
| 164 | + # Format the protected items for output |
| 165 | + formatted_items = [] |
| 166 | + for item in protected_items: |
| 167 | + try: |
| 168 | + formatted_item = _format_protected_item(item) |
| 169 | + formatted_items.append(formatted_item) |
| 170 | + except Exception as format_error: |
| 171 | + logger.warning("Error formatting protected item: %s", str(format_error)) |
| 172 | + # Skip items that fail to format |
| 173 | + continue |
| 174 | + |
| 175 | + # Print summary |
| 176 | + _print_protected_items_summary(formatted_items) |
| 177 | + |
| 178 | + except Exception as e: |
| 179 | + logger.error("Error listing protected items: %s", str(e)) |
| 180 | + raise CLIError(f"Failed to list protected items: {str(e)}") |
| 181 | + |
| 182 | + |
| 183 | +def _format_protected_item(item): |
| 184 | + """ |
| 185 | + Format a protected item for display. |
| 186 | +
|
| 187 | + Args: |
| 188 | + item (dict): Raw protected item from API |
| 189 | +
|
| 190 | + Returns: |
| 191 | + dict: Formatted protected item |
| 192 | + """ |
| 193 | + properties = item.get('properties', {}) |
| 194 | + custom_properties = properties.get('customProperties', {}) |
| 195 | + |
| 196 | + # Extract common properties |
| 197 | + formatted_item = { |
| 198 | + 'id': item.get('id', 'N/A'), |
| 199 | + 'name': item.get('name', 'N/A'), |
| 200 | + 'type': item.get('type', 'N/A'), |
| 201 | + 'protectionState': properties.get('protectionState', 'Unknown'), |
| 202 | + 'protectionStateDescription': properties.get('protectionStateDescription', 'N/A'), |
| 203 | + 'replicationHealth': properties.get('replicationHealth', 'Unknown'), |
| 204 | + 'healthErrors': properties.get('healthErrors', []), |
| 205 | + 'allowedJobs': properties.get('allowedJobs', []), |
| 206 | + 'correlationId': properties.get('correlationId', 'N/A'), |
| 207 | + 'policyName': properties.get('policyName', 'N/A'), |
| 208 | + 'replicationExtensionName': properties.get('replicationExtensionName', 'N/A'), |
| 209 | + } |
| 210 | + |
| 211 | + # Add custom properties if available |
| 212 | + if custom_properties: |
| 213 | + formatted_item['instanceType'] = custom_properties.get('instanceType', 'N/A') |
| 214 | + formatted_item['sourceMachineName'] = custom_properties.get('sourceMachineName', 'N/A') |
| 215 | + formatted_item['targetVmName'] = custom_properties.get('targetVmName', 'N/A') |
| 216 | + formatted_item['targetResourceGroupId'] = custom_properties.get('targetResourceGroupId', 'N/A') |
| 217 | + formatted_item['customLocationRegion'] = custom_properties.get('customLocationRegion', 'N/A') |
| 218 | + |
| 219 | + return formatted_item |
| 220 | + |
| 221 | + |
| 222 | +def _print_protected_items_summary(items): |
| 223 | + """ |
| 224 | + Print a summary of protected items. |
| 225 | +
|
| 226 | + Args: |
| 227 | + items (list): List of formatted protected items |
| 228 | + """ |
| 229 | + if not items: |
| 230 | + return |
| 231 | + |
| 232 | + print(f"\nFound {len(items)} replicating server(s):\n") |
| 233 | + print("-" * 120) |
| 234 | + |
| 235 | + for idx, item in enumerate(items, 1): |
| 236 | + print(f"\n{idx}. {item.get('name', 'Unknown')}") |
| 237 | + print(f" Protection State: {item.get('protectionState', 'Unknown')}") |
| 238 | + print(f" Replication Health: {item.get('replicationHealth', 'Unknown')}") |
| 239 | + print(f" Source Machine: {item.get('sourceMachineName', 'N/A')}") |
| 240 | + print(f" Target VM Name: {item.get('targetVmName', 'N/A')}") |
| 241 | + print(f" Policy: {item.get('policyName', 'N/A')}") |
| 242 | + print(f" Resource ID: {item.get('id', 'N/A')}") |
| 243 | + |
| 244 | + # Show health errors if any |
| 245 | + health_errors = item.get('healthErrors', []) |
| 246 | + if health_errors: |
| 247 | + print(f" Health Errors: {len(health_errors)} error(s)") |
| 248 | + for error in health_errors[:3]: # Show first 3 errors |
| 249 | + error_message = error.get('message', 'Unknown error') |
| 250 | + print(f" - {error_message}") |
| 251 | + |
| 252 | + print("\n" + "-" * 120) |
0 commit comments