Skip to content
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

Switch to async foreman-tasks-based utilization trigger #75

Merged
merged 4 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,7 @@ Rails/SkipsModelValidations:

Style/FormatStringToken:
Enabled: false

Rails/DynamicFindBy:
Exclude:
- "lib/foreman_resource_quota/engine.rb"
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ module HostManagedExtensions

# A host shall always have a .host_resources attribute
before_validation :build_host_resources, unless: -> { host_resources.present? }
after_save :save_host_resources, if: -> { host_resources.changed? }
end

def verify_resource_quota
Expand Down Expand Up @@ -141,6 +142,10 @@ def quota_assigment_optional?
owner.resource_quota_is_optional || Setting[:resource_quota_optional_assignment]
end

def save_host_resources
host_resources.save
end

# Wrap into a function for easier testing
def call_utilization_helper(resources, hosts)
all_host_resources, missing_hosts = utilization_from_resource_origins(resources, hosts)
Expand Down
4 changes: 4 additions & 0 deletions foreman_resource_quota.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@ Gem::Specification.new do |s|
s.description = 'Foreman Plug-in to manage resource usage among users.'

s.files = Dir['{app,config,db,lib,locale,webpack}/**/*'] + ['LICENSE', 'Rakefile', 'README.md', 'package.json']

s.add_dependency 'foreman-tasks', '>= 10.0', '< 11'

s.add_development_dependency 'theforeman-rubocop', '~> 0.1.0'
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# frozen_string_literal: true

module ForemanResourceQuota
module Async
class RefreshResourceQuotaUtilization < ::Actions::EntryAction
include ::Actions::RecurringAction

def run
ResourceQuota.all.each do |quota|
quota.determine_utilization
rescue e
logger.error N_(format("An error occured determining the utilization of '%s'-quota: %s", quota.name, e))
end
end

def logger
action_logger
end

def rescue_strategy_for_self
Dynflow::Action::Rescue::Fail
end
end
end
end
39 changes: 39 additions & 0 deletions lib/foreman_resource_quota/engine.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require 'foreman_tasks'

module ForemanResourceQuota
class Engine < ::Rails::Engine
engine_name 'foreman_resource_quota'
Expand Down Expand Up @@ -42,10 +44,47 @@ class Engine < ::Rails::Engine
Rails.logger.warn "ForemanResourceQuota: skipping engine hook (#{e})"
end

# Register ForemanTasks-based recurring logic/scheduled tasks
initializer 'foreman_resource_quota.register_scheduled_tasks', before: :finisher_hook do |_app|
action_paths = [ForemanResourceQuota::Engine.root.join('lib/foreman_resource_quota/async')]
::ForemanTasks.dynflow.config.eager_load_paths.concat(action_paths)

# Skip object creation if the admin user is not present
# skip database manipulations while tables do not exist, like in migrations
if ActiveRecord::Base.connection.data_source_exists?(::ForemanTasks::Task.table_name) &&
User.unscoped.find_by_login(User::ANONYMOUS_ADMIN).present?
# Register the scheduled tasks
::ForemanTasks.dynflow.config.on_init(false) do |_world|
ForemanResourceQuota::Engine.register_scheduled_task(
ForemanResourceQuota::Async::RefreshResourceQuotaUtilization,
'0 1 * * *'
)
end
end
rescue ActiveRecord::NoDatabaseError => e
Rails.logger.warn "ForemanResourceQuota: skipping ForemanTasks registration hook (#{e})"
end

initializer 'foreman_resource_quota.register_gettext', after: :load_config_initializers do |_app|
locale_dir = File.join(File.expand_path('../..', __dir__), 'locale')
locale_domain = 'foreman_resource_quota'
Foreman::Gettext::Support.add_text_domain locale_domain, locale_dir
end

# Helper to register ForemanTasks
def self.register_scheduled_task(task_class, cronline)
return if ::ForemanTasks::RecurringLogic.joins(:tasks)
.merge(::ForemanTasks::Task.where(label: task_class.name))
.exists?
::ForemanTasks::RecurringLogic.transaction(isolation: :serializable) do
User.as_anonymous_admin do
recurring_logic = ::ForemanTasks::RecurringLogic.new_from_cronline(cronline)
recurring_logic.save!
recurring_logic.start(task_class)
end
end
rescue ActiveRecord::TransactionIsolationError => e
Rails.logger.warn "ForemanResourceQuota: skipping RecurringLogic registration hook (#{e})"
end
end
end
45 changes: 45 additions & 0 deletions test/jobs/refresh_resource_quota_utilization_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# frozen_string_literal: true

require 'test_plugin_helper'
require 'foreman_tasks/test_helpers'

class RefreshResourceQuotaUtilizationTest < ActiveSupport::TestCase
include ForemanTasks::TestHelpers::WithInThreadExecutor

setup do
User.current = User.find_by(login: 'secret_admin')
Setting[:resource_quota_global_no_action] = false
Setting[:resource_quota_optional_assignment] = false
User.current.resource_quota_is_optional = false

stub_host_utilization({ cpu_cores: 2, memory_mb: 1024 * 4, disk_gb: 60 }, {})
@quota = FactoryBot.create(:resource_quota, cpu_cores: 20, memory_mb: 1024 * 30, disk_gb: 512)

@host_a = FactoryBot.create(:host, resource_quota: @quota)
@host_b = FactoryBot.create(:host, resource_quota: @quota)
@host_c = FactoryBot.create(:host, resource_quota: @quota)
@host_d = FactoryBot.create(:host, resource_quota: @quota)
@host_e = FactoryBot.create(:host, resource_quota: @quota)
@quota.reload
end

test 'single resource quota utilization should be updated' do
assert_equal({ cpu_cores: 5 * 2, memory_mb: 5 * 1024 * 4, disk_gb: 5 * 60 }, @quota.utilization)
new_host_utilization = { cpu_cores: 3, memory_mb: 1024 * 5, disk_gb: 61 }
quota_hosts_resources = {
@host_a.name => new_host_utilization,
@host_b.name => new_host_utilization,
@host_c.name => new_host_utilization,
@host_d.name => new_host_utilization,
@host_e.name => new_host_utilization,
}
stub_quota_utilization_helper(quota_hosts_resources, {})
ForemanTasks.sync_task(ForemanResourceQuota::Async::RefreshResourceQuotaUtilization)
@quota.reload
assert_equal({
cpu_cores: 5 * new_host_utilization[:cpu_cores],
memory_mb: 5 * new_host_utilization[:memory_mb],
disk_gb: 5 * new_host_utilization[:disk_gb],
}, @quota.utilization)
end
end
5 changes: 5 additions & 0 deletions test/test_plugin_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ def stub_quota_missing_hosts(return_missing_hosts)
.returns(return_missing_hosts)
end

def stub_quota_utilization_helper(return_hosts_resources, return_missing_hosts)
ForemanResourceQuota::ResourceQuota.any_instance.stubs(:call_utilization_helper)
.returns([return_hosts_resources, return_missing_hosts])
end

def stub_host_utilization(return_utilization, return_missing_hosts)
Host::Managed.any_instance.stubs(:call_utilization_helper).returns([return_utilization, return_missing_hosts])
end