Project

General

Profile

« Previous | Next » 

Revision 9d43fc71

Added by Michael Moll almost 6 years ago

Fixes #19789 - fix Layout/SpaceAroundOperators cop

View differences:

.rubocop_todo.yml
Layout/MultilineOperationIndentation:
Enabled: false
# Offense count: 941
# Cop supports --auto-correct.
# Configuration parameters: AllowForAlignment.
Layout/SpaceAroundOperators:
Enabled: false
# Offense count: 95
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
......
# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
# URISchemes: http, https
Metrics/LineLength:
Max: 385
Max: 340
# Offense count: 522
# Configuration parameters: CountComments.
app/controllers/api/base_controller.rb
end
def add_version_header
response.headers["Foreman_version"]= SETTINGS[:version].full
response.headers["Foreman_api_version"]= api_version
response.headers["Foreman_version"] = SETTINGS[:version].full
response.headers["Foreman_api_version"] = api_version
end
# this method is used with nested resources, where obj_id is passed into the parameters hash.
app/controllers/api/v2/hostgroup_classes_controller.rb
api :GET, "/hostgroups/:hostgroup_id/puppetclass_ids/", N_("List all Puppet class IDs for host group")
def index
render :json => { root_node_name => HostgroupClass.where(:hostgroup_id => @hostgroup.id).pluck('puppetclass_id') }
render :json => { root_node_name => HostgroupClass.where(:hostgroup_id => @hostgroup.id).pluck('puppetclass_id') }
end
api :POST, "/hostgroups/:hostgroup_id/puppetclass_ids", N_("Add a Puppet class to host group")
app/controllers/api/v2/parameters_controller.rb
def find_parameter
# nested_obj is required, so no need to check here
@parameters = nested_obj.send(parameters_method).authorized(current_permission)
@parameters = nested_obj.send(parameters_method).authorized(current_permission)
@parameter = @parameters.from_param(params[:id])
@parameter ||= @parameters.friendly.find(params[:id])
return @parameter if @parameter.present?
app/controllers/application_controller.rb
end
def errors_hash(errors)
errors.any? ? {:status => N_("Error"), :message => errors.full_messages.join('<br>')} : {:status => N_("OK"), :message =>""}
errors.any? ? {:status => N_("Error"), :message => errors.full_messages.join('<br>')} : {:status => N_("OK"), :message => ""}
end
def taxonomy_scope
app/controllers/compute_resources_controller.rb
# This can happen in development when removing a plugin
rescue_from ActiveRecord::SubclassNotFound do |e|
type = (e.to_s =~ /failed to locate the subclass: '((\w|::)+)'/) ? Regexp.last_match(1) : 'STI-Type'
render :plain => (e.to_s+"<br><b>run ComputeResource.where(:type=>'#{type}').delete_all to recover.</b>").html_safe, :status=> :internal_server_error
render :plain => (e.to_s + "<br><b>run ComputeResource.where(:type=>'#{type}').delete_all to recover.</b>").html_safe, :status => :internal_server_error
end
def index
app/controllers/compute_resources_vms_controller.rb
def create
params[:vm].permit!
if (vm = @compute_resource.create_vm params[:vm])
@compute_resource.start_vm(vm.identity) if params[:vm][:start]=='1'
@compute_resource.start_vm(vm.identity) if params[:vm][:start] == '1'
process_success :success_redirect => compute_resource_vms_path(@compute_resource)
else
process_error :redirect => new_compute_resource_vm_path(@compute_resource), :object => @compute_resource
app/controllers/concerns/api/v2/lookup_keys_common_controller.rb
id = params.key?('smart_class_parameter_id') ? params['smart_class_parameter_id'] : params['id']
@smart_class_parameter = PuppetclassLookupKey.authorized(:view_external_parameters).smart_class_parameters.find_by_id(id.to_i) if id.to_i > 0
@smart_class_parameter ||= begin
puppet_cond = { 'environment_classes.puppetclass_id'=> @puppetclass.id } if @puppetclass
puppet_cond = { 'environment_classes.puppetclass_id' => @puppetclass.id } if @puppetclass
env_cond = { 'environment_classes.environment_id' => @environment.id } if @environment
PuppetclassLookupKey.authorized(:view_external_parameters).smart_class_parameters.where(puppet_cond).where(env_cond).where(:key => id).first
end
app/controllers/concerns/foreman/controller/auto_complete_search.rb
{:completed => CGI.escapeHTML(completed), :part => CGI.escapeHTML(part), :label => item, :category => category}
end
rescue ScopedSearch::QueryNotSupported => e
@items = [{:error =>e.to_s}]
@items = [{:error => e.to_s}]
end
render :json => @items
end
app/controllers/concerns/foreman/controller/bruteforce_protection.rb
extend ActiveSupport::Concern
def count_login_failure
Rails.cache.write("failed_login_#{request.ip}", get_login_failures+1, :expires_in => 5.minutes)
Rails.cache.write("failed_login_#{request.ip}", get_login_failures + 1, :expires_in => 5.minutes)
end
def get_login_failures
app/controllers/concerns/foreman/controller/puppet/hosts_controller_extensions.rb
module Foreman::Controller::Puppet::HostsControllerExtensions
extend ActiveSupport::Concern
PUPPETMASTER_ACTIONS=[ :externalNodes, :lookup ]
PUPPET_AJAX_REQUESTS=%w{hostgroup_or_environment_selected puppetclass_parameters}
PUPPETMASTER_ACTIONS = [ :externalNodes, :lookup ]
PUPPET_AJAX_REQUESTS = %w{hostgroup_or_environment_selected puppetclass_parameters}
MULTIPLE_EDIT_ACTIONS = %w(select_multiple_environment update_multiple_environment
select_multiple_puppet_proxy update_multiple_puppet_proxy
......
def update_multiple_environment
# simple validations
if params[:environment].nil? || (id=params["environment"]["id"]).nil?
if params[:environment].nil? || (id = params["environment"]["id"]).nil?
error _('No environment selected!')
redirect_to(select_multiple_environment_hosts_path)
return
......
def environment_from_param
# simple validations
if params[:environment].nil? || (id=params["environment"]["id"]).nil?
if params[:environment].nil? || (id = params["environment"]["id"]).nil?
error _('No environment selected!')
redirect_to(select_multiple_environment_hosts_path)
return
app/controllers/concerns/foreman/controller/taxonomy_multiple.rb
def update_multiple_taxonomies(type)
# simple validations
if params[type].nil? || (id=params[type][:id]).blank?
if params[type].nil? || (id = params[type][:id]).blank?
error "No #{type.to_s.classify} selected!"
redirect_to(hosts_path)
return
app/controllers/facts_controller.rb
@fact = FactName.find(params[:id])
begin
data = {:name => CGI.escapeHTML(@fact.name),
:values => FactValue.count_each(@fact.name).to_a.each{|v| v[:label]=CGI.escapeHTML(v[:label])}}
:values => FactValue.count_each(@fact.name).to_a.each{|v| v[:label] = CGI.escapeHTML(v[:label])}}
rescue
data = @fact
end
app/controllers/filters_controller.rb
def index
@filters = resource_base.includes(:role, :permissions).search_for(params[:search], :order => params[:order])
@filters = @filters.paginate(:page => params[:page], :per_page=> params[:per_page]) unless params[:paginate] == 'client'
@filters = @filters.paginate(:page => params[:page], :per_page => params[:per_page]) unless params[:paginate] == 'client'
@roles_authorizer = Authorizer.new(User.current, :collection => @filters.map(&:role_id))
end
app/controllers/hosts_controller.rb
include Foreman::Controller::CsvResponder
include Foreman::Controller::ConsoleCommon
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') }
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') }
MULTIPLE_ACTIONS = %w(multiple_parameters update_multiple_parameters select_multiple_hostgroup
update_multiple_hostgroup
multiple_destroy submit_multiple_destroy multiple_build
......
end
def compute_resource_selected
return not_found unless (params[:host] && (id=params[:host][:compute_resource_id]))
return not_found unless (params[:host] && (id = params[:host][:compute_resource_id]))
Taxonomy.as_taxonomy @organization, @location do
compute_profile_id = params[:host][:compute_profile_id] || Hostgroup.find_by_id(params[:host][:hostgroup_id]).try(:inherited_compute_profile_id)
compute_resource = ComputeResource.authorized(:view_compute_resources).find_by_id(id)
......
def update_multiple_hostgroup
# simple validations
unless (id=params["hostgroup"]["id"])
unless (id = params["hostgroup"]["id"])
error _('No host group selected!')
redirect_to(select_multiple_hostgroup_hosts_path)
return
......
hg = Hostgroup.find_by_id(id)
# update the hosts
@hosts.each do |host|
host.hostgroup=hg
host.hostgroup = hg
host.save(:validate => false)
end
......
def update_multiple_owner
# simple validations
if params[:owner].nil? || (id=params["owner"]["id"]).nil?
if params[:owner].nil? || (id = params["owner"]["id"]).nil?
error _('No owner selected!')
redirect_to(select_multiple_owner_hosts_path)
return
......
end
def validate_power_action
if params[:power].blank? || (action=params[:power][:action]).blank? ||
if params[:power].blank? || (action = params[:power][:action]).blank? ||
!PowerManager::REAL_ACTIONS.include?(action)
error _('No or invalid power state selected!')
redirect_to(select_multiple_power_state_hosts_path)
app/controllers/settings_controller.rb
# This can happen in development when removing a plugin
rescue_from ActiveRecord::SubclassNotFound do |e|
type = (e.to_s =~ /\'(Setting::.*)\'\./) ? Regexp.last_match(1) : 'STI-Type'
render :plain => (e.to_s+"<br><b>run Setting.where(:category=>'#{type}').delete_all to recover.</b>").html_safe, :status=> :internal_server_error
render :plain => (e.to_s + "<br><b>run Setting.where(:category=>'#{type}').delete_all to recover.</b>").html_safe, :status => :internal_server_error
end
def index
app/controllers/subnets_controller.rb
# query our subnet dhcp proxy for an unused IP
def freeip
unless (s=params[:subnet_id].to_i) > 0
unless (s = params[:subnet_id].to_i) > 0
invalid_request
return
end
app/helpers/application_helper.rb
def remove_link_to_function(text, options)
options.delete_if { |key, value| !options[key].to_s } # otherwise error during template render
title = (_("Click to remove %s") % options[:"data-class-name"])
link_to_function(text, "remove_puppet_class(this)", options.merge!(:'data-original-title'=> title))
link_to_function(text, "remove_puppet_class(this)", options.merge!(:'data-original-title' => title))
end
def link_to_add_puppetclass(klass, type)
......
end
def flot_pie_chart(name, title, data, options = {})
data = data.map { |k, v| {:label=>k.to_s.humanize, :data=>v} } if data.is_a?(Hash)
data = data.map { |k, v| {:label => k.to_s.humanize, :data => v} } if data.is_a?(Hash)
data.map{|element| element[:label] = truncate(element[:label], :length => 16)}
header = content_tag(:h4, options[:show_title] ? title : '', :class=>'ca pie-title', :'data-original-title'=>_("Expand the chart"), :rel=>'twipsy')
link_to_function(header, "expand_chart(this)")+
header = content_tag(:h4, options[:show_title] ? title : '', :class => 'ca pie-title', :'data-original-title' => _("Expand the chart"), :rel => 'twipsy')
link_to_function(header, "expand_chart(this)") +
content_tag(:div, nil,
{ :id => name,
:class => 'statistics-pie',
......
end
def flot_chart(name, xaxis_label, yaxis_label, data, options = {})
data = data.map { |k, v| {:label=>k.to_s.humanize, :data=>v} } if data.is_a?(Hash)
data = data.map { |k, v| {:label => k.to_s.humanize, :data => v} } if data.is_a?(Hash)
content_tag(:div, nil,
{ :id => name,
:class => 'statistics-chart',
......
:'legend-options' => options.delete(:legend),
:'xaxis-label' => xaxis_label,
:'yaxis-label' => yaxis_label,
:series => data
:series => data
}
}.merge(options))
end
def flot_bar_chart(name, xaxis_label, yaxis_label, data, options = {})
i=0
i = 0
ticks = nil
if data.is_a?(Array)
data = data.map do |kv|
ticks ||=[]
ticks << [i+=1, kv[0].to_s.humanize ]
ticks ||= []
ticks << [i += 1, kv[0].to_s.humanize ]
[i, kv[1]]
end
elsif data.is_a?(Hash)
data = data.map do |k, v|
ticks ||=[]
ticks << [i+=1, k.to_s.humanize ]
ticks ||= []
ticks << [i += 1, k.to_s.humanize ]
[i, v]
end
end
......
button_classes = %w(btn btn-default btn-action)
button_classes << 'btn-primary' if options[:primary]
content_tag(:div, options.merge(:class=>'btn-group')) do
content_tag(:div, options.merge(:class => 'btn-group')) do
# single button
if args.length == 1
content_tag(:span, args[0], :class => button_classes).html_safe
......
button = link_to(title.html_safe, '#',
:class => button_classes,
:'data-toggle' => 'dropdown')
dropdown_list = content_tag(:ul, :class=>"dropdown-menu pull-right") do
dropdown_list = content_tag(:ul, :class => "dropdown-menu pull-right") do
args.map { |option| content_tag(:li, option) }.join(" ").html_safe
end
button + dropdown_list
......
return if args.blank?
# single button
return content_tag(:span, args[0].html_safe, :class=>'btn btn-sm btn-default') if args.length == 1
return content_tag(:span, args[0].html_safe, :class => 'btn btn-sm btn-default') if args.length == 1
# multiple buttons
primary = args.delete_at(0).html_safe
primary = content_tag(:span, primary, :class=>'btn btn-sm btn-default') if primary !~ /btn/
primary = content_tag(:span, primary, :class => 'btn btn-sm btn-default') if primary !~ /btn/
content_tag(:div, :class => "btn-group") do
primary + link_to(content_tag(:span, '', :class=>'caret'), '#', :class=>"btn btn-default #{'btn-sm' if primary =~ /btn-sm/} dropdown-toggle", :'data-toggle'=>'dropdown') +
content_tag(:ul, :class=>"dropdown-menu pull-right") do
primary + link_to(content_tag(:span, '', :class => 'caret'), '#', :class => "btn btn-default #{'btn-sm' if primary =~ /btn-sm/} dropdown-toggle", :'data-toggle' => 'dropdown') +
content_tag(:ul, :class => "dropdown-menu pull-right") do
args.map{|option| content_tag(:li, option)}.join(" ").html_safe
end
end
app/helpers/audits_helper.rb
end
elsif !main_object? audit
["#{audit_action_name(audit).humanize} #{id_to_label audit.audited_changes.keys[0], audit.audited_changes.values[0]}
#{(audit_action_name(audit)=='removed') ? 'from' : 'to'} #{audit.associated_name || id_to_label(audit.audited_changes.keys[1], audit.audited_changes.values[1])}"]
#{(audit_action_name(audit) == 'removed') ? 'from' : 'to'} #{audit.associated_name || id_to_label(audit.audited_changes.keys[1], audit.audited_changes.values[1])}"]
else
[]
end
app/helpers/autosign_helper.rb
module AutosignHelper
def autosign_form
button_tag(_("Create Autosign Entry"), :type => 'button', :class => 'btn btn-primary fr', :data => {:toggle => 'modal', :target =>'#autosignModal'}) if authorized_for(:controller => "SmartProxies::Autosign", :action => :create, :auth_object => @proxy)
button_tag(_("Create Autosign Entry"), :type => 'button', :class => 'btn btn-primary fr', :data => {:toggle => 'modal', :target => '#autosignModal'}) if authorized_for(:controller => "SmartProxies::Autosign", :action => :create, :auth_object => @proxy)
end
end
app/helpers/compute_resources_helper.rb
def power_action_html(vm)
if vm.ready?
{
:data => { :confirm =>_("Are you sure you want to power %{act} %{vm}?") % { :act => action_string(vm).downcase.strip, :vm => vm }},
:data => { :confirm => _("Are you sure you want to power %{act} %{vm}?") % { :act => action_string(vm).downcase.strip, :vm => vm }},
:class => "btn btn-danger"
}
else
......
{ :class => "btn btn-info" }
else
{
:data => { :confirm =>_("Are you sure you want to %{act} %{vm}?") % { :act => pause_action, :vm => vm } },
:data => { :confirm => _("Are you sure you want to %{act} %{vm}?") % { :act => pause_action, :vm => vm } },
:class => "btn btn-danger"
}
end
app/helpers/compute_resources_vms_helper.rb
link_to_if_authorized(_("Console"), hash_for_console_host_path().merge(:auth_object => host, :permission => 'console_hosts'),
{ :class => "btn btn-info" })
else
link_to(_("Console"), '#', {:disabled=> true, :class => "btn btn-info"})
link_to(_("Console"), '#', {:disabled => true, :class => "btn btn-info"})
end
end
......
def subnet_vpc_hash(subnets)
subnet_vpc_hash = {}
subnets.each{ |sub| subnet_vpc_hash[sub.subnet_id] = {:vpc_id =>sub.vpc_id, :subnet_name => sub.tag_set["Name"] || sub.subnet_id} }
subnets.each{ |sub| subnet_vpc_hash[sub.subnet_id] = {:vpc_id => sub.vpc_id, :subnet_name => sub.tag_set["Name"] || sub.subnet_id} }
subnet_vpc_hash
end
......
:permission => 'edit_compute_resources'),
:title => _("Associate VM to a Foreman host"),
:method => :put,
:class =>"btn btn-default"
:class => "btn btn-default"
)
end
app/helpers/dashboard_helper.rb
_('Manage'), {},
link_to_function(_('Save positions'), "save_position('#{save_positions_widgets_path}')"),
link_to(_('Reset to default'), reset_default_widgets_path, :method => :put),
content_tag(:li, '', :class=>'divider'),
content_tag(:li, _("Add widgets"), :class=>'nav-header'),
content_tag(:li, '', :class=>'widget-add') do
content_tag(:li, '', :class => 'divider'),
content_tag(:li, _("Add widgets"), :class => 'nav-header'),
content_tag(:li, '', :class => 'widget-add') do
widgets_to_add
end
),
......
end
def widget_data(widget)
{ :data => { :id => widget.id, :name => _(widget.name), :row => widget.row, :col => widget.col,
{ :data => { :id => widget.id, :name => _(widget.name), :row => widget.row, :col => widget.col,
:sizex => widget.sizex, :sizey => widget.sizey } }
end
......
start = Time.zone.now - interval_setting.minutes
(0..9).each do |i|
t = start + (interval.minutes * i)
data << [interval_setting - i*interval, hosts.run_distribution(t, t + interval.minutes).count]
data << [interval_setting - i * interval, hosts.run_distribution(t, t + interval.minutes).count]
end
data
end
......
def searchable_links(name, search, counter)
search += " and #{@data.filter}" if @data.filter.present?
content_tag :li do
content_tag(:span, raw('&nbsp;'), :class=>'label', :style => "background-color:" + report_color[counter]) +
raw('&nbsp;')+
link_to(name, hosts_path(:search => search), :class=>"dashboard-links") +
content_tag(:span, raw('&nbsp;'), :class => 'label', :style => "background-color:" + report_color[counter]) +
raw('&nbsp;') +
link_to(name, hosts_path(:search => search), :class => "dashboard-links") +
content_tag(:h4, @data.report[counter])
end
end
app/helpers/form_helper.rb
hidden_fields = ''
html_options["data-useds"] ||= "[]"
JSON.parse(html_options["data-useds"]).each do |disabled_value|
hidden_fields += f.hidden_field(attr_ids, :multiple => true, :value => disabled_value, :id=>'')
hidden_fields += f.hidden_field(attr_ids, :multiple => true, :value => disabled_value, :id => '')
end
unauthorized.each do |unauthorized_value|
hidden_fields += f.hidden_field(attr_ids, :multiple => true, :value => unauthorized_value, :id=>'')
hidden_fields += f.hidden_field(attr_ids, :multiple => true, :value => unauthorized_value, :id => '')
end
hidden_fields + f.collection_select(attr_ids, authorized.sort_by { |a| a.to_s },
:id, options.delete(:object_label_method) || :to_label, options.merge(:selected => selected_ids),
......
def radio_button_f(f, attr, options = {})
text = options.delete(:text)
value = options.delete(:value)
label_tag('', :class=>"radio-inline") do
label_tag('', :class => "radio-inline") do
f.radio_button(attr, value, options) + " #{text} "
end
end
......
if options[:file_name]
html = content_tag(:b) {options.delete(:file_name)}
html += content_tag(:hr)
html += content_tag(:div, :style=>"margin-bottom: 10px") {_("Choose a new file:")}
html += content_tag(:div, :style => "margin-bottom: 10px") {_("Choose a new file:")}
end
field(f, attr, options) do
(html ? html: " ") + (f.file_field attr, options)
(html ? html : " ") + (f.file_field attr, options)
end
end
......
def form_for(record_or_name_or_array, *args, &proc)
if args.last.is_a?(Hash)
args.last[:html] = {:class=>"form-horizontal well"}.merge(args.last[:html]||{})
args.last[:html] = {:class => "form-horizontal well"}.merge(args.last[:html] || {})
else
args << {:html=>{:class=>"form-horizontal well"}}
args << {:html => {:class => "form-horizontal well"}}
end
super record_or_name_or_array, *args, &proc
end
......
error = options.delete(:error) || f.object.errors[attr] if f && f.object.respond_to?(:errors)
help_inline = help_inline(options.delete(:help_inline), error)
help_inline += options[:help_inline_permanent] unless options[:help_inline_permanent].nil?
size_class = options.delete(:size) || "col-md-4"
size_class = options.delete(:size) || "col-md-4"
wrapper_class = options.delete(:wrapper_class) || "form-group"
label = options[:no_label] ? "" : add_label(options, f, attr)
app/helpers/home_helper.rb
end
def user_header
summary = avatar_image_tag(User.current, :class=>'avatar small') +
"#{User.current.to_label} " + content_tag(:span, "", :class=>'caret')
link_to(summary.html_safe, "#", :class => "dropdown-toggle nav-item-iconic", :'data-toggle'=>"dropdown", :id => "account_menu")
summary = avatar_image_tag(User.current, :class => 'avatar small') +
"#{User.current.to_label} " + content_tag(:span, "", :class => 'caret')
link_to(summary.html_safe, "#", :class => "dropdown-toggle nav-item-iconic", :'data-toggle' => "dropdown", :id => "account_menu")
end
end
app/helpers/hosts_helper.rb
def resources_chart(timerange = 1.day.ago)
applied, failed, restarted, failed_restarts, skipped = [], [], [], [], []
@host.reports.recent(timerange).each do |r|
applied << [r.reported_at.to_i*1000, r.applied ]
failed << [r.reported_at.to_i*1000, r.failed ]
restarted << [r.reported_at.to_i*1000, r.restarted ]
failed_restarts << [r.reported_at.to_i*1000, r.failed_restarts ]
skipped << [r.reported_at.to_i*1000, r.skipped ]
applied << [r.reported_at.to_i * 1000, r.applied ]
failed << [r.reported_at.to_i * 1000, r.failed ]
restarted << [r.reported_at.to_i * 1000, r.restarted ]
failed_restarts << [r.reported_at.to_i * 1000, r.failed_restarts ]
skipped << [r.reported_at.to_i * 1000, r.skipped ]
end
[{:label=>_("Applied"), :data=>applied, :color =>'#89A54E'},
{:label=>_("Failed"), :data=>failed, :color =>'#AA4643'},
{:label=>_("Failed restarts"), :data=>failed_restarts, :color =>'#EC971F'},
{:label=>_("Skipped"), :data=>skipped, :color =>'#80699B'},
{:label=>_("Restarted"), :data=>restarted, :color =>'#4572A7'}]
[{:label => _("Applied"), :data => applied, :color => '#89A54E'},
{:label => _("Failed"), :data => failed, :color => '#AA4643'},
{:label => _("Failed restarts"), :data => failed_restarts, :color => '#EC971F'},
{:label => _("Skipped"), :data => skipped, :color => '#80699B'},
{:label => _("Restarted"), :data => restarted, :color => '#4572A7'}]
end
def runtime_chart(timerange = 1.day.ago)
config, runtime = [], []
@host.reports.recent(timerange).each do |r|
config << [r.reported_at.to_i*1000, r.config_retrieval]
runtime << [r.reported_at.to_i*1000, r.runtime]
config << [r.reported_at.to_i * 1000, r.config_retrieval]
runtime << [r.reported_at.to_i * 1000, r.runtime]
end
[{:label=>_("Config Retrieval"), :data=> config, :color=>'#AA4643'}, {:label=>_("Runtime"), :data=> runtime, :color=>'#4572A7'}]
[{:label => _("Config Retrieval"), :data => config, :color => '#AA4643'}, {:label => _("Runtime"), :data => runtime, :color => '#4572A7'}]
end
def reports_show
......
form_tag @host, :id => 'days_filter', :method => :get, :class => "form form-inline" do
content_tag(:span, (_("Found %{count} reports from the last %{days} days") %
{ :days => select(nil, 'range', 1..number_of_days,
{:selected => @range}, {:style=>"float:none; width: #{width}em;", :onchange =>"$('#days_filter').submit();$(this).disabled();"}),
{ :days => select(nil, 'range', 1..number_of_days,
{:selected => @range}, {:style => "float:none; width: #{width}em;", :onchange => "$('#days_filter').submit();$(this).disabled();"}),
:count => @host.reports.recent(@range.days.ago).count }).html_safe)
end
end
......
link_to_if_authorized(_("Run puppet"), hash_for_puppetrun_host_path(:id => host).merge(:auth_object => host, :permission => 'puppetrun_hosts'),
:disabled => !Setting[:puppetrun],
:class => 'btn btn-default',
:title => _("Trigger a puppetrun on a node; requires that puppet run is enabled"))
:title => _("Trigger a puppetrun on a node; requires that puppet run is enabled"))
end
),
button_group(
......
return '' if nic.new_record?
if nic.link
status = '<i class="glyphicon glyphicon glyphicon-arrow-up interface-up" title="'+ _('Interface is up') +'"></i>'
status = '<i class="glyphicon glyphicon glyphicon-arrow-up interface-up" title="' + _('Interface is up') + '"></i>'
else
status = '<i class="glyphicon glyphicon glyphicon-arrow-down interface-down" title="'+ _('Interface is down') +'"></i>'
status = '<i class="glyphicon glyphicon glyphicon-arrow-down interface-down" title="' + _('Interface is down') + '"></i>'
end
status.html_safe
end
app/helpers/layout_helper.rb
end
def button_group(*elements)
content_tag(:div, :class=>"btn-group") { elements.join(" ").html_safe }
content_tag(:div, :class => "btn-group") { elements.join(" ").html_safe }
end
def search_bar(*elements)
......
def icon_text(i, text = "", opts = {})
opts[:kind] ||= "glyphicon"
(content_tag(:span, "", :class=>"#{opts[:kind] + ' ' + opts[:kind]}-#{i} #{opts[:class]}", :title => opts[:title]) + " " + text).html_safe
(content_tag(:span, "", :class => "#{opts[:kind] + ' ' + opts[:kind]}-#{i} #{opts[:class]}", :title => opts[:title]) + " " + text).html_safe
end
def alert(opts = {})
opts[:close] = true if opts[:close].nil?
opts[:close] = true if opts[:close].nil?
opts[:header] ||= _("Warning!")
opts[:text] ||= _("Alert")
html_class = "alert #{opts[:class]} "
html_class += 'alert-dismissable' if opts[:close]
html_class = "alert #{opts[:class]} "
html_class += 'alert-dismissable' if opts[:close]
content_tag :div, :class => html_class, :id => opts[:id] do
result = "".html_safe
result += alert_close if opts[:close]
app/helpers/lookup_keys_helper.rb
module LookupKeysHelper
def remove_child_link(name, f, opts = {})
opts[:class] = [opts[:class], "remove_nested_fields"].compact.join(" ")
f.hidden_field(opts[:method]||:_destroy) + link_to_function(name, "remove_child_node(this);", opts)
f.hidden_field(opts[:method] || :_destroy) + link_to_function(name, "remove_child_node(this);", opts)
end
def delete_child_link(name, f, opts = {})
......
def param_type_selector(f, options = {})
selectable_f f, :key_type, options_for_select(LookupKey::KEY_TYPES.map { |e| [_(e), e] }, f.object.key_type), {},
options.merge({ :disabled => (f.object.puppet? && !f.object.override), :size => "col-md-8", :class=> "without_select2",
options.merge({ :disabled => (f.object.puppet? && !f.object.override), :size => "col-md-8", :class => "without_select2",
:label_help => _("<dl>" +
"<dt>String</dt> <dd>Everything is taken as a string.</dd>" +
"<dt>Boolean</dt> <dd>Common representation of boolean values are accepted.</dd>" +
......
def validator_type_selector(f)
selectable_f f, :validator_type, options_for_select(LookupKey::VALIDATOR_TYPES.map { |e| [_(e), e] }, f.object.validator_type), {:include_blank => _("None")},
{ :disabled => (f.object.puppet? && !f.object.override), :size => "col-md-8", :class=> "without_select2",
{ :disabled => (f.object.puppet? && !f.object.override), :size => "col-md-8", :class => "without_select2",
:onchange => 'validatorTypeSelected(this)',
:label_help => _("<dl>" +
"<dt>List</dt> <dd>A list of the allowed values, specified in the Validator rule field.</dd>" +
......
link_to_function(icon_text('pencil-square-o', '', :kind => 'fa'), "override_class_param(this)",
:title => _("Override this value"),
:'data-tag' => 'override',
:class =>"btn btn-default btn-md btn-override #{'hide' if overridden}") +
:class => "btn btn-default btn-md btn-override #{'hide' if overridden}") +
link_to_function(icon_text('times', '', :kind => 'fa'), "override_class_param(this)",
:title => _("Remove this override"),
:'data-tag' => 'remove',
:class =>"btn btn-default btn-md btn-override #{'hide' unless overridden}")
:class => "btn btn-default btn-md btn-override #{'hide' unless overridden}")
end
def hidden_toggle(hidden, hide_icon = 'eye-slash', unhide_icon = 'eye', strikethrough = false)
return unless can_edit_params?
if strikethrough && !hidden
link_to_function(icon_text(hide_icon, '', :kind => 'fa'), "", :class =>"btn btn-default btn-md btn-hide", :disabled => "disabled", :rel => "twipsy", :title => _("This value is not hidden"))
link_to_function(icon_text(hide_icon, '', :kind => 'fa'), "", :class => "btn btn-default btn-md btn-hide", :disabled => "disabled", :rel => "twipsy", :title => _("This value is not hidden"))
else
link_to_function(icon_text(unhide_icon, '', :kind => 'fa'), "input_group_hidden(this)",
:title => _("Unhide this value"),
:class =>"btn btn-default btn-md btn-hide #{'hide' unless hidden}") +
:class => "btn btn-default btn-md btn-hide #{'hide' unless hidden}") +
link_to_function(icon_text(hide_icon, "", :class => ('btn-strike' if strikethrough).to_s, :kind => 'fa'), "input_group_hidden(this)",
:title => _("Hide this value"),
:class =>"btn btn-default btn-md btn-hide #{'hide' if hidden}")
:class => "btn btn-default btn-md btn-hide #{'hide' if hidden}")
end
end
app/helpers/operatingsystems_helper.rb
record.family
end
image_tag(family+".png", opts) + " "
image_tag(family + ".png", opts) + " "
end
def os_name(record, opts = {})
app/helpers/provisioning_templates_helper.rb
:text => ('<p>' + _("When editing a template, you must assign a list \
of operating systems which this template can be used with. Optionally, you can \
restrict a template to a list of host groups and/or environments.") + '</p>' +
'<p>'+ _("When a Host requests a template (e.g. during provisioning), Foreman \
'<p>' + _("When a Host requests a template (e.g. during provisioning), Foreman \
will select the best match from the available templates of that type, in the \
following order:") + '</p>' + '<ul>' +
'<li>' + _("Host group and Environment") + '</li>' +
app/helpers/puppetca_helper.rb
'revoked' => 'fa fa-ban' }
def state_filter
select_tag "Filter", options_for_select([[_('valid or pending'), _('valid')+'|'+_('pending')]] +
select_tag "Filter", options_for_select([[_('valid or pending'), _('valid') + '|' + _('pending')]] +
STATES.map{|s| _(s)} +
[[_('all'), '']]),
:class => "datatable-filter", :id => "puppetca-filter"
app/helpers/puppetclasses_and_environments_helper.rb
def import_proxy_links(hash, import_env_text = false, classes = nil)
import_from_text = import_env_text ? _("Import environments from %s") : _("Import classes from %s")
SmartProxy.with_features("Puppet").map do |proxy|
display_link_if_authorized(import_from_text % proxy.name, hash.merge(:proxy => proxy), {:class=>classes})
display_link_if_authorized(import_from_text % proxy.name, hash.merge(:proxy => proxy), {:class => classes})
end.flatten
end
app/helpers/reports_helper.rb
def report_event_column(event, style = "")
style = "label-default" if event == 0
content_tag(:span, event, :class=>'label ' + style)
content_tag(:span, event, :class => 'label ' + style)
end
def reports_since(builder)
......
form_tag config_report_path(@config_report), :id => 'level_filter', :method => :get, :class => "form form-horizontal" do
content_tag(:span, _("Show log messages:") + ' ') +
select(nil, 'level', [[_('All messages'), 'info'], [_('Notices, warnings and errors'), 'notice'], [_('Warnings and errors'), 'warning'], [_('Errors only'), 'error']],
{}, {:class=>"col-md-1 form-control", :onchange =>"filter_by_level(this);"})
{}, {:class => "col-md-1 form-control", :onchange => "filter_by_level(this);"})
end
end
app/helpers/taxonomy_helper.rb
end
def wizard_header(current, *args)
content_tag(:ul, :class=>"wizard") do
step=1
content_tag(:ul, :class => "wizard") do
step = 1
content = nil
args.each do |arg|
step_content = content_tag(:li, (content_tag(:span, step, :class=>"badge" +" #{'badge-inverse' if step==current}")+arg).html_safe, :class=>('active' if step==current).to_s)
step_content = content_tag(:li, (content_tag(:span, step, :class => "badge" + " #{'badge-inverse' if step == current}") + arg).html_safe, :class => ('active' if step == current).to_s)
(step == 1) ? content = step_content : content += step_content
step += 1
end
......
def taxonomy_selects(f, selected_ids, taxonomy, label, options = {}, options_html = {})
options[:disabled] = Array.wrap(options[:disabled])
options[:label] ||= _(label)
options[:label] ||= _(label)
multiple_selects f, label.downcase.singularize + '_ids', taxonomy.authorized("assign_#{label.downcase}", taxonomy), selected_ids, options, options_html
end
app/helpers/trends_helper.rb
def trendable_types
options = {_('Environment') => 'Environment', _('Operating system') => 'Operatingsystem',
_('Model') => 'Model', _('Facts') =>'FactName', _('Host group') => 'Hostgroup', _('Compute resource') => 'ComputeResource'}
_('Model') => 'Model', _('Facts') => 'FactName', _('Host group') => 'Hostgroup', _('Compute resource') => 'ComputeResource'}
existing = ForemanTrend.types.pluck(:trendable_type)
options.delete_if{ |k, v| existing.include?(v) }
end
def trend_days_filter
form_tag @trend, :id => 'days_filter', :method => :get, :class=>"form form-inline" do
form_tag @trend, :id => 'days_filter', :method => :get, :class => "form form-inline" do
content_tag(:span, (_("Trend of the last %s days.") %
select(nil, 'range', 1..Setting[:max_trend], {:selected => range},
{:onchange =>"$('#days_filter').submit();$(this).attr('disabled','disabled');;"})).html_safe)
{:onchange => "$('#days_filter').submit();$(this).attr('disabled','disabled');;"})).html_safe)
end
end
......
interval_start = ((counter.interval_start || from) > from) ? counter.interval_start : from
next_timestamp = counter.try(:interval_end) || Time.now.utc
# transform the timestamp values to flot format - from seconds in Ruby to milliseconds in flot
data << [interval_start.to_i*1000, counter.count]
data << [next_timestamp.to_i*1000 - 1, counter.count]
data << [interval_start.to_i * 1000, counter.count]
data << [next_timestamp.to_i * 1000 - 1, counter.count]
end
{:label => labels[value.id][0], :href=>labels[value.id][1], :data =>data, :color => chart_colors[idx % chart_colors.size()] } unless data.empty?
{:label => labels[value.id][0], :href => labels[value.id][1], :data => data, :color => chart_colors[idx % chart_colors.size()] } unless data.empty?
end.compact
end
app/helpers/unattended_helper.rb
include Foreman::Renderer
def ks_console
(@port && @baud) ? "console=ttyS#{@port},#{@baud}": ""
(@port && @baud) ? "console=ttyS#{@port},#{@baud}" : ""
end
def grub_pass
app/mailers/audit_mailer.rb
helper :audits, :layout
def summary(options = {})
raise ::Foreman::Exception.new(N_("Must specify a user with email enabled")) unless (user=User.unscoped.find(options[:user])) && user.mail_enabled?
raise ::Foreman::Exception.new(N_("Must specify a user with email enabled")) unless (user = User.unscoped.find(options[:user])) && user.mail_enabled?
time = options[:time] ? %(time >= "#{options[:time]}") : 'time > yesterday'
@query = options[:query].present? ? "#{options[:query]} and #{time}" : time.to_s
@count = Audit.authorized_as(user, :view_audit_logs, Audit).search_for(@query).count
app/mailers/host_mailer.rb
# sends out a summary email of hosts and their metrics (e.g. how many changes failures etc).
def summary(options = {})
raise ::Foreman::Exception.new(N_("Must specify a valid user with email enabled")) unless (user=User.find(options[:user]))
raise ::Foreman::Exception.new(N_("Must specify a valid user with email enabled")) unless (user = User.find(options[:user]))
hosts = Host::Managed.authorized_as(user, :view_hosts, Host)
time = options[:time] || 1.day.ago
host_data = ConfigReport.summarise(time, hosts.all).sort
......
private
def load_metrics(host_data)
total_metrics = {"failed"=>0, "restarted"=>0, "skipped"=>0, "applied"=>0, "failed_restarts"=>0}
total_metrics = {"failed" => 0, "restarted" => 0, "skipped" => 0, "applied" => 0, "failed_restarts" => 0}
host_data.flatten.delete_if { |x| true unless x.is_a?(Hash) }.each do |data_hash|
total_metrics["failed"] += data_hash[:metrics]["failed"]
app/models/compute_attribute.rb
def method_missing(method, *args, &block)
method = method.to_s
return super if method[-1]=="="
return super if method[-1] == "="
return super if method == 'vm_attrs'
if vm_attrs.has_key?(method)
app/models/compute_resources/foreman/model/ec2.rb
def console(uuid)
vm = find_vm_by_uuid(uuid)
vm.console_output.body.merge(:type=>'log', :name=>vm.name)
vm.console_output.body.merge(:type => 'log', :name => vm.name)
end
def destroy_vm(uuid)
app/models/compute_resources/foreman/model/gce.rb
end
args[:disks] = []
args[:volumes].each_with_index do |vol_args, i|
args[:disks] << new_volume(vol_args.merge(:name => "#{args[:name]}-disk#{i+1}"))
args[:disks] << new_volume(vol_args.merge(:name => "#{args[:name]}-disk#{i + 1}"))
end
end
app/models/compute_resources/foreman/model/libvirt.rb
# Listen address cannot be updated while the guest is running
# When we update the display password, we pass the existing listen address
vm.update_display(:password => password, :listen => vm.display[:listen], :type => vm.display[:type])
WsProxy.start(:host => hypervisor.hostname, :host_port => vm.display[:port], :password => password).merge(:type => vm.display[:type], :name=> vm.name)
WsProxy.start(:host => hypervisor.hostname, :host_port => vm.display[:port], :password => password).merge(:type => vm.display[:type], :name => vm.name)
rescue ::Libvirt::Error => e
if e.message =~ /cannot change listen address/
logger.warn e
......
vm_attrs[:memory] = nil
logger.debug("Compute attributes for VM '#{uuid}' diddn't contain :memory_size")
else
vm_attrs[:memory] = vm_attrs[:memory_size]*1024 # value is returned in megabytes, we need bytes
vm_attrs[:memory] = vm_attrs[:memory_size] * 1024 # value is returned in megabytes, we need bytes
end
vm_attrs
end
......
begin
vols = []
(volumes = args[:volumes]).each do |vol|
vol.name = "#{args[:prefix]}-disk#{volumes.index(vol)+1}"
vol.name = "#{args[:prefix]}-disk#{volumes.index(vol) + 1}"
vol.capacity = "#{vol.capacity}G" unless vol.capacity.to_s.end_with?('G')
vol.allocation = "#{vol.allocation}G" unless vol.allocation.to_s.end_with?('G')
vol.save
app/models/compute_resources/foreman/model/ovirt.rb
rating = 0.0
if os[:name].include?(os_name)
rating += 100
rating += (1.0/os[:name].length) # prefer the shorter names a bit in case we have not found more important some specifics
rating += (1.0 / os[:name].length) # prefer the shorter names a bit in case we have not found more important some specifics
rating += 10 if os[:name].include?("#{os_name}_#{host.operatingsystem.major}")
rating += 10 if arch_name && os[:name].include?(arch_name)
end
......
{
:search => params['search']['value'] || '',
:max => max,
:page => (params['start'].to_i / max)+1,
:page => (params['start'].to_i / max) + 1,
:without_details => true
}
end
......
end
def os_name_mapping(host)
(host.operatingsystem.name =~ /redhat|centos/i) ? 'rhel': host.operatingsystem.name.downcase
(host.operatingsystem.name =~ /redhat|centos/i) ? 'rhel' : host.operatingsystem.name.downcase
end
def arch_name_mapping(host)
app/models/compute_resources/foreman/model/rackspace.rb
super && flavors
rescue Excon::Errors::Unauthorized => e
errors[:base] << e.response.body
rescue Fog::Compute::Rackspace::Error, Excon::Errors::SocketError=> e
rescue Fog::Compute::Rackspace::Error, Excon::Errors::SocketError => e
errors[:base] << e.message
end
app/models/concerns/fog_extensions/ovirt/server.rb
def volumes_attributes=(attrs); end
def poweroff
service.vm_action(:id =>id, :action => :shutdown)
service.vm_action(:id => id, :action => :shutdown)
end
def reset
app/models/concerns/host_common.rb
# We encode the hw_model into the image file name as not all Sparc flashes can contain all possible hw_models. The user can always
# edit it if required or use symlinks if they prefer.
hw_model = model.try :hardware_model if defined?(model_id)
operatingsystem.interpolate_medium_vars(nfs_path, architecture.name, operatingsystem) +\
operatingsystem.interpolate_medium_vars(nfs_path, architecture.name, operatingsystem) + \
"#{operatingsystem.file_prefix}.#{architecture}#{hw_model.empty? ? '' : '.' + hw_model.downcase}.#{operatingsystem.image_extension}"
else
""
app/models/concerns/hostext/operating_system.rb
end
def jumpstart?
operatingsystem.family == "Solaris" && architecture.name =~/Sparc/i rescue false
operatingsystem.family == "Solaris" && architecture.name =~ /Sparc/i rescue false
end
end
end
app/models/concerns/hostext/search.rb
scoped_search :relation => :last_report_object, :on => :origin
scoped_search :relation => :configuration_status_object, :on => :status, :offset => 0, :word_size => ConfigReport::BIT_NUM*4, :rename => :'status.interesting', :complete_value => {:true => true, :false => false}, :only_explicit => true
scoped_search :relation => :configuration_status_object, :on => :status, :offset => 0, :word_size => ConfigReport::BIT_NUM * 4, :rename => :'status.interesting', :complete_value => {:true => true, :false => false}, :only_explicit => true
scoped_search_status "applied", :relation => :configuration_status_object, :on => :status, :rename => :'status.applied'
scoped_search_status "restarted", :relation => :configuration_status_object, :on => :status, :rename => :'status.restarted'
scoped_search_status "failed", :relation => :configuration_status_object, :on => :status, :rename => :'status.failed'
......
scoped_search :relation => :interfaces, :on => :mac, :complete_value => true, :rename => :has_mac, :only_explicit => true
scoped_search :relation => :puppetclasses, :on => :name, :complete_value => true, :rename => :class, :only_explicit => true, :operators => ['= ', '~ '], :ext_method => :search_by_puppetclass
scoped_search :relation => :fact_values, :on => :value, :in_key=> :fact_names, :on_key=> :name, :rename => :facts, :complete_value => true, :only_explicit => true, :ext_method => :search_cast_facts
scoped_search :relation => :search_parameters, :on => :value, :on_key=> :name, :complete_value => true, :rename => :params, :ext_method => :search_by_params, :only_explicit => true
scoped_search :relation => :fact_values, :on => :value, :in_key => :fact_names, :on_key => :name, :rename => :facts, :complete_value => true, :only_explicit => true, :ext_method => :search_cast_facts
scoped_search :relation => :search_parameters, :on => :value, :on_key => :name, :complete_value => true, :rename => :params, :ext_method => :search_by_params, :only_explicit => true
if SETTINGS[:locations_enabled]
scoped_search :relation => :location, :on => :title, :rename => :location, :complete_value => true, :only_explicit => true
app/models/config_report.rb
class ConfigReport < Report
METRIC = %w[applied restarted failed failed_restarts skipped pending]
BIT_NUM = 6
MAX = (1 << BIT_NUM) -1 # maximum value per metric
MAX = (1 << BIT_NUM) - 1 # maximum value per metric
scoped_search :on => :status, :offset => 0, :word_size => 4*BIT_NUM, :complete_value => {:true => true, :false => false}, :rename => :eventful
scoped_search :on => :status, :offset => 0, :word_size => 4 * BIT_NUM, :complete_value => {:true => true, :false => false}, :rename => :eventful
scoped_search_status 'applied', :on => :status, :rename => :applied
scoped_search_status 'restarted', :on => :status, :rename => :restarted
app/models/domain.rb
validates :fullname, :uniqueness => true, :allow_blank => true, :allow_nil => true
scoped_search :on => [:name, :fullname], :complete_value => true
scoped_search :relation => :domain_parameters, :on => :value, :on_key=> :name, :complete_value => true, :only_explicit => true, :rename => :params
scoped_search :relation => :domain_parameters, :on => :value, :on_key => :name, :complete_value => true, :only_explicit => true, :rename => :params
# with proc support, default_scope can no longer be chained
# include all default scoping here
app/models/fact_value.rb
has_one :parent_fact_name, :through => :fact_name, :source => :parent
scoped_search :on => :value, :in_key=> :fact_name, :on_key=> :name, :rename => :facts, :complete_value => true, :only_explicit => true, :ext_method => :search_cast_facts
scoped_search :on => :value, :in_key => :fact_name, :on_key => :name, :rename => :facts, :complete_value => true, :only_explicit => true, :ext_method => :search_cast_facts
scoped_search :on => :value, :default_order => true, :ext_method => :search_value_cast_facts
scoped_search :on => :updated_at, :rename => :reported_at, :only_explicit => true, :complete_value => true
scoped_search :on => :host_id, :only_explicit => true, :complete_value => false
......
else
k
end
output << {:label => label, :data =>v } unless v == 0
output << {:label => label, :data => v } unless v == 0
end
output
end
app/models/host/managed.rb
# this method accepts a puppets external node yaml output and generate a node in our setup
# it is assumed that you already have the node (e.g. imported by one of the rack tasks)
def importNode(nodeinfo)
myklasses= []
myklasses = []
# puppet classes
classes = nodeinfo["classes"]
classes = classes.keys if classes.is_a?(Hash)
......
def self.count_habtm(association)
counter = Host::Managed.joins(association.tableize.to_sym).group("#{association.tableize.to_sym}.id").reorder('').count
# Puppetclass.find(counter.keys.compact)...
association.camelize.constantize.find(counter.keys.compact).map {|i| {:label=>i.to_label, :data =>counter[i.id]}}
association.camelize.constantize.find(counter.keys.compact).map {|i| {:label => i.to_label, :data => counter[i.id]}}
end
def self.provision_methods
app/models/hostgroup.rb
}
scoped_search :on => :name, :complete_value => :true
scoped_search :relation => :group_parameters, :on => :value, :on_key=> :name, :complete_value => true, :only_explicit => true, :rename => :params
scoped_search :relation => :group_parameters, :on => :value, :on_key => :name, :complete_value => true, :only_explicit => true, :rename => :params
scoped_search :relation => :hosts, :on => :name, :complete_value => :true, :rename => "host", :only_explicit => true
scoped_search :relation => :puppetclasses, :on => :name, :complete_value => true, :rename => :class, :only_explicit => true, :operators => ['= ', '~ ']
scoped_search :relation => :environment, :on => :name, :complete_value => :true, :rename => :environment, :only_explicit => true
app/models/lookup_keys/lookup_key.rb
KEY_DELM = ","
EQ_DELM = "="
VALUE_REGEX =/\A[^#{KEY_DELM}]+#{EQ_DELM}[^#{KEY_DELM}]+(#{KEY_DELM}[^#{KEY_DELM}]+#{EQ_DELM}[^#{KEY_DELM}]+)*\Z/
VALUE_REGEX = /\A[^#{KEY_DELM}]+#{EQ_DELM}[^#{KEY_DELM}]+(#{KEY_DELM}[^#{KEY_DELM}]+#{EQ_DELM}[^#{KEY_DELM}]+)*\Z/
validates_lengths_from_database
app/models/medium.rb
has_many :hostgroups, :dependent => :nullify
# We need to include $ in this as $arch, $release, can be in this string
VALID_NFS_PATH=/\A([-\w\d\.]+):(\/[\w\d\/\$\.]+)\Z/
VALID_NFS_PATH = /\A([-\w\d\.]+):(\/[\w\d\/\$\.]+)\Z/
validates :name, :uniqueness => true, :presence => true
validates :path, :uniqueness => true, :presence => true,
:url_schema => ['http', 'https', 'ftp', 'nfs']
app/models/nic/bond.rb
attr_exportable :mode, :bond_options
MODES = %w(balance-rr active-backup balance-xor broadcast 802.3ad balance-tlb balance-alb)
MODES = %w(balance-rr active-backup balance-xor broadcast 802.3ad balance-tlb balance-alb)
validates :mode, :presence => true, :inclusion => { :in => MODES }
def add_slave(identifier)
app/models/operatingsystem.rb
scoped_search :relation => :architectures, :on => :name, :complete_value => :true, :rename => "architecture", :only_explicit => true
scoped_search :relation => :media, :on => :name, :complete_value => :true, :rename => "medium", :only_explicit => true
scoped_search :relation => :provisioning_templates, :on => :name, :complete_value => :true, :rename => "template", :only_explicit => true
scoped_search :relation => :os_parameters, :on => :value, :on_key=> :name, :complete_value => true, :rename => :params, :only_explicit => true
scoped_search :relation => :os_parameters, :on => :value, :on_key => :name, :complete_value => true, :rename => :params, :only_explicit => true
FAMILIES = { 'Debian' => %r{Debian|Ubuntu}i,
'Redhat' => %r{RedHat|Centos|Fedora|Scientific|SLC|OracleLinux}i,
app/models/operatingsystems/junos.rb
end
def boot_filename(host = nil)
"ztp.cfg/"+host.mac.delete(':').upcase
"ztp.cfg/" + host.mac.delete(':').upcase
end
def kernel(arch)
app/models/operatingsystems/nxos.rb
end
def boot_filename(host = nil)
"poap.cfg/"+host.mac.delete(':').upcase
"poap.cfg/" + host.mac.delete(':').upcase
end
def kernel(arch)
app/models/puppetclass.rb
# returns module name (excluding of the class name)
# if class separator does not exists (the "::" chars), then returns the whole class name
def module_name
(i = name.index("::")) ? name[0..i-1] : name
(i = name.index("::")) ? name[0..i - 1] : name
end
# returns class name (excluding of the module name)
def klass
name.gsub(module_name+"::", "")
name.gsub(module_name + "::", "")
end
def all_hostgroups(with_descendants = true, unsorted = false)
app/models/setting.rb
include EncryptValue
self.inheritance_column = 'category'
TYPES= %w{integer boolean hash array string}
TYPES = %w{integer boolean hash array string}
FROZEN_ATTRS = %w{name category full_name}
NONZERO_ATTRS = %w{puppet_interval idle_timeout entries_per_page max_trend outofsync_interval}
BLANK_ATTRS = %w{ host_owner trusted_hosts login_delegation_logout_url authorize_login_delegation_auth_source_user_autocreate root_pass default_location default_organization websockets_ssl_key websockets_ssl_cert oauth_consumer_key oauth_consumer_secret login_text
app/models/subnet.rb
:vlanid, :mtu, :ipam, :boot_mode, :type], :complete_value => true
scoped_search :relation => :domains, :on => :name, :rename => :domain, :complete_value => true
scoped_search :relation => :subnet_parameters, :on => :value, :on_key=> :name, :complete_value => true, :only_explicit => true, :rename => :params
scoped_search :relation => :subnet_parameters, :on => :value, :on_key => :name, :complete_value => true, :only_explicit => true, :rename => :params
delegate :supports_ipam_mode?, :supported_ipam_modes, :show_mask?, to: 'self.class'
......
errors.add(:to, _("must be specified if from is defined")) if to.blank?
end
return if errors.key?(:from) || errors.key?(:to)
errors.add(:from, _("does not belong to subnet")) if from.present? && !self.contains?(f=IPAddr.new(from))
errors.add(:to, _("does not belong to subnet")) if to.present? && !self.contains?(t=IPAddr.new(to))
errors.add(:from, _("does not belong to subnet")) if from.present? && !self.contains?(f = IPAddr.new(from))
errors.add(:to, _("does not belong to subnet")) if to.present? && !self.contains?(t = IPAddr.new(to))
errors.add(:from, _("can't be bigger than to range")) if from.present? && t.present? && f > t
end
app/models/taxonomy.rb
end
def expire_topbar_cache
(users+User.only_admin).each { |u| u.expire_topbar_cache }
(users + User.only_admin).each { |u| u.expire_topbar_cache }
end
def parent_params(include_source = false)
app/models/usergroup_member.rb
end
def find_all_user_roles_for(usergroup)
(UserRole.where(:owner => usergroup)+ usergroup.parents.map { |g| find_all_user_roles_for(g) }).flatten
(UserRole.where(:owner => usergroup) + usergroup.parents.map { |g| find_all_user_roles_for(g) }).flatten
end
def find_all_usergroups
app/registries/foreman/access_permissions.rb
end
permission_set.security_block :host_editing do |map|
map.permission :edit_classes, { :host_editing => [:edit_classes],
map.permission :edit_classes, { :host_editing => [:edit_classes],
:"api/v2/host_classes" => [:index, :create, :destroy]
}
map.permission :view_params, { :host_editing => [:view_params],
......
end
permission_set.security_block :facts do |map|
map.permission :view_facts, {:facts => [:index, :show],
map.permission :view_facts, {:facts => [:index, :show],
:fact_values => [:index, :show, :auto_complete_search],
:"api/v2/fact_values" => [:index, :show]
}
......
end
permission_set.security_block :statistics do |map|
map.permission :view_statistics, {:statistics => [:index, :show],
map.permission :view_statistics, {:statistics => [:index, :show],
:"api/v2/statistics" => [:index]
}
end
app/registries/foreman/plugin.rb
def requires_foreman(matcher)
current = SETTINGS[:version].notag
unless Gem::Dependency.new('', matcher).match?('', current)
raise PluginRequirementError.new(N_("%{id} plugin requires Foreman %{matcher} but current is %{current}" % {:id=>id, :matcher => matcher, :current=>current}))
raise PluginRequirementError.new(N_("%{id} plugin requires Foreman %{matcher} but current is %{current}" % {:id => id, :matcher => matcher, :current => current}))
end
true
end
......
# matcher format is gem dependency format
def requires_foreman_plugin(plugin_name, matcher)
plugin = Plugin.find(plugin_name)
raise PluginNotFound.new(N_("%{id} plugin requires the %{plugin_name} plugin, not found") % {:id =>id, :plugin_name=>plugin_name}) unless plugin
raise PluginNotFound.new(N_("%{id} plugin requires the %{plugin_name} plugin, not found") % {:id => id, :plugin_name => plugin_name}) unless plugin
unless Gem::Dependency.new('', matcher).match?('', plugin.version)
raise PluginRequirementError.new(N_("%{id} plugin requires the %{plugin_name} plugin %{matcher} but current is %{plugin_version}" % {:id=>id, :plugin_name=>plugin_name, :matcher=> matcher, :plugin_version=>plugin.version}))
raise PluginRequirementError.new(N_("%{id} plugin requires the %{plugin_name} plugin %{matcher} but current is %{plugin_version}" % {:id => id, :plugin_name => plugin_name, :matcher => matcher, :plugin_version => plugin.version}))
end
true
end
app/registries/menu/item.rb
end
def url
add_relative_path(@url || @context.routes.url_for(url_hash.merge(:only_path=>true).except(:use_route)))
add_relative_path(@url || @context.routes.url_for(url_hash.merge(:only_path => true).except(:use_route)))
end
def url_hash
app/services/classification/matches_generator.rb
matches << match.join(LookupKey::KEY_DELM)
hostgroup_matches.each do |hostgroup_match|
match[match.index { |m| m =~ /hostgroup\s*=/ }]=hostgroup_match
match[match.index { |m| m =~ /hostgroup\s*=/ }] = hostgroup_match
matches << match.join(LookupKey::KEY_DELM)
end if add_hostgroup_matches?(rule)
end
......
if host.hostgroup
path = host.hostgroup.to_label
while path.include?("/")
path = path[0..path.rindex("/")-1]
path = path[0..path.rindex("/") - 1]
matches << "hostgroup#{LookupKey::EQ_DELM}#{path}"
end
end
app/services/classification/values_hash_query.rb
computed_lookup_value = nil
lookup_values.each do |lookup_value|
element, element_name = get_element_and_element_name(lookup_value)
next if (options[:skip_fqdn] && element=="fqdn")
next if (options[:skip_fqdn] && element == "fqdn")
computed_lookup_value = compute_lookup_value(lookup_value, element, element_name)
computed_lookup_value[:managed] = lookup_value.omit if lookup_value.lookup_key.puppet?
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff