Project

General

Profile

Download (17.6 KB) Statistics
| Branch: | Tag: | Revision:
611fd588 Amos Benari
# Redmine - project management software
# Copyright (C) 2006-2013 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

40fffe69 Dominic Cleal
require_dependency 'foreman/plugin/logging'
require_dependency 'foreman/plugin/rbac_registry'
require_dependency 'foreman/plugin/rbac_support'
45089e16 Sebastian Gräßl
require_dependency 'foreman/plugin/report_scanner_registry'
348ec9c0 Sebastian Gräßl
require_dependency 'foreman/plugin/report_origin_registry'
3088e641 Eric D. Helms
611fd588 Amos Benari
module Foreman #:nodoc:
class PluginNotFound < Foreman::Exception; end
class PluginRequirementError < Foreman::Exception; end

# Base class for Foreman plugins.
# Plugins are registered using the <tt>register</tt> class method that acts as the public constructor.
#
# Foreman::Plugin.register :example do
# name 'Example plugin'
# author 'John Smith'
# description 'This is an example plugin for Foreman'
# version '0.0.1'
# end
#
class Plugin
@registered_plugins = {}
c4741504 Greg Sutcliffe
@tests_to_skip = {}
45089e16 Sebastian Gräßl
@report_scanner_registry = Plugin::ReportScannerRegistry.new
348ec9c0 Sebastian Gräßl
@report_origin_registry = Plugin::ReportOriginRegistry.new
45089e16 Sebastian Gräßl
611fd588 Amos Benari
class << self
c4741504 Greg Sutcliffe
attr_reader :registered_plugins
348ec9c0 Sebastian Gräßl
attr_accessor :tests_to_skip, :report_scanner_registry,
:report_origin_registry
611fd588 Amos Benari
private :new

def def_field(*names)
class_eval do
names.each do |name|
define_method(name) do |*args|
args.empty? ? instance_variable_get("@#{name}") : instance_variable_set("@#{name}", *args)
end
end
end
end

# Plugin constructor
def register(id, &block)
plugin = new(id)
if (gem = Gem.loaded_specs[id.to_s])
plugin.name gem.name
d7ad6cbe Timo Goebel
plugin.author gem.authors.to_sentence
611fd588 Amos Benari
plugin.description gem.description
plugin.url gem.homepage
plugin.version gem.version.to_s
aacd8973 Bryan Kearney
plugin.path gem.full_gem_path
611fd588 Amos Benari
end

plugin.instance_eval(&block)
3088e641 Eric D. Helms
plugin.after_initialize
611fd588 Amos Benari
registered_plugins[id] = plugin
end

02a26515 Ondrej Prazak
def unregister(plugin_id)
@registered_plugins.delete(plugin_id)
end

611fd588 Amos Benari
# Clears the registered plugins hash
# It doesn't unload installed plugins
def clear
@registered_plugins = {}
end

# Returns an array of all registered plugins
def all
registered_plugins.values.sort
end

# Finds a plugin by its id
def find(id)
registered_plugins[id.to_sym]
end

# Checks if a plugin is installed
#
# @param [String] id name of the plugin
def installed?(id)
registered_plugins[id.to_sym].present?
end
45089e16 Sebastian Gräßl
def registered_report_scanners
report_scanner_registry.report_scanners
end
611fd588 Amos Benari
end

fbbab0d8 Michael Moll
prepend Foreman::Plugin::Assets
b40dde10 Dominic Cleal
prepend Foreman::Plugin::SearchOverrides

aacd8973 Bryan Kearney
def_field :name, :description, :url, :author, :author_url, :version, :path
72a28408 Ondrej Prazak
attr_reader :id, :logging, :provision_methods, :compute_resources, :to_prepare_callbacks,
02a26515 Ondrej Prazak
:facets, :rbac_registry, :dashboard_widgets, :info_providers, :smart_proxy_references
72a28408 Ondrej Prazak
# Lists plugin's roles:
# Foreman::Plugin.find('my_plugin').registered_roles
delegate :registered_roles, :registered_permissions, :default_roles, :permissions, :permission_names, :to => :rbac_registry
45089e16 Sebastian Gräßl
delegate :register_report_scanner, :unregister_report_scanner, :to => :report_scanner_registry
348ec9c0 Sebastian Gräßl
delegate :register_report_origin, :to => :report_origin_registry
611fd588 Amos Benari
def initialize(id)
@id = id.to_sym
3088e641 Eric D. Helms
@logging = Plugin::Logging.new(@id)
72a28408 Ondrej Prazak
@rbac_registry = Plugin::RbacRegistry.new
51685ba8 Timo Goebel
@provision_methods = {}
355c3a31 Dominic Cleal
@compute_resources = []
32f3b017 Marek Hulan
@to_prepare_callbacks = []
93dc012b Dominic Cleal
@template_labels = {}
12612809 Dominic Cleal
@parameter_filters = {}
c6760930 Timo Goebel
@smart_proxies = {}
87f8f03e Shimon Shtein
@controller_action_scopes = {}
d3f47405 Dominic Cleal
@dashboard_widgets = []
d73b9198 Timo Goebel
@rabl_template_extensions = {}
02a26515 Ondrej Prazak
@smart_proxy_references = []
3088e641 Eric D. Helms
end

45089e16 Sebastian Gräßl
def report_scanner_registry
self.class.report_scanner_registry
end

348ec9c0 Sebastian Gräßl
def report_origin_registry
self.class.report_origin_registry
end

3088e641 Eric D. Helms
def after_initialize
configure_logging
end

def configure_logging
@logging.configure(SETTINGS[@id])
end

def logger(name, configuration = {})
@logging.add_logger(name, configuration)
611fd588 Amos Benari
end

def <=>(plugin)
self.id.to_s <=> plugin.id.to_s
end

def to_s
"Foreman plugin: #{id}, #{version}, #{author}, #{description}"
end

# Sets a requirement on Foreman version
# Raises a PluginRequirementError exception if the requirement is not met
# matcher format is gem dependency format
def requires_foreman(matcher)
current = SETTINGS[:version].notag
unless Gem::Dependency.new('', matcher).match?('', current)
9d43fc71 Michael Moll
raise PluginRequirementError.new(N_("%{id} plugin requires Foreman %{matcher} but current is %{current}" % {:id => id, :matcher => matcher, :current => current}))
611fd588 Amos Benari
end
true
end

# Sets a requirement on a Foreman plugin version
# Raises a PluginRequirementError exception if the requirement is not met
# matcher format is gem dependency format
def requires_foreman_plugin(plugin_name, matcher)
plugin = Plugin.find(plugin_name)
9d43fc71 Michael Moll
raise PluginNotFound.new(N_("%{id} plugin requires the %{plugin_name} plugin, not found") % {:id => id, :plugin_name => plugin_name}) unless plugin
611fd588 Amos Benari
unless Gem::Dependency.new('', matcher).match?('', plugin.version)
9d43fc71 Michael Moll
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}))
611fd588 Amos Benari
end
true
end

# Adds an item to the given menu
# The id parameter is automatically added to the url.
# menu :menu_name, :plugin_example, 'menu text', { :controller => :example, :action => :index }
#
# name parameter can be: :top_menu or :admin_menu
#
4f7a4d0b David Davis
def menu(menu, name, options = {})
cabe2c2e Ohad Levy
options[:parent] = @parent if @parent
611fd588 Amos Benari
Menu::Manager.map(menu).item(name, options)
end

96144a47 Daniel Lobato
alias_method :add_menu_item, :menu
611fd588 Amos Benari
4f7a4d0b David Davis
def sub_menu(menu, name, options = {}, &block)
cabe2c2e Ohad Levy
options[:parent] = @parent if @parent
611fd588 Amos Benari
Menu::Manager.map(menu).sub_menu(name, options)
current = @parent
@parent = name
f26c594e Dmitri Dolguikh
self.instance_eval(&block) if block_given?
611fd588 Amos Benari
@parent = current
end

f5037382 Eric D. Helms
def divider(menu, options = {})
Menu::Manager.map(menu).divider(options)
end

611fd588 Amos Benari
# Removes item from the given menu
def delete_menu_item(menu, item)
Menu::Manager.map(menu).delete(item)
33f7c66c Ondrej Prazak
end

c9a68e50 Ondrej Prazak
# Extends page by adding custom pagelet to a mountpoint.
33f7c66c Ondrej Prazak
# Usage:
#
49cfbd45 Ondrej Prazak
# extend_page("hosts/_form") do |context|
c9a68e50 Ondrej Prazak
# context.add_pagelet :mountpoint,
# :name => N_("Example Pagelet"),
# :partial => "path/to/partial",
# :priority => 10000,
208d9743 Ondrej Prazak
# :id => 'custom-html-id',
# :onlyif => Proc.new { |subject| subject.should_show_pagelet? }
33f7c66c Ondrej Prazak
# end
49cfbd45 Ondrej Prazak
def extend_page(virtual_path, &block)
36483d66 Dominic Cleal
Pagelets::Manager.with_key(virtual_path, &block) if block_given?
611fd588 Amos Benari
end

c4741504 Greg Sutcliffe
def tests_to_skip(hash)
# Format is { "testclass" => [ "skip1", "skip2" ] }
3cd8c84b Michael Moll
hash.each do |testclass, tests|
c4741504 Greg Sutcliffe
if self.class.tests_to_skip[testclass].nil?
self.class.tests_to_skip[testclass] = tests
else
self.class.tests_to_skip[testclass] = self.class.tests_to_skip[testclass].push(tests).flatten.uniq
end
end
end

611fd588 Amos Benari
def security_block(name, &block)
@security_block = name
self.instance_eval(&block)
@security_block = nil
end

# Defines a permission called name for the given controller=>actions
acfbc458 Marek Hulan
# :options can contain :resource_type key which is the string of resource
# class to which this permissions is related, rest of options is passed
# to AccessControl
4f7a4d0b David Davis
def permission(name, hash, options = {})
40dd32b0 Marek Hulan
rbac_registry.register name, options
1a6e0963 Marek Hulan
options[:engine] ||= self.id.to_s
cabe2c2e Ohad Levy
options[:security_block] = @security_block
611fd588 Amos Benari
Foreman::AccessControl.map do |map|
map.permission name, hash, options
end
dc9bd44f Dominic Cleal
return false if pending_migrations || Rails.env.test?
Permission.where(:name => name).first_or_create(:resource_type => options[:resource_type])
611fd588 Amos Benari
end

# Add a new role if it doesn't exist
def role(name, permissions)
72a28408 Ondrej Prazak
default_roles[name] = permissions
d3fd7441 Marek Hulán
return false if pending_migrations || Rails.env.test? || User.unscoped.find_by_login(User::ANONYMOUS_ADMIN).nil?
64d9dd55 Marek Hulan
Role.without_auditing do
Filter.without_auditing do
Plugin::RoleLock.new(self.id).register_role name, permissions, rbac_registry
end
end
6dea4e94 adamruzicka
rescue PermissionMissingException => e
Rails.logger.warn(_("Could not create role '%{name}': %{message}") % {:name => name, :message => e.message})
return false if Foreman.in_rake?
Rails.logger.error(_('Cannot continue because some permissions were not found, please run rake db:seed and retry'))
raise e
611fd588 Amos Benari
end

72a28408 Ondrej Prazak
# Add plugin permissions to core's Manager and Viewer roles
# Usage:
# add_resource_permissions_to_default_roles ['MyPlugin::FirstResource', 'MyPlugin::SecondResource'], :except => [:skip_this_permission]
def add_resource_permissions_to_default_roles(resources, opts = {})
64d9dd55 Marek Hulan
Role.without_auditing do
Filter.without_auditing do
Plugin::RbacSupport.new.add_resource_permissions_to_default_roles resources, opts
end
end
72a28408 Ondrej Prazak
end

# Add plugin permissions to Manager and Viewer roles. Use this for permissions without resource_type or to handle special cases
# Usage:
# add_permissions_to_default_roles 'Role Name' => [:first_permission, :second_permission]
def add_permissions_to_default_roles(args)
64d9dd55 Marek Hulan
Role.without_auditing do
Filter.without_auditing do
Plugin::RbacSupport.new.add_permissions_to_default_roles args
end
end
72a28408 Ondrej Prazak
end

# Add plugin permissions to Manager and Viewer roles. Use this method if there are no special cases that need to be taken care of.
# Otherwise add_permissions_to_default_roles or add_resource_permissions_to_default_roles might be the methods you are looking for.
def add_all_permissions_to_default_roles
1d92402b Ondrej Prazak
return if Foreman.in_rake?('db:migrate') || !permission_table_exists?
64d9dd55 Marek Hulan
Role.without_auditing do
Filter.without_auditing do
Plugin::RbacSupport.new.add_all_permissions_to_default_roles(Permission.where(:name => @rbac_registry.permission_names))
end
end
72a28408 Ondrej Prazak
end

1a6e0963 Marek Hulan
def pending_migrations
fb9f45e8 Daniel Lobato
migration_paths = ActiveRecord::Migrator.migrations(
ActiveRecord::Migrator.migrations_paths)
pending_migrations = ActiveRecord::Migrator.new(:up, migration_paths).
pending_migrations

648dbb84 Daniel Lobato Garcia
return false if pending_migrations.empty?
migration_names = pending_migrations.take(5).map(&:name).join(', ')
Rails.logger.debug(
"There are #{pending_migrations.size} pending migrations: "\
da9865b8 Michael Moll
"#{migration_names}#{(pending_migrations.size > 5) ? '...' : ''}")
648dbb84 Daniel Lobato Garcia
true
1a6e0963 Marek Hulan
end

869bbffe Ivan Nečas
# List of helper methods allowed for templates in safe mode
def allowed_template_helpers(*helpers)
32f3b017 Marek Hulan
in_to_prepare do
Foreman::Renderer::ALLOWED_HELPERS.concat(helpers).uniq!
end
869bbffe Ivan Nečas
end

# List of variables allowed for templates in safe mode
def allowed_template_variables(*variables)
32f3b017 Marek Hulan
in_to_prepare do
Foreman::Renderer::ALLOWED_VARIABLES.concat(variables).uniq!
end
end

bdcdb09c Lukáš Zapletal
# List of global settings allowed for templates
def allowed_template_global_settings(*settings)
in_to_prepare do
Foreman::Renderer::ALLOWED_GLOBAL_SETTINGS.concat(settings).uniq!
end
end

32f3b017 Marek Hulan
# List of modules which public methods will be available during template rendering
# including safe mode
def extend_template_helpers(*mods)
in_to_prepare do
mods.each do |mod|
extend_template_helpers_by_module(mod.to_s)
end
end
869bbffe Ivan Nečas
end

5df3d514 Amos Benari
# Add Compute resource
def compute_resource(provider)
355c3a31 Dominic Cleal
return if @compute_resources.include?(provider)
if !provider.is_a?(Class) || !(provider < ComputeResource)
raise ::Foreman::Exception.new(N_("Cannot register compute resource, wrong type supplied"))
end
@compute_resources << provider.name
5df3d514 Amos Benari
end

42117380 Tomer Brisker
def widget(template, options)
d3f47405 Dominic Cleal
@dashboard_widgets << {:template => template}.merge(options)
db6d37b9 Amos Benari
end

a59972c3 Martin Bačovský
# list of API controller paths, globs allowed
def apipie_documented_controllers(controllers = nil)
if controllers
@apipie_documented_controllers = controllers
Apipie.configuration.api_controllers_matcher.concat(controllers)
end
@apipie_documented_controllers
end

# list of clontroller classnames that are ignored by apipie
def apipie_ignored_controllers(controllers = nil)
if controllers
@apipie_ignored_controllers = controllers
Apipie.configuration.ignored.concat(controllers)
end
@apipie_ignored_controllers
end
e54016da Marek Hulan
# register custom host status class, it should inherit from HostStatus::Status
def register_custom_status(klass)
670184e1 Marek Hulan
in_to_prepare do
HostStatus.status_registry.add(klass)
end
e54016da Marek Hulan
end
51685ba8 Timo Goebel
# register a provision method
def provision_method(name, friendly_name)
return if @provision_methods.key?(name.to_s)
@provision_methods[name.to_s] = friendly_name
end
7d90b5cb Eric D. Helms
def register_facet(klass, name, &block)
057641b4 Shimon Shtein
# Save the entry in case of reloading
@facets ||= []
@facets << Facets.register(klass, name, &block)
7d90b5cb Eric D. Helms
end
32f3b017 Marek Hulan
60cf5a37 Shimon Shtein
def register_info_provider(klass)
@info_providers ||= []
@info_providers << klass
end

32f3b017 Marek Hulan
def in_to_prepare(&block)
@to_prepare_callbacks << block
end

1ef8f52b Ondrej Prazak
# add human readable label for plugin's template kind with i18n support: template_labels "kind_name" => N_("Nice Name")
def template_labels(hash)
93dc012b Dominic Cleal
@template_labels.merge!(hash)
end

def get_template_labels
@template_labels
1ef8f52b Ondrej Prazak
end

12612809 Dominic Cleal
def parameter_filter(klass, *args, &block)
@parameter_filters[klass.name] ||= []
@parameter_filters[klass.name] << (block_given? ? args + [block] : args)
end

def parameter_filters(klass)
@parameter_filters.fetch(klass.is_a?(Class) ? klass.name : klass, [])
end

c6760930 Timo Goebel
def smart_proxy_for(klass, name, options)
@smart_proxies[klass.name] ||= {}
@smart_proxies[klass.name][name] = options
klass.register_smart_proxy(name, options)
end

def smart_proxies(klass)
@smart_proxies.fetch(klass.name, {})
end

87f8f03e Shimon Shtein
def add_controller_action_scope(controller_class, action, &block)
controller_actions = @controller_action_scopes[controller_class.name] || {}
actions_list = controller_actions[action] || []
actions_list << block
controller_actions[action] = actions_list
@controller_action_scopes[controller_class.name] = controller_actions
end

def action_scopes_hash_for(controller_class)
@controller_action_scopes[controller_class.name] || {}
end

d73b9198 Timo Goebel
# Extends a rabl template by "including" another template
#
# Usage:
# extend_rabl_template 'api/v2/hosts/main', 'api/v2/hosts/expiration'
#
# This will call 'extends api/v2/hosts/expiration' inside
# the template 'api/v2/hosts/main'
#
def extend_rabl_template(virtual_path, template)
@rabl_template_extensions[virtual_path] ||= []
@rabl_template_extensions[virtual_path] << template
end

def rabl_template_extensions(virtual_path)
@rabl_template_extensions.fetch(virtual_path, [])
end

f020721d Lukas Zapletal
def add_counter_telemetry(name, description, instance_labels = [])
Foreman::Telemetry.instance.add_counter(name, description, instance_labels)
end

def add_gauge_telemetry(name, description, instance_labels = [])
Foreman::Telemetry.instance.add_gauge(name, description, instance_labels)
end

def add_histogram_telemetry(name, description, instance_labels = [], buckets = DEFAULT_BUCKETS)
Foreman::Telemetry.instance.add_histogram(name, description, instance_labels, buckets)
end

02a26515 Ondrej Prazak
def smart_proxy_reference(hash)
@smart_proxy_references << ProxyReferenceRegistry.new_reference(hash)
end

32f3b017 Marek Hulan
private

1d92402b Ondrej Prazak
def permission_table_exists?
exists = Permission.connection.table_exists?(Permission.table_name)
Rails.logger.debug("Not adding permissions from plugin #{@id} to default roles - permissions table not found") if !exists && !Rails.env.test?
exists
end

32f3b017 Marek Hulan
def extend_template_helpers_by_module(mod)
mod = mod.constantize

4fb3d7c3 Timo Goebel
(TemplatesController.descendants + [TemplatesController, UnattendedController, UnattendedHelper]).each do |klass|
32f3b017 Marek Hulan
klass.send(:include, mod)
end
allowed_template_helpers(*(mod.public_instance_methods - Module.public_instance_methods))
end
611fd588 Amos Benari
end
end