-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Populate HostMetric.used_in_inventories with actual inventory counts #16436
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tll3r
wants to merge
1
commit into
ansible:devel
Choose a base branch
from
tll3r:fix/populate-used-in-inventories
base: devel
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+195
−3
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
10 changes: 10 additions & 0 deletions
10
awx/main/management/commands/update_host_metric_inventory_counts.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| from django.core.management.base import BaseCommand | ||
| from awx.main.tasks.host_metrics import HostMetricInventoryCountTask | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = 'Populate HostMetric.used_in_inventories with the count of inventories each host belongs to' | ||
|
|
||
| def handle(self, *args, **options): | ||
| rows = HostMetricInventoryCountTask.update_counts() | ||
| self.stdout.write(f'Updated {rows} HostMetric records') |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
109 changes: 109 additions & 0 deletions
109
awx/main/tests/functional/commands/test_update_host_metric_inventory_counts.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| import pytest | ||
| from django.utils.timezone import now | ||
|
|
||
| from awx.main.management.commands.update_host_metric_inventory_counts import Command | ||
| from awx.main.models import Inventory, Host, Organization | ||
| from awx.main.models.inventory import HostMetric | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def org(db): | ||
| return Organization.objects.create(name='test-org') | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def inventories(org): | ||
| return [ | ||
| Inventory.objects.create(name='inv-1', organization=org), | ||
| Inventory.objects.create(name='inv-2', organization=org), | ||
| Inventory.objects.create(name='inv-3', organization=org), | ||
| ] | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_no_hosts_sets_zero(inventories): | ||
| """HostMetric records with no matching Host rows get used_in_inventories=0.""" | ||
| current_time = now() | ||
| HostMetric.objects.create(hostname='orphan-host', last_automation=current_time) | ||
|
|
||
| Command().handle() | ||
|
|
||
| hm = HostMetric.objects.get(hostname='orphan-host') | ||
| assert hm.used_in_inventories == 0 | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_single_inventory(inventories): | ||
| """Host in one inventory produces used_in_inventories=1.""" | ||
| current_time = now() | ||
| Host.objects.create(name='host-a', inventory=inventories[0]) | ||
| HostMetric.objects.create(hostname='host-a', last_automation=current_time) | ||
|
|
||
| Command().handle() | ||
|
|
||
| hm = HostMetric.objects.get(hostname='host-a') | ||
| assert hm.used_in_inventories == 1 | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_multiple_inventories(inventories): | ||
| """Same hostname across 3 inventories produces used_in_inventories=3.""" | ||
| current_time = now() | ||
| for inv in inventories: | ||
| Host.objects.create(name='shared-host', inventory=inv) | ||
| HostMetric.objects.create(hostname='shared-host', last_automation=current_time) | ||
|
|
||
| Command().handle() | ||
|
|
||
| hm = HostMetric.objects.get(hostname='shared-host') | ||
| assert hm.used_in_inventories == 3 | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_mixed_hosts(inventories): | ||
| """Different hosts with different inventory membership counts.""" | ||
| current_time = now() | ||
|
|
||
| Host.objects.create(name='host-x', inventory=inventories[0]) | ||
| Host.objects.create(name='host-x', inventory=inventories[1]) | ||
| Host.objects.create(name='host-y', inventory=inventories[0]) | ||
|
|
||
| HostMetric.objects.create(hostname='host-x', last_automation=current_time) | ||
| HostMetric.objects.create(hostname='host-y', last_automation=current_time) | ||
| HostMetric.objects.create(hostname='host-z', last_automation=current_time) | ||
|
|
||
| Command().handle() | ||
|
|
||
| assert HostMetric.objects.get(hostname='host-x').used_in_inventories == 2 | ||
| assert HostMetric.objects.get(hostname='host-y').used_in_inventories == 1 | ||
| assert HostMetric.objects.get(hostname='host-z').used_in_inventories == 0 | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_idempotent(inventories): | ||
| """Running the command twice produces the same result.""" | ||
| current_time = now() | ||
| Host.objects.create(name='host-idem', inventory=inventories[0]) | ||
| Host.objects.create(name='host-idem', inventory=inventories[1]) | ||
| HostMetric.objects.create(hostname='host-idem', last_automation=current_time) | ||
|
|
||
| Command().handle() | ||
| assert HostMetric.objects.get(hostname='host-idem').used_in_inventories == 2 | ||
|
|
||
| Command().handle() | ||
| assert HostMetric.objects.get(hostname='host-idem').used_in_inventories == 2 | ||
|
|
||
|
|
||
| @pytest.mark.django_db | ||
| def test_updates_after_inventory_change(inventories): | ||
| """Counts update correctly when a host is added to a new inventory.""" | ||
| current_time = now() | ||
| Host.objects.create(name='host-grow', inventory=inventories[0]) | ||
| HostMetric.objects.create(hostname='host-grow', last_automation=current_time) | ||
|
|
||
| Command().handle() | ||
| assert HostMetric.objects.get(hostname='host-grow').used_in_inventories == 1 | ||
|
|
||
| Host.objects.create(name='host-grow', inventory=inventories[2]) | ||
| Command().handle() | ||
| assert HostMetric.objects.get(hostname='host-grow').used_in_inventories == 2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid materializing full host-name counts into Python for updates.
counts = dict(...)plushostname__in=counts.keys()does not scale for large datasets and can produce very largeIN (...)clauses; it also introduces a stale key-set window across two UPDATEs. Use one correlated subquery withCoalesce(..., 0)for a single set-based update.Proposed refactor
class HostMetricInventoryCountTask: @@ `@staticmethod` def update_counts(): - counts = dict( - Host.objects.values('name') - .annotate(cnt=Count('inventory_id', distinct=True)) - .values_list('name', 'cnt') - ) - - rows = 0 - - # Set hosts with inventory membership to their actual count (only where changed) - if counts: - inventory_count_subquery = ( - Host.objects.filter(name=OuterRef('hostname')) - .values('name') - .annotate(cnt=Count('inventory_id', distinct=True)) - .values('cnt') - ) - rows += HostMetric.objects.filter(hostname__in=counts.keys()).exclude( - used_in_inventories=Subquery(inventory_count_subquery) - ).update(used_in_inventories=Subquery(inventory_count_subquery)) - - # Set hosts without any inventory membership to 0 (only where not already 0) - rows += HostMetric.objects.exclude(hostname__in=counts.keys()).exclude( - used_in_inventories=0 - ).update(used_in_inventories=0) + inventory_count_subquery = ( + Host.objects.filter(name=OuterRef('hostname')) + .values('name') + .annotate(cnt=Count('inventory_id', distinct=True)) + .values('cnt')[:1] + ) + computed_count = Coalesce(Subquery(inventory_count_subquery), Value(0)) + + rows = HostMetric.objects.exclude( + used_in_inventories=computed_count + ).update(used_in_inventories=computed_count) settings.HOST_METRIC_INVENTORY_COUNTS_LAST_TS = now() logger.info(f"update_host_metric_inventory_counts: updated {rows} HostMetric records") return rows📝 Committable suggestion
🤖 Prompt for AI Agents