Skip to content

Commit

Permalink
Refactor find_vm method
Browse files Browse the repository at this point in the history
  • Loading branch information
agrare committed Apr 3, 2019
1 parent 228e8d4 commit e794003
Showing 1 changed file with 19 additions and 11 deletions.
30 changes: 19 additions & 11 deletions app/models/ems_refresh/save_inventory.rb
Original file line number Diff line number Diff line change
Expand Up @@ -381,17 +381,25 @@ def save_ems_storage_inventory(ems, hashes, target = nil)
def find_vm(h, vms_by_ems_ref, vms_by_uid_ems)
# Find the Vm in the database with the current uid_ems. In the event
# of duplicates, try to determine which one is correct.
found = vms_by_uid_ems[h[:uid_ems]] || []
if found.length > 1 || (found.length == 1 && found.first.ems_id)
found_dups = found
found = found_dups.select { |v| v.ems_id == h[:ems_id] && (v.ems_ref.nil? || v.ems_ref == h[:ems_ref]) }
if found.empty?
found_dups = found_dups.select { |v| v.ems_id.nil? }
found = found_dups.select { |v| v.ems_ref == h[:ems_ref] }
found = found_dups if found.empty?
end
end
duplicates = vms_by_uid_ems[h[:uid_ems]] || []

# Reject any VMs which are active on other EMSs
duplicates.reject! { |vm| vm.ems_id.present? && vm.ems_id != h[:ems_id] }

# No vms with this uid_ems were found, create a new record
return if duplicates.blank?

active_duplicates, archived_duplicates = duplicates.partition { |vm| vm.ems_id.present? }

# Prioritize VMs on the current EMS with the same ems_ref or a nil ems_ref
found = active_duplicates.detect { |v| v.ems_ref.nil? || v.ems_ref == h[:ems_ref] }

# Next select an archived VM with the same ems_ref as the current vm
found ||= archived_duplicates.detect { |v| v.ems_ref == h[:ems_ref] }

# Lastly fall back on the first archived VM with the same uid_ems
found ||= archived_duplicates.first

found.first
found
end
end

0 comments on commit e794003

Please sign in to comment.