Skip to content

Commit

Permalink
Use a single query to get count of active VMs and Hosts
Browse files Browse the repository at this point in the history
Instead of looping through all ExtManagementSystems and adding up the
counts of vms and hosts manually we can get this count in one shot by
querying for active VMs and Hosts.
  • Loading branch information
agrare committed Feb 14, 2020
1 parent c223c1c commit 17b393e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
2 changes: 2 additions & 0 deletions app/models/host.rb
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,8 @@ class Host < ApplicationRecord
virtual_total :v_total_vms, :vms
virtual_total :v_total_miq_templates, :miq_templates

scope :active, -> { where.not(:ems_id => nil) }

alias_method :datastores, :storages # Used by web-services to return datastores as the property name

alias_method :parent_cluster, :ems_cluster
Expand Down
12 changes: 3 additions & 9 deletions app/models/miq_server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -488,15 +488,9 @@ def self.zone_is_modifiable?
end

def self.audit_managed_resources
total_vms = 0
total_hosts = 0

ExtManagementSystem.all.each do |e|
vms = e.all_vms_and_templates.count
hosts = e.all_hosts.count
total_vms += vms
total_hosts += hosts
end
total_vms = VmOrTemplate.active.count
total_hosts = Host.active.count

totals = {"vms" => total_vms, "hosts" => total_hosts}
$audit_log.info("Under Management: #{totals.to_json}")
end
Expand Down
15 changes: 15 additions & 0 deletions spec/models/miq_server_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -464,4 +464,19 @@
expect(described_class.zone_is_modifiable?).to be_falsey
end
end

context ".audit_managed_resources" do
let(:ems) { FactoryBot.create(:ems_infra) }
let!(:active_vm) { FactoryBot.create(:vm_infra, :ext_management_system => ems) }
let!(:archived_vm) { FactoryBot.create(:vm_infra) }
let!(:active_host) { FactoryBot.create(:host, :ext_management_system => ems) }
let!(:archived_host) { FactoryBot.create(:host) }

it "with active and archived vms and hosts" do
expected_message = "Under Management: #{{"vms" => 1, "hosts" => 1}.to_json}"

expect($audit_log).to receive(:info).with(expected_message)
described_class.audit_managed_resources
end
end
end

0 comments on commit 17b393e

Please sign in to comment.