Skip to content

Commit bc1acc1

Browse files
Improve clean up process
1 parent 71c1945 commit bc1acc1

File tree

2 files changed

+33
-50
lines changed

2 files changed

+33
-50
lines changed

infrastructure/ag-apim-pe/clean-up.ipynb

Lines changed: 3 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -12,49 +12,17 @@
1212
},
1313
{
1414
"cell_type": "code",
15-
"execution_count": 2,
15+
"execution_count": null,
1616
"id": "2326891e",
1717
"metadata": {},
18-
"outputs": [
19-
{
20-
"name": "stdout",
21-
"output_type": "stream",
22-
"text": [
23-
"\n",
24-
"👉🏽 \u001b[1;34mCleaning up resources for ag-apim-pe - 10\u001b[0m \n",
25-
"👉🏽 \u001b[1;34mResource group : apim-infra-ag-apim-pe-10\u001b[0m \n",
26-
"\u001b[1;31mCommand failed with error: ERROR: (ResourceGroupNotFound) Resource group 'apim-infra-ag-apim-pe-10' could not be found.\n",
27-
"Code: ResourceGroupNotFound\n",
28-
"Message: Resource group 'apim-infra-ag-apim-pe-10' could not be found.\n",
29-
"\u001b[0m ⌚ 15:15:21.751616 [0m:2s]\n",
30-
"\n",
31-
"\u001b[1;32mCleanup completed!\u001b[0m ⌚ 15:15:21.790932 \n"
32-
]
33-
},
34-
{
35-
"name": "stderr",
36-
"output_type": "stream",
37-
"text": [
38-
"Traceback (most recent call last):\n",
39-
" File \"C:\\Dev\\Azure-Samples\\Apim-Samples\\shared\\python\\utils.py\", line 1846, in run\n",
40-
" output_text = subprocess.check_output(command, shell = True, stderr = subprocess.STDOUT).decode('utf-8')\n",
41-
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
42-
" File \"C:\\Users\\simonkurtz\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\subprocess.py\", line 466, in check_output\n",
43-
" return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,\n",
44-
" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
45-
" File \"C:\\Users\\simonkurtz\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\subprocess.py\", line 571, in run\n",
46-
" raise CalledProcessError(retcode, process.args,\n",
47-
"subprocess.CalledProcessError: Command 'az deployment group show --name ag-apim-pe -g apim-infra-ag-apim-pe-10 -o json' returned non-zero exit status 3.\n"
48-
]
49-
}
50-
],
18+
"outputs": [],
5119
"source": [
5220
"import utils\n",
5321
"from apimtypes import INFRASTRUCTURE\n",
5422
"\n",
5523
"# Select infrastructure type and one or more deployment indexes to remove\n",
5624
"infrastructure = INFRASTRUCTURE.AG_APIM_PE\n",
57-
"indexes = [10]\n",
25+
"indexes = [1]\n",
5826
"\n",
5927
"utils.cleanup_infra_deployments(infrastructure, indexes)"
6028
]

shared/python/utils.py

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@
3838
BOLD_W = '\x1b[1;37m' # white
3939
RESET = '\x1b[0m'
4040

41+
INFRA_PREFIX = 'apim-infra-'
42+
SAMPLE_PREFIX = 'apim-sample-'
43+
4144
# Thread colors for parallel operations
4245
THREAD_COLORS = [BOLD_B, BOLD_G, BOLD_Y, BOLD_C, BOLD_M, BOLD_W]
4346

@@ -418,7 +421,7 @@ def _get_current_index(self) -> int | None:
418421
int | None: The index if it exists, None otherwise.
419422
"""
420423

421-
prefix = f'apim-infra-{self.deployment.value}'
424+
prefix = f'{INFRA_PREFIX}{self.deployment.value}'
422425

423426
if self.rg_name == prefix:
424427
return None
@@ -600,8 +603,8 @@ def _find_infrastructure_instances(self, infrastructure: INFRASTRUCTURE) -> list
600603

601604
for rg_name in rg_names:
602605
# Parse the resource group name to extract the index
603-
# Expected format: apim-infra-{infrastructure}-{index} or apim-infra-{infrastructure}
604-
prefix = f'apim-infra-{infrastructure.value}'
606+
# Expected format: {INFRA_PREFIX}{infrastructure}-{index} or {INFRA_PREFIX}{infrastructure}
607+
prefix = f'{INFRA_PREFIX}{infrastructure.value}'
605608

606609
if rg_name == prefix:
607610
# No index
@@ -722,7 +725,7 @@ def _cleanup_resources(deployment_name: str, rg_name: str) -> None:
722725
print_info(f'Resource group : {rg_name}')
723726

724727
# Show the deployment details
725-
output = run(f'az deployment group show --name {deployment_name} -g {rg_name} -o json', 'Deployment retrieved', 'Failed to retrieve the deployment', print_command_to_run = False)
728+
output = run(f'az deployment group show --name {deployment_name} -g {rg_name} -o json', 'Deployment retrieved', 'Failed to retrieve the deployment', print_command_to_run = False, print_errors = False)
726729

727730
if output.success and output.json_data:
728731
# Delete and purge CognitiveService accounts
@@ -780,7 +783,6 @@ def _cleanup_resources(deployment_name: str, rg_name: str) -> None:
780783

781784
except Exception as e:
782785
print(f'An error occurred during cleanup: {e}')
783-
traceback.print_exc()
784786

785787
def _print_log(message: str, prefix: str = '', color: str = '', output: str = '', duration: str = '', show_time: bool = False, blank_above: bool = False, blank_below: bool = False, wrap_lines: bool = False) -> None:
786788
"""
@@ -1380,16 +1382,13 @@ def _cleanup_resources_thread_safe(deployment_name: str, rg_name: str, thread_pr
13801382
# Create a modified version of _cleanup_resources that uses thread-safe printing
13811383
_cleanup_resources_with_thread_safe_printing(deployment_name, rg_name, thread_prefix, thread_color)
13821384

1383-
with _print_lock:
1384-
_print_log(f"{thread_prefix}Completed cleanup for resource group: {rg_name}", '👉🏽 ', thread_color)
1385-
1385+
# Don't print completion message here - it will be printed in the main function with progress
13861386
return True, ""
13871387

13881388
except Exception as e:
13891389
error_msg = f'An error occurred during cleanup of {rg_name}: {str(e)}'
13901390
with _print_lock:
13911391
_print_log(f"{thread_prefix}{error_msg}", '⛔ ', BOLD_R, show_time=True)
1392-
traceback.print_exc()
13931392
return False, error_msg
13941393

13951394

@@ -1413,7 +1412,7 @@ def _cleanup_resources_with_thread_safe_printing(deployment_name: str, rg_name:
14131412
_print_log(f"{thread_prefix}Resource group : {rg_name}", '👉🏽 ', thread_color)
14141413

14151414
# Show the deployment details
1416-
output = run(f'az deployment group show --name {deployment_name} -g {rg_name} -o json', 'Deployment retrieved', 'Failed to retrieve the deployment', print_command_to_run = False)
1415+
output = run(f'az deployment group show --name {deployment_name} -g {rg_name} -o json', 'Deployment retrieved', 'Failed to retrieve the deployment', print_command_to_run = False, print_errors = False)
14171416

14181417
if output.success and output.json_data:
14191418
# Delete and purge CognitiveService accounts
@@ -1530,7 +1529,8 @@ def cleanup_infra_deployments(deployment: INFRASTRUCTURE, indexes: int | list[in
15301529
})
15311530

15321531
# Execute cleanup tasks in parallel
1533-
with ThreadPoolExecutor(max_workers=max_workers) as executor:
1532+
print_info(f'Executing cleanup tasks in parallel with up to {max_workers} workers.', False)
1533+
with ThreadPoolExecutor(max_workers = max_workers) as executor:
15341534
# Submit all tasks
15351535
future_to_task = {
15361536
executor.submit(
@@ -1551,20 +1551,35 @@ def cleanup_infra_deployments(deployment: INFRASTRUCTURE, indexes: int | list[in
15511551
task = future_to_task[future]
15521552
try:
15531553
success, error_msg = future.result()
1554-
completed_count += 1
15551554

15561555
if success:
1556+
completed_count += 1
1557+
# Calculate status counts
1558+
total_count = len(indexes_list)
1559+
in_progress_count = total_count - completed_count - failed_count
1560+
15571561
with _print_lock:
1558-
print_ok(f"Completed cleanup for {deployment.value}-{task['index']} ({completed_count}/{len(indexes_list)})")
1562+
print_ok(f"Completed cleanup for resource group: {task['rg_name']}", blank_above = False)
1563+
print_info(f"📊 Progress: {completed_count}/{total_count} completed, {failed_count} failed, {in_progress_count} remaining")
15591564
else:
15601565
failed_count += 1
1566+
# Calculate status counts
1567+
total_count = len(indexes_list)
1568+
in_progress_count = total_count - completed_count - failed_count
1569+
15611570
with _print_lock:
15621571
print_error(f"❌ Failed cleanup for {deployment.value}-{task['index']}: {error_msg}")
1572+
print_info(f"📊 Progress: {completed_count}/{total_count} completed, {failed_count} failed, {in_progress_count} remaining")
15631573

15641574
except Exception as e:
15651575
failed_count += 1
1576+
# Calculate status counts
1577+
total_count = len(indexes_list)
1578+
in_progress_count = total_count - completed_count - failed_count
1579+
15661580
with _print_lock:
15671581
print_error(f"❌ Exception during cleanup for {deployment.value}-{task['index']}: {str(e)}")
1582+
print_info(f"📊 Progress: {completed_count}/{total_count} completed, {failed_count} failed, {in_progress_count} remaining")
15681583

15691584
# Final summary
15701585
if failed_count == 0:
@@ -1789,7 +1804,7 @@ def get_infra_rg_name(deployment_name: INFRASTRUCTURE, index: int | None = None)
17891804
str: The generated resource group name.
17901805
"""
17911806

1792-
rg_name = f'apim-infra-{deployment_name.value}'
1807+
rg_name = f'{INFRA_PREFIX}{deployment_name.value}'
17931808

17941809
if index is not None:
17951810
rg_name = f'{rg_name}-{index}'
@@ -1808,7 +1823,7 @@ def get_rg_name(deployment_name: str, index: int | None = None) -> str:
18081823
str: The generated resource group name.
18091824
"""
18101825

1811-
rg_name = f'apim-sample-{deployment_name}'
1826+
rg_name = f'{SAMPLE_PREFIX}{deployment_name}'
18121827

18131828
if index is not None:
18141829
rg_name = f'{rg_name}-{str(index)}'

0 commit comments

Comments
 (0)