Project

General

Profile

Download (30.1 KB) Statistics
| Branch: | Tag: | Revision:
2f077f63 Ohad Levy
class HostsController < ApplicationController
007bf254 Shimon Shtein
include Foreman::Controller::ActionPermissionDsl
87f8f03e Shimon Shtein
include ScopesPerAction
e5d3f34e Ohad Levy
include Foreman::Controller::HostDetails
7747485a Ohad Levy
include Foreman::Controller::AutoCompleteSearch
a6bbe3d7 Ohad Levy
include Foreman::Controller::TaxonomyMultiple
358ec5a3 Dominic Cleal
include Foreman::Controller::SmartProxyAuth
12612809 Dominic Cleal
include Foreman::Controller::Parameters::Host
68c7a592 Timo Goebel
include Foreman::Controller::HostFormCommon
007bf254 Shimon Shtein
include Foreman::Controller::Puppet::HostsControllerExtensions
229195a5 Tomer Brisker
include Foreman::Controller::CsvResponder
1416a23d Timo Goebel
include Foreman::Controller::ConsoleCommon
e5d3f34e Ohad Levy
9d43fc71 Michael Moll
SEARCHABLE_ACTIONS = %w[index active errors out_of_sync pending disabled]
AJAX_REQUESTS = %w{compute_resource_selected current_parameters process_hostgroup process_taxonomy review_before_build scheduler_hint_selected}
BOOT_DEVICES = { :disk => N_('Disk'), :cdrom => N_('CDROM'), :pxe => N_('PXE'), :bios => N_('BIOS') }
e7e5ef3e Tomer Brisker
MULTIPLE_ACTIONS = %w(multiple_parameters update_multiple_parameters select_multiple_hostgroup
007bf254 Shimon Shtein
update_multiple_hostgroup
acfbc458 Marek Hulan
multiple_destroy submit_multiple_destroy multiple_build
submit_multiple_build multiple_disable submit_multiple_disable
007bf254 Shimon Shtein
multiple_enable submit_multiple_enable
multiple_disassociate update_multiple_disassociate
8ca6c6bb Timo Goebel
rebuild_config submit_rebuild_config select_multiple_owner update_multiple_owner
007bf254 Shimon Shtein
select_multiple_power_state update_multiple_power_state)
4634fd09 Ohad Levy
901fe896 Ondrej Prazak
HOST_POWER = {
fc053564 Dominic Cleal
:on => { :state => 'on', :title => N_('On') },
:off => { :state => 'off', :title => N_('Off') },
:na => { :state => 'na', :title => N_('N/A') }
901fe896 Ondrej Prazak
}.freeze

before_action :ajax_request, :only => AJAX_REQUESTS + [:get_power_state]
df6a9f34 Dominic Cleal
before_action :find_resource, :only => [:show, :clone, :edit, :update, :destroy, :puppetrun, :review_before_build,
901fe896 Ondrej Prazak
:setBuild, :cancelBuild, :power, :get_power_state, :overview, :bmc, :vm,
1ef8f52b Ondrej Prazak
:runtime, :resources, :nics, :ipmi_boot, :console,
1d1e4dab Ewoud Kohl van Wijngaarden
:toggle_manage, :pxe_config, :disassociate]
6e916e52 Shlomi Zadok
df6a9f34 Dominic Cleal
before_action :taxonomy_scope, :only => [:new, :edit] + AJAX_REQUESTS
before_action :set_host_type, :only => [:update]
before_action :find_multiple, :only => MULTIPLE_ACTIONS
before_action :validate_power_action, :only => :update_multiple_power_state
22a5bf03 Daniel Lobato Garcia
356b2e69 Marek Hulan
helper :hosts, :reports, :interfaces
0e12dbfc Ohad Levy
4f7a4d0b David Davis
def index(title = nil)
7747485a Ohad Levy
begin
87f8f03e Shimon Shtein
search = action_scope_for(:index, resource_base_with_search)
7747485a Ohad Levy
rescue => e
error e.to_s
acfbc458 Marek Hulan
search = resource_base.search_for ''
aa729377 Amos Benari
end
a6bbe3d7 Ohad Levy
respond_to do |format|
aa729377 Amos Benari
format.html do
a154c816 lizagilman
@hosts = search.includes(included_associations).paginate(:page => params[:page], :per_page => params[:per_page])
aa729377 Amos Benari
# SQL optimizations queries
e8d6d2d6 Shlomi Zadok
@last_report_ids = ConfigReport.where(:host_id => @hosts.map(&:id)).group(:host_id).maximum(:id)
@last_reports = ConfigReport.where(:id => @last_report_ids.values)
aa729377 Amos Benari
# rendering index page for non index page requests (out of sync hosts etc)
acfbc458 Marek Hulan
@hostgroup_authorizer = Authorizer.new(User.current, :collection => @hosts.map(&:hostgroup_id).compact.uniq)
287082a5 David Davis
render :index if title && (@title = title)
aa729377 Amos Benari
end
229195a5 Tomer Brisker
format.csv do
c8f5cd53 Tomer Brisker
@hosts = search.preload(included_associations - [:host_statuses, :token])
229195a5 Tomer Brisker
csv_response(@hosts)
end
7747485a Ohad Levy
end
a393106d Ohad Levy
end
8e4c0917 Ohad Levy
72e65b31 Ohad Levy
def show
86744a6b Ohad Levy
respond_to do |format|
7deaced2 Daniel Lobato
format.html do
86744a6b Ohad Levy
# filter graph time range
@range = (params["range"].empty? ? 7 : params["range"].to_i)

# summary report text
e8d6d2d6 Shlomi Zadok
@report_summary = ConfigReport.summarise(@range.days.ago, @host)
7deaced2 Daniel Lobato
end
b88cd3a2 Dominic Cleal
format.yaml { render :plain => @host.info.to_yaml }
76e5dd41 Joseph Mitchell Magen
format.json
86744a6b Ohad Levy
end
72e65b31 Ohad Levy
end

b09b4515 Ohad Levy
def new
637da2f2 Timo Goebel
@host = Host.new(
:managed => true,
:build => true
)
b09b4515 Ohad Levy
end

dad78fb6 Paul Kelly
# Clone the host
def clone
30534f9c Ori Rabin
@clone_host = @host
@host = @clone_host.clone
4623fbd4 Timo Goebel
@host.build = true if @host.managed?
dad78fb6 Paul Kelly
load_vars_for_ajax
b9df73be Ohad Levy
warning(_("The marked fields will need reviewing"), true)
e67fc0bd Joseph Magen
@host.valid?
dad78fb6 Paul Kelly
end

b09b4515 Ohad Levy
def create
12612809 Dominic Cleal
@host = Host.new(host_params)
d076d573 Joseph Mitchell Magen
@host.managed = true if (params[:host] && params[:host][:managed].nil?)
5f75d98a Ivan Necas
forward_url_options
b28fdce4 Ohad Levy
if @host.save
96277f87 Tomas Strachota
process_success :success_redirect => host_path(@host)
b28fdce4 Ohad Levy
else
e6dff06b Paul Kelly
load_vars_for_ajax
30ae12bf Ohad Levy
offer_to_overwrite_conflicts
b28fdce4 Ohad Levy
process_error
b09b4515 Ohad Levy
end
end

def edit
dad78fb6 Paul Kelly
load_vars_for_ajax
b09b4515 Ohad Levy
end

def update
5f75d98a Ivan Necas
forward_url_options
611f5bff Amos Benari
Taxonomy.no_taxonomy_scope do
12612809 Dominic Cleal
attributes = @host.apply_inherited_attributes(host_params)
04cb74c0 Shimon Shtein
9ae8fa19 Michael Moll
if @host.update(attributes)
96277f87 Tomas Strachota
process_success :success_redirect => host_path(@host)
611f5bff Amos Benari
else
66afbc33 Joseph Mitchell Magen
taxonomy_scope
611f5bff Amos Benari
load_vars_for_ajax
offer_to_overwrite_conflicts
process_error
end
b09b4515 Ohad Levy
end
end

def destroy
if @host.destroy
e29e550e Shlomi Zadok
process_success :success_redirect => hosts_path
b09b4515 Ohad Levy
else
b28fdce4 Ohad Levy
process_error
b09b4515 Ohad Levy
end
end

# form AJAX methods
03510341 Lukas Zapletal
def random_name
render :json => { :name => NameGenerator.new.next_random_name }
rescue ActionView::Template::Error => exception
process_ajax_error exception, 'generate random name'
end

334d0359 Amos Benari
def compute_resource_selected
9d43fc71 Michael Moll
return not_found unless (params[:host] && (id = params[:host][:compute_resource_id]))
66afbc33 Joseph Mitchell Magen
Taxonomy.as_taxonomy @organization, @location do
05d9c49e Dominic Cleal
compute_profile_id = params[:host][:compute_profile_id] || Hostgroup.find_by_id(params[:host][:hostgroup_id]).try(:inherited_compute_profile_id)
acfbc458 Marek Hulan
compute_resource = ComputeResource.authorized(:view_compute_resources).find_by_id(id)
c6e02bd3 Joseph Magen
render :partial => "compute", :locals => { :compute_resource => compute_resource,
:vm_attrs => compute_resource.compute_profile_attributes_for(compute_profile_id) }
66afbc33 Joseph Mitchell Magen
end
09a8d9a7 Daniel Lobato Garcia
rescue ActionView::Template::Error => exception
process_ajax_error exception, 'render compute resource template'
334d0359 Amos Benari
end

5e813fae elad
def scheduler_hint_selected
ee360810 Michael Moll
return not_found unless params[:host]
265e1d98 orrabin
refresh_host
5e813fae elad
Taxonomy.as_taxonomy @organization, @location do
render :partial => "compute_resources_vms/form/scheduler_hint_filters"
end
end

43c4bd72 Marek Hulan
def interfaces
265e1d98 orrabin
refresh_host
47990639 Tomas Strachota
@host.apply_compute_profile(InterfaceMerge.new)
6d05514a Tomas Strachota
43c4bd72 Marek Hulan
render :partial => "interfaces_tab"
end

8bfaec2a Joseph Mitchell Magen
def current_parameters
5cbba9ec Tomer Brisker
host = refresh_host
66afbc33 Joseph Mitchell Magen
Taxonomy.as_taxonomy @organization, @location do
5cbba9ec Tomer Brisker
render :partial => "common_parameters/inherited_parameters", :locals => {:inherited_parameters => host.inherited_params_hash, :parameters => host.host_parameters}
66afbc33 Joseph Mitchell Magen
end
8bfaec2a Joseph Mitchell Magen
end

68388bc2 Michael Moll
# returns a yaml file ready to use for puppet external nodes script
# expected a fqdn parameter to provide hostname to lookup
# see example script in extras directory
# will return HTML error codes upon failure
ad36b317 Ohad Levy
8e4c0917 Ohad Levy
def externalNodes
27752930 kgaikwad
certname = params[:name].to_s
acfbc458 Marek Hulan
@host ||= resource_base.find_by_certname certname
fb9f45e8 Daniel Lobato
@host ||= resource_base.friendly.find certname
e263719a David Davis
unless @host
not_found
return
end
bc2625b5 Ohad Levy
begin
respond_to do |format|
0069c98d Shimon Shtein
# don't break lines in yaml to support Ruby < 1.9.3
host_info_yaml = @host.info.to_yaml(:line_width => -1)
518f3ce3 Timo Goebel
format.html { render :html => "<pre>#{ERB::Util.html_escape(host_info_yaml)}</pre>".html_safe }
b88cd3a2 Dominic Cleal
format.yml { render :plain => host_info_yaml }
38a6bbd9 Ohad Levy
end
350a0417 David Davis
rescue => e
01e78260 Ivan Nečas
Foreman::Logging.exception("Failed to generate external nodes for #{@host}", e)
b88cd3a2 Dominic Cleal
render :plain => _('Unable to generate output, Check log files'),
350a0417 David Davis
:status => :precondition_failed
8e4c0917 Ohad Levy
end
end
0ce8fa05 Ohad Levy
e1e9e09b Ohad Levy
def puppetrun
c45a0014 Ohad Levy
return deny_access unless Setting[:puppetrun]
dd172ed7 Ohad Levy
if @host.puppetrun!
cf94f62e Avi Sharvit
success _("Successfully executed, check log files for more details")
e1e9e09b Ohad Levy
else
b4fbdf57 Dominic Cleal
error @host.errors[:base].to_sentence
e1e9e09b Ohad Levy
end
e57d4aa5 Ohad Levy
redirect_to host_path(@host)
e1e9e09b Ohad Levy
end

6e916e52 Shlomi Zadok
def review_before_build
e54016da Marek Hulan
@build = @host.build_status_checker
6e916e52 Shlomi Zadok
render :layout => false
end

8613dec9 Ohad Levy
def setBuild
5f75d98a Ivan Necas
forward_url_options
67799065 Ohad Levy
if @host.setBuild
6e916e52 Shlomi Zadok
if (params[:host] && params[:host][:build] == '1')
begin
6695a556 Timo Goebel
if @host.power.reset
message = _("Enabled %s for reboot and rebuild")
else
message = _("Enabled %s for rebuild on next boot, but failed to power cycle the host")
end
ee360810 Michael Moll
process_success :success_msg => message % @host, :success_redirect => :back
6e916e52 Shlomi Zadok
rescue => error
01e78260 Ivan Nečas
message = _('Failed to reboot %s.') % @host
warning(message)
Foreman::Logging.exception(message, error)
ee360810 Michael Moll
process_success :success_msg => _("Enabled %s for rebuild on next boot") % @host, :success_redirect => :back
6e916e52 Shlomi Zadok
end
else
ee360810 Michael Moll
process_success :success_msg => _("Enabled %s for rebuild on next boot") % @host, :success_redirect => :back
6e916e52 Shlomi Zadok
end
8613dec9 Ohad Levy
else
bfbf7ed8 Lukas Zapletal
process_error :redirect => :back, :error_msg => _("Failed to enable %{host} for installation: %{errors}") % { :host => @host, :errors => @host.errors.full_messages }
8613dec9 Ohad Levy
end
end
b0d3f4ee Ohad Levy
7700f32f Frank Sweetser
def cancelBuild
86744a6b Ohad Levy
if @host.built(false)
630061d2 Michael Moll
process_success :success_msg => _("Canceled pending build for %s") % @host.name, :success_redirect => :back
7700f32f Frank Sweetser
else
bfa131a8 Dominic Cleal
process_error :redirect => :back, :error_msg => _("Failed to cancel pending build for %{hostname} with the following errors: %{errors}") % {:hostname => @host.name, :errors => @host.errors.full_messages.join(', ')}
7700f32f Frank Sweetser
end
end

334d0359 Amos Benari
def power
cbb5c847 Timo Goebel
return invalid_request unless PowerManager::REAL_ACTIONS.include?(params[:power_action])
40df7dfb Daniel Lobato
@host.power.send(params[:power_action].to_sym)
e07a21c9 Sam Kottler
process_success :success_redirect => :back, :success_msg => _("%{host} is about to %{action}") % { :host => @host, :action => _(params[:power_action].downcase) }
40df7dfb Daniel Lobato
rescue => e
process_error :redirect => :back, :error_msg => _("Failed to %{action} %{host}: %{e}") % { :action => _(params[:power_action]), :host => @host, :e => e }
end

901fe896 Ondrej Prazak
def get_power_state
fc053564 Dominic Cleal
result = {:id => @host.id}.merge(host_power_state(:na))
901fe896 Ondrej Prazak
if @host.supports_power?
result = host_power_ping result
else
fc053564 Dominic Cleal
result[:statusText] = _('Power operations are not enabled on this host.')
901fe896 Ondrej Prazak
end

render :json => result
rescue => e
Foreman::Logging.exception("Failed to fetch power status", e)
fc053564 Dominic Cleal
result.merge!(host_power_state(:na))
result[:statusText] = _("Failed to fetch power status: %s") % e
901fe896 Ondrej Prazak
render :json => result
end

bf59cec1 Tomer Brisker
def overview
render :partial => 'overview', :locals => { :host => @host }
rescue ActionView::Template::Error => exception
process_ajax_error exception, 'fetch overview information'
end

40df7dfb Daniel Lobato
def bmc
render :partial => 'bmc', :locals => { :host => @host }
a933fc25 Marek Hulan
rescue ActionView::Template::Error => exception
88ed4900 Amos Benari
process_ajax_error exception, 'fetch bmc information'
end

def vm
@vm = @host.compute_resource.find_vm_by_uuid(@host.uuid)
@compute_resource = @host.compute_resource
render :partial => "compute_resources_vms/details"
f694d292 Amir Fefer
rescue ActiveRecord::RecordNotFound, ActionView::Template::Error => exception
88ed4900 Amos Benari
process_ajax_error exception, 'fetch vm information'
40df7dfb Daniel Lobato
end

bf59cec1 Tomer Brisker
def runtime
render :partial => 'runtime'
rescue ActionView::Template::Error => exception
process_ajax_error exception, 'fetch runtime chart information'
end

def resources
render :partial => 'resources'
rescue ActionView::Template::Error => exception
process_ajax_error exception, 'fetch resources chart information'
end

def templates
1ef8f52b Ondrej Prazak
find_templates
render :partial => 'templates'
rescue => exception
bf59cec1 Tomer Brisker
process_ajax_error exception, 'fetch templates information'
end

43c4bd72 Marek Hulan
def nics
render :partial => 'nics'
rescue ActionView::Template::Error => exception
process_ajax_error exception, 'fetch interfaces information'
end

40df7dfb Daniel Lobato
def ipmi_boot
d370f4aa Marek Hulan
device = params[:ipmi_device]
device_id = BOOT_DEVICES.stringify_keys[device.downcase] || device
@host.ipmi_boot(device)
process_success :success_redirect => :back, :success_msg => _("%{host} now boots from %{device}") % { :host => @host.name, :device => _(device_id) }
rescue => e
process_error :redirect => :back, :error_msg => _("Failed to configure %{host} to boot from %{device}: %{e}") % { :device => _(device_id), :host => @host.name, :e => e }
334d0359 Amos Benari
end

197e2dce Ohad Levy
def console
return unless @host.compute_resource
@console = @host.compute_resource.console @host.uuid
1416a23d Timo Goebel
super
197e2dce Ohad Levy
rescue => e
01e78260 Ivan Nečas
Foreman::Logging.exception("Failed to set console", e)
ee360810 Michael Moll
process_error :redirect => :back, :error_msg => _("Failed to set console: %s") % e
197e2dce Ohad Levy
end

a67e7179 Paul Kelly
def toggle_manage
if @host.toggle! :managed
bfbf7ed8 Lukas Zapletal
if @host.managed
497c022b Tomer Brisker
@host.suggest_default_pxe_loader
ee360810 Michael Moll
msg = _("Foreman now manages the build cycle for %s") % @host.name
bfbf7ed8 Lukas Zapletal
else
ee360810 Michael Moll
msg = _("Foreman now no longer manages the build cycle for %s") % @host.name
bfbf7ed8 Lukas Zapletal
end
process_success :success_msg => msg, :success_redirect => :back
a67e7179 Paul Kelly
else
3dfb6e4c Dominic Cleal
process_error :error_msg => _("Failed to modify the build cycle for %s") % @host.name, :redirect => :back
a67e7179 Paul Kelly
end
end

9c0709db Jason Montleon
def disassociate
5a9ad12f Ori Rabin
if @host.compute?
3ccd0ef6 Jason Montleon
@host.disassociate!
ee360810 Michael Moll
process_success :success_msg => _("%s has been disassociated from VM") % @host.name, :success_redirect => :back
5a9ad12f Ori Rabin
else
process_error :error_msg => _("Host %s is not associated with a VM") % @host.name, :redirect => :back
9c0709db Jason Montleon
end
end

0f77c7f2 Ohad Levy
def pxe_config
b1997f52 Dominic Cleal
redirect_to(:controller => "unattended", :action => 'host_template', :kind => "pxe_#{@host.operatingsystem.pxe_type}_config", :host_id => @host) if @host
0f77c7f2 Ohad Levy
end

52538203 Ohad Levy
# multiple host selection methods

def multiple_parameters
8593fdde Ohad Levy
@parameters = HostParameter.where(:reference_id => @hosts).select("distinct name")
52538203 Ohad Levy
end

def update_multiple_parameters
if params[:name].empty?
cf94f62e Avi Sharvit
warning _("No parameters were allocated to the selected hosts, can't mass assign")
e263719a David Davis
redirect_to hosts_path
return
52538203 Ohad Levy
end

@skipped_parameters = {}
counter = 0
@hosts.each do |host|
skipped = []
params[:name].each do |name, value|
next if value.empty?
fb9f45e8 Daniel Lobato
if (host_param = host.host_parameters.friendly.find(name))
52538203 Ohad Levy
counter += 1 if host_param.update_attribute(:value, value)
else
skipped << name
end
@skipped_parameters[host.name] = skipped unless skipped.empty?
end
end
if @skipped_parameters.empty?
cf94f62e Avi Sharvit
success _('Updated all hosts!')
e263719a David Davis
redirect_to(hosts_path)
return
52538203 Ohad Levy
else
ee360810 Michael Moll
success _("%s Parameters updated, see below for more information") % counter
52538203 Ohad Levy
end
end

def select_multiple_hostgroup
end

def update_multiple_hostgroup
# simple validations
9d43fc71 Michael Moll
unless (id = params["hostgroup"]["id"])
9a280163 Dominic Cleal
error _('No host group selected!')
e263719a David Davis
redirect_to(select_multiple_hostgroup_hosts_path)
return
52538203 Ohad Levy
end
8b737c9c Joseph Magen
hg = Hostgroup.find_by_id(id)
68388bc2 Michael Moll
# update the hosts
4ebe38c7 Ohad Levy
@hosts.each do |host|
9d43fc71 Michael Moll
host.hostgroup = hg
017e1049 Ohad Levy
host.save(:validate => false)
52538203 Ohad Levy
end

cf94f62e Avi Sharvit
success _('Updated hosts: changed host group')
bf228dd6 Paul Kelly
# We prefer to go back as this does not lose the current search
redirect_back_or_to hosts_path
52538203 Ohad Levy
end

a92ee5bc Timo Goebel
def select_multiple_owner
end

def update_multiple_owner
# simple validations
9d43fc71 Michael Moll
if params[:owner].nil? || (id = params["owner"]["id"]).nil?
a92ee5bc Timo Goebel
error _('No owner selected!')
e263719a David Davis
redirect_to(select_multiple_owner_hosts_path)
return
a92ee5bc Timo Goebel
end

68388bc2 Michael Moll
# update the hosts
a92ee5bc Timo Goebel
@hosts.each do |host|
host.is_owned_by = id
host.save(:validate => false)
end

cf94f62e Avi Sharvit
success _('Updated hosts: changed owner')
a92ee5bc Timo Goebel
redirect_back_or_to hosts_path
end

8ca6c6bb Timo Goebel
def select_multiple_power_state
end

def update_multiple_power_state
action = params[:power][:action]
@hosts.each do |host|
begin
host.power.send(action.to_sym) if host.supports_power?
rescue => error
message = _('Failed to set power state for %s.') % host
Foreman::Logging.exception(message, error)
end
end

cf94f62e Avi Sharvit
success _('The power state of the selected hosts will be set to %s') % _(action)
8ca6c6bb Timo Goebel
redirect_back_or_to hosts_path
end

89569baa Jochen Schalanda
def multiple_destroy
end

1f927b16 Paul Kelly
def multiple_build
end

2fba6ad7 Ondrej Prazak
def rebuild_config
end

def submit_rebuild_config
all_fails = {}
@hosts.each do |host|
result = host.recreate_config
result.each_pair do |k, v|
all_fails[k] ||= []
all_fails[k] << host.name unless v
end
end

message = ''
all_fails.each_pair do |key, values|
unless values.empty?
message << ((n_("%{config_type} rebuild failed for host: %{host_names}.",
"%{config_type} rebuild failed for hosts: %{host_names}.",
values.count) % {:config_type => _(key), :host_names => values.to_sentence})) + " "
end
end

if message.blank?
cf94f62e Avi Sharvit
success _('Configuration successfully rebuilt')
2fba6ad7 Ondrej Prazak
else
error message
end
redirect_to hosts_path
end

1f927b16 Paul Kelly
def submit_multiple_build
d6814ff0 Timo Goebel
reboot = params[:host][:build] == '1' || false

ca59bac0 Dominic Cleal
missed_hosts = @hosts.select do |host|
d6814ff0 Timo Goebel
success = true
5f75d98a Ivan Necas
forward_url_options(host)
d6814ff0 Timo Goebel
begin
host.setBuild
host.power.reset if host.supports_power_and_running? && reboot
rescue => error
message = _('Failed to redeploy %s.') % host
Foreman::Logging.exception(message, error)
success = false
end
ca59bac0 Dominic Cleal
!success
80e0157c Paul Kelly
end
1f927b16 Paul Kelly
ca59bac0 Dominic Cleal
if missed_hosts.empty?
d6814ff0 Timo Goebel
if reboot
cf94f62e Avi Sharvit
success _("The selected hosts were enabled for reboot and rebuild")
d6814ff0 Timo Goebel
else
cf94f62e Avi Sharvit
success _("The selected hosts will execute a build operation on next reboot")
d6814ff0 Timo Goebel
end
1a51088d Ohad Levy
else
ca59bac0 Dominic Cleal
error _("The following hosts failed the build operation: %s") % missed_hosts.map(&:name).to_sentence
1a51088d Ohad Levy
end
1f927b16 Paul Kelly
redirect_to(hosts_path)
end

89569baa Jochen Schalanda
def submit_multiple_destroy
# keep all the ones that were not deleted for notification.
ca59bac0 Dominic Cleal
missed_hosts = @hosts.select {|host| !host.destroy}
if missed_hosts.empty?
cf94f62e Avi Sharvit
success _("Destroyed selected hosts")
1a51088d Ohad Levy
else
ca59bac0 Dominic Cleal
error _("The following hosts were not deleted: %s") % missed_hosts.map(&:name).to_sentence
1a51088d Ohad Levy
end
89569baa Jochen Schalanda
redirect_to(hosts_path)
end

58b01247 Eric Shamow
def multiple_disable
end

def submit_multiple_disable
toggle_hostmode false
end

def multiple_enable
end

def submit_multiple_enable
toggle_hostmode
end

9c0709db Jason Montleon
def multiple_disassociate
5a9ad12f Ori Rabin
@non_physical_hosts = @hosts.with_compute_resource
@physical_hosts = @hosts.to_a - @non_physical_hosts.to_a
9c0709db Jason Montleon
end

def update_multiple_disassociate
@hosts.each do |host|
3ccd0ef6 Jason Montleon
host.disassociate!
9c0709db Jason Montleon
end
cf94f62e Avi Sharvit
success _('Updated hosts: Disassociated from VM')
9c0709db Jason Montleon
redirect_back_or_to hosts_path
end

6e8defed Ohad Levy
def errors
348ec9c0 Sebastian Gräßl
merge_search_filter("#{origin_intervals_query('>').join(' or ')} and (status.failed > 0 or status.failed_restarts > 0)")
bfbf7ed8 Lukas Zapletal
index _("Hosts with errors")
6e8defed Ohad Levy
end

def active
348ec9c0 Sebastian Gräßl
merge_search_filter("#{origin_intervals_query('>').join(' or ')} and (status.applied > 0 or status.restarted > 0)")
bfbf7ed8 Lukas Zapletal
index _("Active Hosts")
6e8defed Ohad Levy
end

9b41cf08 Ohad Levy
def pending
348ec9c0 Sebastian Gräßl
merge_search_filter("#{origin_intervals_query('>').join(' or ')} and (status.pending > 0)")
bfbf7ed8 Lukas Zapletal
index _("Pending Hosts")
9b41cf08 Ohad Levy
end

6e8defed Ohad Levy
def out_of_sync
348ec9c0 Sebastian Gräßl
merge_search_filter("#{origin_intervals_query('<').join(' or ')} and status.enabled = true")
ee360810 Michael Moll
index _("Hosts which didn't report in the last %s") % reported_origin_interval_settings.map { |origin, interval| "#{interval} minutes for #{origin}" }.join(' or ')
6e8defed Ohad Levy
end

def disabled
17637a75 Ohad Levy
merge_search_filter("status.enabled = false")
bfbf7ed8 Lukas Zapletal
index _("Hosts with notifications disabled")
6e8defed Ohad Levy
end

e5d3f34e Ohad Levy
def process_hostgroup
feacea35 Amos Benari
@hostgroup = Hostgroup.find(params[:host][:hostgroup_id]) if params[:host][:hostgroup_id].to_i > 0
743a5d9c Ohad Levy
return head(:not_found) unless @hostgroup
265e1d98 orrabin
refresh_host
@host.attributes = host.apply_inherited_attributes(host_params) unless @host.new_record?
743a5d9c Ohad Levy
d301d11d Ondrej Prazak
@host.set_hostgroup_defaults true
19d9e229 Shimon Shtein
@host.set_compute_attributes unless params[:host][:compute_profile_id]
007bf254 Shimon Shtein
set_class_variables(@host)
66afbc33 Joseph Mitchell Magen
render :partial => "form"
e5d3f34e Ohad Levy
end

611f5bff Amos Benari
def process_taxonomy
66afbc33 Joseph Mitchell Magen
return head(:not_found) unless @location || @organization
265e1d98 orrabin
refresh_host
66afbc33 Joseph Mitchell Magen
# revert compute resource to "Bare Metal" (nil) if selected
# compute resource is not included taxonomy
4f7a4d0b David Davis
Taxonomy.as_taxonomy @organization, @location do
66afbc33 Joseph Mitchell Magen
# if compute_resource_id is not in our scope, reset it to nil.
@host.compute_resource_id = nil unless ComputeResource.exists?(@host.compute_resource_id)
611f5bff Amos Benari
end
66afbc33 Joseph Mitchell Magen
render :partial => 'form'
611f5bff Amos Benari
end

585329f5 Marek Hulan
# on persisted record calling has_many `relations=` triggers saving/deletion immediately
# so we have to filter such parameters
# we don't need any has_many relation to determine what proxies are used and the view
# renders only resulting templates set so the rest of form is unaffected
69f9cb82 Ohad Levy
def template_used
ec3360d9 Daniel Lobato Garcia
host = params[:id] ? Host::Base.readonly.find(params[:id]) : Host.new
5cbba9ec Tomer Brisker
kind = params.delete(:provisioning)
ec3360d9 Daniel Lobato Garcia
host.attributes = host_attributes_for_templates(host)
5cbba9ec Tomer Brisker
templates = host.available_template_kinds(kind)
69f9cb82 Ohad Levy
return not_found if templates.empty?
6e916e52 Shlomi Zadok
render :partial => 'provisioning', :locals => { :templates => templates }
69f9cb82 Ohad Levy
end

9ca77d08 Timo Goebel
def preview_host_collection
scope = Template.descendants.detect { |klass| klass.name == params[:scope] } || Template
@hosts = scope.preview_host_collection.where("name LIKE :name", :name => "%#{params['q']}%").limit(10).pluck(:id, :name).map {|id, name| {:id => id, :name => name}}
respond_to do |format|
68b3c50d Tomer Brisker
format.json { render :json => @hosts }
9ca77d08 Timo Goebel
end
end

8bfaec2a Joseph Mitchell Magen
private
298756ca Amos Benari
acfbc458 Marek Hulan
def resource_base
@resource_base ||= Host.authorized(current_permission, Host)
end

007bf254 Shimon Shtein
define_action_permission [
'clone', 'externalNodes', 'overview', 'bmc', 'vm', 'runtime', 'resources', 'templates', 'nics',
1d1e4dab Ewoud Kohl van Wijngaarden
'pxe_config', 'active', 'errors', 'out_of_sync', 'pending', 'disabled', 'get_power_state', 'preview_host_collection'
d6641b26 Tomer Brisker
], :view
007bf254 Shimon Shtein
define_action_permission [
'setBuild', 'cancelBuild', 'multiple_build', 'submit_multiple_build', 'review_before_build',
d6641b26 Tomer Brisker
'rebuild_config', 'submit_rebuild_config'
], :build
007bf254 Shimon Shtein
define_action_permission 'power', :power
define_action_permission 'ipmi_boot', :ipmi_boot
define_action_permission 'console', :console
define_action_permission [
'toggle_manage', 'multiple_parameters', 'update_multiple_parameters',
'select_multiple_hostgroup', 'update_multiple_hostgroup',
'multiple_disable', 'submit_multiple_disable',
'multiple_enable', 'submit_multiple_enable',
'update_multiple_organization', 'select_multiple_organization',
'update_multiple_location', 'select_multiple_location',
'disassociate', 'update_multiple_disassociate', 'multiple_disassociate',
'select_multiple_owner', 'update_multiple_owner',
d6641b26 Tomer Brisker
'select_multiple_power_state', 'update_multiple_power_state', 'random_name'
], :edit
007bf254 Shimon Shtein
define_action_permission ['multiple_destroy', 'submit_multiple_destroy'], :destroy
acfbc458 Marek Hulan
8bfaec2a Joseph Mitchell Magen
def refresh_host
5cbba9ec Tomer Brisker
@host = Host::Base.authorized(:view_hosts, Host).find_by_id(params.delete(:host_id))
265e1d98 orrabin
@host ||= Host.new(host_params)

unless @host.is_a?(Host::Managed)
@host = @host.becomes(Host::Managed)
@host.type = "Host::Managed"
8bfaec2a Joseph Mitchell Magen
end
265e1d98 orrabin
@host.attributes = host_params unless @host.new_record?
96144a47 Daniel Lobato
265e1d98 orrabin
@host.lookup_values.each(&:validate_value)
96144a47 Daniel Lobato
@host
995b1748 Amos Benari
end

796352ed Greg Sutcliffe
def set_host_type
287082a5 David Davis
return unless params[:host] && params[:host][:type]
68388bc2 Michael Moll
type = params[:host].delete(:type) # important, otherwise mass assignment will save the type.
cd032085 Daniel Lobato
if type.constantize.new.is_a?(Host::Base)
feacea35 Amos Benari
@host = @host.becomes(type.constantize)
@host.type = type
else
ee360810 Michael Moll
error _("invalid type: %s requested") % type
feacea35 Amos Benari
render :unprocessable_entity
796352ed Greg Sutcliffe
end
rescue => e
01e78260 Ivan Nečas
Foreman::Logging.exception("Something went wrong while changing host type", e)
ee360810 Michael Moll
error _("Something went wrong while changing host type - %s") % e
796352ed Greg Sutcliffe
end

8b737c9c Joseph Magen
# overwrite application_controller
def find_resource
e263719a David Davis
if (id = params[:id]).blank?
not_found
return false
end
fb9f45e8 Daniel Lobato
@host = resource_base.friendly.find(id)
27752930 kgaikwad
@host ||= resource_base.find_by_mac params[:host][:mac].to_s if params[:host] && params[:host][:mac]
8b737c9c Joseph Magen
e263719a David Davis
unless @host
not_found
return(false)
end

acfbc458 Marek Hulan
@host
9bbcf6a4 Ohad Levy
end

13a7bf0d amirfefer
def multiple_with_filter?
params.key?(:search)
end

52538203 Ohad Levy
def find_multiple
ffedb85d Tomer Brisker
# Lets search by name or id and make sure one of them exists first
13a7bf0d amirfefer
if params.key?(:host_names) || params.key?(:host_ids) || multiple_with_filter?
@hosts = resource_base.search_for(params[:search]) if multiple_with_filter?
@hosts ||= resource_base.where("hosts.id IN (?) or hosts.name IN (?)", params[:host_ids], params[:host_names])
2b0af5e7 Ohad Levy
if @hosts.empty?
13a7bf0d amirfefer
error _('No hosts were found with that id, name or query filter')
e263719a David Davis
redirect_to(hosts_path)
return false
2b0af5e7 Ohad Levy
end
else
9a280163 Dominic Cleal
error _('No hosts selected')
e263719a David Davis
redirect_to(hosts_path)
return false
52538203 Ohad Levy
end
2b0af5e7 Ohad Levy
5f5b13a9 Michael Moll
@hosts
01e78260 Ivan Nečas
rescue => error
message = _("Something went wrong while selecting hosts - %s") % error
error(message)
Foreman::Logging.exception(message, error)
e263719a David Davis
redirect_to hosts_path
5f5b13a9 Michael Moll
false
52538203 Ohad Levy
end

5f029ed6 Daniel Lobato
def toggle_hostmode(mode = true)
58b01247 Eric Shamow
# keep all the ones that were not disabled for notification.
ca59bac0 Dominic Cleal
missed_hosts = @hosts.select { |host| !host.update_attribute(:enabled, mode) }
58b01247 Eric Shamow
action = mode ? "enabled" : "disabled"

ca59bac0 Dominic Cleal
if missed_hosts.empty?
ee360810 Michael Moll
success _("%s selected hosts") % action.capitalize
078fbb59 Ohad Levy
else
ca59bac0 Dominic Cleal
error _("The following hosts were not %{action}: %{missed_hosts}") % { :action => action, :missed_hosts => missed_hosts.map(&:name).to_sentence }
078fbb59 Ohad Levy
end
67799065 Ohad Levy
redirect_to(hosts_path)
58b01247 Eric Shamow
end

90b83222 Ohad Levy
# this is required for template generation (such as pxelinux) which is not done via a web request
5f75d98a Ivan Necas
def forward_url_options(host = @host)
host.url_options = url_options if @host.respond_to?(:url_options)
90b83222 Ohad Levy
end

5f029ed6 Daniel Lobato
def merge_search_filter(filter)
17637a75 Ohad Levy
if params[:search].empty?
params[:search] = filter
else
params[:search] += " and #{filter}"
end
end

30ae12bf Ohad Levy
# if a save failed and the only reason was network conflicts then flag this so that the view
# is rendered differently and the next save operation will be forced
def offer_to_overwrite_conflicts
287082a5 David Davis
@host.overwrite = "true" if @host.errors.any? && @host.errors.are_all_conflicts?
30ae12bf Ohad Levy
end
8ca6c6bb Timo Goebel
def validate_power_action
9d43fc71 Michael Moll
if params[:power].blank? || (action = params[:power][:action]).blank? ||
8ca6c6bb Timo Goebel
!PowerManager::REAL_ACTIONS.include?(action)
error _('No or invalid power state selected!')
e263719a David Davis
redirect_to(select_multiple_power_state_hosts_path)
33a09887 Michael Moll
false
8ca6c6bb Timo Goebel
end
end
5131edbf Timo Goebel
def validate_multiple_puppet_proxy
fbb47ea5 Timo Goebel
validate_multiple_proxy(select_multiple_puppet_proxy_hosts_path)
end

def validate_multiple_puppet_ca_proxy
validate_multiple_proxy(select_multiple_puppet_ca_proxy_hosts_path)
end

def validate_multiple_proxy(redirect_path)
if params[:proxy].nil? || (proxy_id = params[:proxy][:proxy_id]).nil?
error _('No proxy selected!')
e263719a David Davis
redirect_to(redirect_path)
return false
5131edbf Timo Goebel
end

85021506 Michael Moll
if proxy_id.present? && !SmartProxy.find_by_id(proxy_id)
fbb47ea5 Timo Goebel
error _('Invalid proxy selected!')
e263719a David Davis
redirect_to(redirect_path)
return false
5131edbf Timo Goebel
end
end
fbb47ea5 Timo Goebel
def update_multiple_proxy(proxy_type, host_update_method)
proxy_id = params[:proxy][:proxy_id]
if proxy_id
proxy = SmartProxy.find_by_id(proxy_id)
else
proxy = nil
end

failed_hosts = {}

@hosts.each do |host|
begin
host.send(host_update_method, proxy)
host.save!
rescue => error
failed_hosts[host.name] = error
message = _('Failed to set %{proxy_type} proxy for %{host}.') % {:host => host, :proxy_type => proxy_type}
Foreman::Logging.exception(message, error)
end
end

if failed_hosts.empty?
if proxy
cf94f62e Avi Sharvit
success _('The %{proxy_type} proxy of the selected hosts was set to %{proxy_name}') % {:proxy_name => proxy.name, :proxy_type => proxy_type}
fbb47ea5 Timo Goebel
else
cf94f62e Avi Sharvit
success _('The %{proxy_type} proxy of the selected hosts was cleared') % {:proxy_type => proxy_type}
fbb47ea5 Timo Goebel
end
else
error n_("The %{proxy_type} proxy could not be set for host: %{host_names}.",
b9df73be Ohad Levy
"The %{proxy_type} puppet ca proxy could not be set for hosts: %{host_names}",
fbb47ea5 Timo Goebel
failed_hosts.count) % {:proxy_type => proxy_type, :host_names => failed_hosts.map {|h, err| "#{h} (#{err})"}.to_sentence}
end
redirect_back_or_to hosts_path
end
1ef8f52b Ondrej Prazak
def find_templates
find_resource
@templates = TemplateKind.order(:name).map do |kind|
@host.provisioning_template(:kind => kind.name)
end.compact
raise Foreman::Exception.new(N_("No templates found")) if @templates.empty?
end
901fe896 Ondrej Prazak
def host_power_ping(result)
timeout = 3
Timeout.timeout(timeout) do
fc053564 Dominic Cleal
result.merge!(host_power_state(@host.supports_power_and_running? ? :on : :off))
901fe896 Ondrej Prazak
end
result
rescue Timeout::Error
fc053564 Dominic Cleal
logger.debug("Failed to retrieve power status for #{@host} within #{timeout} seconds.")
result[:statusText] = n_("Failed to retrieve power status for %{host} within %{timeout} second.",
"Failed to retrieve power status for %{host} within %{timeout} seconds.", timeout) %
{:host => @host, :timeout => timeout}
901fe896 Ondrej Prazak
result
end
fc053564 Dominic Cleal
def host_power_state(key)
HOST_POWER[key].merge(:title => _(HOST_POWER[key][:title]))
end
ec3360d9 Daniel Lobato Garcia
def host_attributes_for_templates(host)
# This method wants to only get the attributes applicable to the current
# kind of host. For example 'is_owned_by', even if it's in host_params,
# should be ignored by Host::Discovered or any other Host class that does
# not have that attribute
b3fb472c Daniel Lobato Garcia
host_attributes = host.class.attribute_names.dup
if host_params["compute_attributes"].present?
host_attributes << 'compute_attributes'
end
3cd8c84b Michael Moll
host_params.select do |k, v|
68b3c50d Tomer Brisker
host_attributes.include?(k) && !k.end_with?('_ids')
ec3360d9 Daniel Lobato Garcia
end.except(:host_parameters_attributes)
end
229195a5 Tomer Brisker
def csv_columns
c8f5cd53 Tomer Brisker
[:name, :operatingsystem, :environment, :compute_resource_or_model, :hostgroup, :last_report]
229195a5 Tomer Brisker
end
80dc430e Ohad Levy
348ec9c0 Sebastian Gräßl
def origin_intervals_query(compare_with)
reported_origin_interval_settings.map do |origin, interval|
"(origin = #{origin} and last_report #{compare_with} \"#{interval + Setting[:outofsync_interval]} minutes ago\")"
end
end

def reported_origin_interval_settings
Hash[Report.origins.map do |origin|
[origin, Setting[:"#{origin.downcase}_interval"].to_i]
end]
end
2f077f63 Ohad Levy
end