Skip to content
Open
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
80 changes: 78 additions & 2 deletions app/controllers/api/v2/hosts_bulk_actions_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ class HostsBulkActionsController < V2::BaseController
include Api::V2::BulkHostsExtension

before_action :find_deletable_hosts, :only => [:bulk_destroy]
before_action :find_editable_hosts, :only => [:build, :reassign_hostgroup, :change_owner, :disassociate]
before_action :find_editable_hosts, :only => [:build, :reassign_hostgroup, :change_owner, :disassociate, :change_power_state]
before_action :validate_power_action, :only => [:change_power_state]

def_param_group :bulk_host_ids do
param :organization_id, :number, :required => true, :desc => N_("ID of the organization")
Expand Down Expand Up @@ -63,6 +64,56 @@ def build
end
end

api :PUT, "/hosts/bulk/change_power_state", N_("Change power state")
param_group :bulk_host_ids
param :power, String, :required => true, :desc => N_("Power action to perform (start, stop, poweroff, reboot, reset, soft, cycle)")
def change_power_state
action = params[:power]

manager = BulkHostsManager.new(hosts: @hosts)
result = manager.change_power_state(action)

failed_hosts = result[:failed_hosts] || []
failed_host_ids = result[:failed_host_ids] || []
unsupported_hosts = result[:unsupported_hosts] || []
unsupported_host_ids = result[:unsupported_host_ids] || []

if failed_hosts.empty? && unsupported_hosts.empty?
render json: {
message: _('The power state of the selected hosts will be set to %s') % _(action),
}, status: :ok
else
total_failed = failed_hosts.size
total_unsupported = unsupported_hosts.size

parts = []
if total_failed > 0
parts << n_(
"Failed to set power state for %s host.",
"Failed to set power state for %s hosts.",
total_failed
) % total_failed
end

if total_unsupported > 0
parts << n_(
"%s host does not support power management.",
"%s hosts do not support power management.",
total_unsupported
) % total_unsupported
end

render json: {
error: {
message: parts.join(' '),
failed_host_ids: (failed_host_ids + unsupported_host_ids).uniq,
failed_hosts: failed_hosts,
unsupported_hosts: unsupported_hosts,
},
}, status: :unprocessable_entity
end
end

api :PUT, "/hosts/bulk/reassign_hostgroups", N_("Reassign hostgroups")
param_group :bulk_host_ids
param :hostgroup_id, :number, :desc => N_("ID of the hostgroup to reassign the hosts to")
Expand Down Expand Up @@ -126,7 +177,7 @@ def assign_location

def action_permission
case params[:action]
when 'build'
when 'build', 'change_power_state'
'edit'
else
super
Expand Down Expand Up @@ -173,6 +224,31 @@ def rebuild_config
)
end
end

def validate_power_action
action = params[:power]
host_ids = @hosts&.map(&:id) || []

return true if action.present? && PowerManager::REAL_ACTIONS.include?(action)

if action.blank?
render json: {
error: {
message: _("Power action is required"),
failed_host_ids: host_ids,
},
}, status: :unprocessable_entity
else
render json: {
error: {
message: _("Invalid power action"),
valid_power_actions: PowerManager::REAL_ACTIONS,
failed_host_ids: host_ids,
},
}, status: :unprocessable_entity
end
false
end
end
end
end
32 changes: 32 additions & 0 deletions app/services/bulk_hosts_manager.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,36 @@ def assign_taxonomy(taxonomy, optimistic_import)
raise _("Cannot update %{type} to %{name} because of mismatch in settings") % {type: taxonomy.type.downcase, name: taxonomy.name}
end
end

def change_power_state(action)
failed_hosts = []
unsupported_hosts = []

@hosts.each do |host|
unless host.supports_power?
unsupported_hosts << {
id: host.id,
error: _('Power management not available for this host'),
}
next
end

begin
host.power.send(action.to_sym)
rescue => error
Foreman::Logging.exception("Failed to set power state for #{host}.", error)
failed_hosts << {
id: host.id,
error: error.message,
}
end
end

{
failed_hosts: failed_hosts,
failed_host_ids: failed_hosts.map { |h| h[:id] },
unsupported_hosts: unsupported_hosts,
unsupported_host_ids: unsupported_hosts.map { |h| h[:id] },
}
end
end
2 changes: 1 addition & 1 deletion config/initializers/f_foreman_permissions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@
:"api/v2/hosts" => [:update, :disassociate, :forget_status],
:"api/v2/interfaces" => [:create, :update, :destroy],
:"api/v2/compute_resources" => [:associate],
:"api/v2/hosts_bulk_actions" => [:assign_organization, :assign_location, :build, :reassign_hostgroup, :change_owner, :disassociate],
:"api/v2/hosts_bulk_actions" => [:assign_organization, :assign_location, :build, :reassign_hostgroup, :change_owner, :disassociate, :change_power_state],
}
map.permission :destroy_hosts, {:hosts => [:destroy, :multiple_actions, :reset_multiple, :multiple_destroy, :submit_multiple_destroy],
:"api/v2/hosts" => [:destroy],
Expand Down
1 change: 1 addition & 0 deletions config/routes/api/v2.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
put 'hosts/bulk/assign_location', :to => 'hosts_bulk_actions#assign_location'
match 'hosts/bulk/build', :to => 'hosts_bulk_actions#build', :via => [:put]
match 'hosts/bulk/change_owner', :to => 'hosts_bulk_actions#change_owner', :via => [:put]
put 'hosts/bulk/change_power_state', :to => 'hosts_bulk_actions#change_power_state'
put 'hosts/bulk/disassociate', :to => 'hosts_bulk_actions#disassociate'
match 'hosts/bulk/reassign_hostgroup', :to => 'hosts_bulk_actions#reassign_hostgroup', :via => [:put]

Expand Down
86 changes: 86 additions & 0 deletions test/controllers/api/v2/hosts_bulk_actions_controller_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ def valid_bulk_params(host_ids = @host_ids)
}
end

def valid_power_params(host_ids = @host_ids, action = 'start')
valid_bulk_params(host_ids).merge(:power => action)
end

test "should change owner with user id" do
put :change_owner, params: valid_bulk_params.merge(:owner_id => @user.id_and_type)

Expand Down Expand Up @@ -103,6 +107,88 @@ def valid_bulk_params(host_ids = @host_ids)
end
end

context "change_power_state" do
test "successfully changes power state for all hosts" do
Host.any_instance.stubs(:supports_power?).returns(true)
power_mock = mock('power')
Host.any_instance.stubs(:power).returns(power_mock)
power_mock.expects(:send).with(:start).times(@host_ids.size)

put :change_power_state, params: valid_power_params(@host_ids, 'start')

assert_response :success
body = ActiveSupport::JSON.decode(@response.body)
assert_match(/The power state of the selected hosts will be set to start/, body['message'])
end

test "returns failed_host_ids when all hosts fail" do
Host.any_instance.stubs(:supports_power?).returns(true)
power_mock = mock('power')
Host.any_instance.stubs(:power).returns(power_mock)
power_mock.stubs(:send).with(:start).raises(StandardError.new('Power operation failed'))

put :change_power_state, params: valid_power_params(@host_ids, 'start')

assert_response :unprocessable_entity
body = ActiveSupport::JSON.decode(@response.body)
assert_match(/Failed to set power state for 3 hosts/, body['error']['message'])
assert_equal @host_ids.sort, body['error']['failed_host_ids'].sort
end

test "returns error when power param is missing" do
Host.any_instance.stubs(:supports_power?).returns(true)
power_mock = mock('power')
Host.any_instance.stubs(:power).returns(power_mock)
power_mock.stubs(:send).raises(StandardError.new('Power operation failed'))

put :change_power_state, params: valid_bulk_params(@host_ids)

assert_response :unprocessable_entity
body = ActiveSupport::JSON.decode(@response.body)
assert_equal "Power action is required", body['error']['message']
assert_equal @host_ids.sort, body['error']['failed_host_ids'].sort
end

test "returns error when power action is invalid" do
put :change_power_state, params: valid_power_params(@host_ids, 'invalid')

assert_response :unprocessable_entity
body = ActiveSupport::JSON.decode(@response.body)
assert_equal "Invalid power action", body['error']['message']
assert_equal PowerManager::REAL_ACTIONS, body['error']['valid_power_actions']
assert_equal @host_ids.sort, body['error']['failed_host_ids'].sort
end

test "handles mixed hosts with no power support, failure, and success" do
Host.any_instance.stubs(:supports_power?)
.returns(false)
.then.returns(true)
.then.returns(true)

power_fail = mock('power_fail')
power_ok = mock('power_ok')

Host.any_instance.stubs(:power)
.returns(power_fail)
.then.returns(power_ok)

power_fail.expects(:send).with(:start).raises(StandardError.new('Power operation failed'))
power_ok.expects(:send).with(:start)

put :change_power_state, params: valid_power_params(@host_ids, 'start')

assert_response :unprocessable_entity
body = ActiveSupport::JSON.decode(@response.body)
# Message should contain both failure types
assert_match(/Failed to set power state for 1 host/, body['error']['message'])
assert_match(/1 host does not support power management/, body['error']['message'])
assert_equal 2, body['error']['failed_host_ids'].size
body['error']['failed_host_ids'].each do |id|
assert_includes @host_ids, id
end
end
end

private

def set_session_user
Expand Down
Loading