Merge pull request #4137 from chrismeyersfsu/fix-smart_inv_race

wrap smart inv cache update w/ advisory lock

Reviewed-by: https://github.com/softwarefactory-project-zuul[bot]
This commit is contained in:
softwarefactory-project-zuul[bot]
2019-06-21 20:25:10 +00:00
committed by GitHub

View File

@@ -602,25 +602,26 @@ def update_inventory_computed_fields(inventory_id, should_update_hosts=True):
def update_smart_memberships_for_inventory(smart_inventory): def update_smart_memberships_for_inventory(smart_inventory):
current = set(SmartInventoryMembership.objects.filter(inventory=smart_inventory).values_list('host_id', flat=True)) with advisory_lock('update_smart_memberships_for_inventory-{}'.format(smart_inventory.id)):
new = set(smart_inventory.hosts.values_list('id', flat=True)) current = set(SmartInventoryMembership.objects.filter(inventory=smart_inventory).values_list('host_id', flat=True))
additions = new - current new = set(smart_inventory.hosts.values_list('id', flat=True))
removals = current - new additions = new - current
if additions or removals: removals = current - new
with transaction.atomic(): if additions or removals:
if removals: with transaction.atomic():
SmartInventoryMembership.objects.filter(inventory=smart_inventory, host_id__in=removals).delete() if removals:
if additions: SmartInventoryMembership.objects.filter(inventory=smart_inventory, host_id__in=removals).delete()
add_for_inventory = [ if additions:
SmartInventoryMembership(inventory_id=smart_inventory.id, host_id=host_id) add_for_inventory = [
for host_id in additions SmartInventoryMembership(inventory_id=smart_inventory.id, host_id=host_id)
] for host_id in additions
SmartInventoryMembership.objects.bulk_create(add_for_inventory) ]
logger.debug('Smart host membership cached for {}, {} additions, {} removals, {} total count.'.format( SmartInventoryMembership.objects.bulk_create(add_for_inventory)
smart_inventory.pk, len(additions), len(removals), len(new) logger.debug('Smart host membership cached for {}, {} additions, {} removals, {} total count.'.format(
)) smart_inventory.pk, len(additions), len(removals), len(new)
return True # changed ))
return False return True # changed
return False
@task() @task()