Class: Chef::Resource
- Inherits:
-
Object
- Object
- Chef::Resource
- Extended by:
- Mixin::ConvertToClassName, Mixin::Provides
- Includes:
- DSL::DataQuery, DSL::PlatformIntrospection, DSL::RebootPending, DSL::RegistryHelper, Mixin::ConvertToClassName, Mixin::Deprecation, Mixin::ParamsValidate
- Defined in:
- lib/chef/resource.rb,
lib/chef/resource/csh.rb,
lib/chef/resource/env.rb,
lib/chef/resource/git.rb,
lib/chef/resource/log.rb,
lib/chef/resource/scm.rb,
lib/chef/resource/bash.rb,
lib/chef/resource/cron.rb,
lib/chef/resource/file.rb,
lib/chef/resource/link.rb,
lib/chef/resource/ohai.rb,
lib/chef/resource/perl.rb,
lib/chef/resource/ruby.rb,
lib/chef/resource/user.rb,
lib/chef/resource/batch.rb,
lib/chef/resource/group.rb,
lib/chef/resource/mdadm.rb,
lib/chef/resource/mount.rb,
lib/chef/resource/route.rb,
lib/chef/resource/deploy.rb,
lib/chef/resource/python.rb,
lib/chef/resource/reboot.rb,
lib/chef/resource/script.rb,
lib/chef/resource/execute.rb,
lib/chef/resource/package.rb,
lib/chef/resource/service.rb,
lib/chef/resource/chef_gem.rb,
lib/chef/resource/erl_call.rb,
lib/chef/resource/ifconfig.rb,
lib/chef/resource/template.rb,
lib/chef/resource/directory.rb,
lib/chef/resource/lwrp_base.rb,
lib/chef/resource/breakpoint.rb,
lib/chef/resource/dsc_script.rb,
lib/chef/resource/ruby_block.rb,
lib/chef/resource/subversion.rb,
lib/chef/resource/apt_package.rb,
lib/chef/resource/bff_package.rb,
lib/chef/resource/conditional.rb,
lib/chef/resource/gem_package.rb,
lib/chef/resource/ips_package.rb,
lib/chef/resource/remote_file.rb,
lib/chef/resource/rpm_package.rb,
lib/chef/resource/yum_package.rb,
lib/chef/resource/dpkg_package.rb,
lib/chef/resource/dsc_resource.rb,
lib/chef/resource/http_request.rb,
lib/chef/resource/registry_key.rb,
lib/chef/resource/cookbook_file.rb,
lib/chef/resource/macosx_service.rb,
lib/chef/resource/pacman_package.rb,
lib/chef/resource/windows_script.rb,
lib/chef/resource/deploy_revision.rb,
lib/chef/resource/freebsd_package.rb,
lib/chef/resource/openbsd_package.rb,
lib/chef/resource/paludis_package.rb,
lib/chef/resource/portage_package.rb,
lib/chef/resource/smartos_package.rb,
lib/chef/resource/solaris_package.rb,
lib/chef/resource/windows_package.rb,
lib/chef/resource/windows_service.rb,
lib/chef/resource/homebrew_package.rb,
lib/chef/resource/macports_package.rb,
lib/chef/resource/remote_directory.rb,
lib/chef/resource/file/verification.rb,
lib/chef/resource/powershell_script.rb,
lib/chef/resource/timestamped_deploy.rb,
lib/chef/resource/easy_install_package.rb,
lib/chef/resource/resource_notification.rb,
lib/chef/resource/whyrun_safe_ruby_block.rb,
lib/chef/resource/conditional_action_not_nothing.rb
Direct Known Subclasses
Breakpoint, Cron, Deploy, Directory, DscResource, DscScript, Env, ErlCall, Execute, File, Group, HttpRequest, Ifconfig, LWRPBase, Link, Log, Mdadm, Mount, Ohai, Package, Reboot, RegistryKey, Route, RubyBlock, Scm, Service, User
Defined Under Namespace
Classes: AptPackage, Bash, Batch, BffPackage, Breakpoint, ChefGem, Conditional, ConditionalActionNotNothing, CookbookFile, Cron, Csh, Deploy, DeployBranch, DeployRevision, Directory, DpkgPackage, DscResource, DscScript, EasyInstallPackage, Env, ErlCall, Execute, File, FreebsdPackage, GemPackage, Git, Group, HomebrewPackage, HttpRequest, Ifconfig, IpsPackage, LWRPBase, Link, Log, MacosxService, MacportsPackage, Mdadm, Mount, Notification, Ohai, OpenbsdPackage, Package, PacmanPackage, PaludisPackage, Perl, PortagePackage, PowershellScript, Python, Reboot, RegistryKey, RemoteDirectory, RemoteFile, Route, RpmPackage, Ruby, RubyBlock, Scm, Script, Service, SmartosPackage, SolarisPackage, Subversion, Template, TimestampedDeploy, User, WhyrunSafeRubyBlock, WindowsPackage, WindowsScript, WindowsService, YumPackage
Constant Summary collapse
- FORBIDDEN_IVARS =
Internal Resource Interface (for Chef)
[:@run_context, :@not_if, :@only_if, :@enclosing_provider]
- HIDDEN_IVARS =
[:@allowed_actions, :@resource_name, :@source_line, :@run_context, :@name, :@not_if, :@only_if, :@elapsed_time, :@enclosing_provider]
Instance Attribute Summary collapse
-
#allowed_actions ⇒ Array<Symbol>
The list of actions this Resource is allowed to have.
-
#cookbook_name ⇒ String
The cookbook this resource was declared in.
-
#declared_type ⇒ String
The actual name that was used to create this resource.
-
#default_guard_interpreter ⇒ Class, ...
readonly
The guard interpreter that will be used to process
only_ifandnot_ifstatements by default. -
#elapsed_time ⇒ Integer
readonly
The time it took (in seconds) to run the most recently-run action.
-
#enclosing_provider ⇒ Chef::Provider
The provider this resource was declared in (if it was declared in an LWRP).
-
#ignore_failure(arg = nil) ⇒ Object
Whether to ignore failures.
-
#not_if_args ⇒ Object
readonly
??? TODO unreferenced.
-
#only_if_args ⇒ Object
readonly
??? TODO unreferenced.
-
#params ⇒ Object
XXX: this is required for definition params inside of the scope of a subresource to work correctly.
-
#recipe_name ⇒ String
The recipe this resource was declared in.
-
#resource_name ⇒ String
readonly
The name of this resource (e.g.
file). -
#retries(arg = nil) ⇒ Integer
The number of times to retry this resource if it fails by throwing an exception while running an action.
-
#retry_delay(arg = nil) ⇒ Integer
The number of seconds to wait between retries.
-
#run_context ⇒ Chef::RunContext
where the context for the current Chef run is stored, including the node and the resource collection.
-
#sensitive(arg = nil) ⇒ Boolean
Whether to treat this resource’s data as sensitive.
-
#source_line ⇒ String
The source line where this resource was declared.
-
#updated ⇒ Boolean
Whether or not this resource was updated during an action.
Class Method Summary collapse
-
.dsl_name ⇒ String
The DSL name of this resource (e.g.
packageoryum_package). -
.identity_attr(attr_name = nil) ⇒ Object
Set or return the “identity attribute” for this resource class.
- .json_create(o) ⇒ Object
-
.provider_base(arg = nil) ⇒ Module
The module where Chef should look for providers for this resource.
-
.resource_for_node(short_name, node) ⇒ Object
Returns a resource based on a short_name and node.
-
.resource_matching_short_name(short_name) ⇒ Object
- Returns the class of a Chef::Resource based on the short name ==== Parameters short_name<Symbol>
-
short_name of the resource (ie :directory).
-
.state_attrs(*attr_names) ⇒ Object
Set or return the list of “state attributes” implemented by the Resource subclass.
Instance Method Summary collapse
-
#action(arg = nil) ⇒ Array[Symbol]
The action or actions that will be taken when this resource is run.
-
#after_created ⇒ Object
A hook called after a resource is created.
-
#as_json(*a) ⇒ Object
as_json does most of the to_json heavy lifted.
-
#cookbook_version ⇒ Object
The cookbook in which this Resource was defined (if any).
-
#custom_exception_message(e) ⇒ String
Preface an exception message with generic Resource information.
- #customize_exception(e) ⇒ Object
-
#declared_key ⇒ Object
We usually want to store and reference resources by their declared type and not the actual type that was looked up by the Resolver (IE, “package” becomes YumPackage class).
- #defined_at ⇒ Object
- #delayed_notifications ⇒ Object
-
#epic_fail(arg = nil) ⇒ Object
Equivalent to #ignore_failure.
- #events ⇒ Object
-
#guard_interpreter(arg = nil) ⇒ Class, ...
The guard interpreter that will be used to process
only_ifandnot_ifstatements. -
#identity ⇒ Object
The value of the identity attribute, if declared.
- #immediate_notifications ⇒ Object
-
#initialize(name, run_context = nil) ⇒ Resource
constructor
Create a new Resource.
- #inspect ⇒ Object
-
#is(*args) ⇒ Object
TODO Seems unused.
-
#load_from(resource) ⇒ Object
Make this resource into an exact (shallow) copy of the other resource.
-
#method_missing(method_symbol, *args, &block) ⇒ Object
If an unknown method is invoked, determine whether the enclosing Provider’s lexical scope can fulfill the request.
-
#name(name = nil) ⇒ String
The name of this particular resource.
-
#node ⇒ Chef::Node
The node the current Chef run is using.
-
#noop(tf = nil) ⇒ Object
??? TODO Seems unused.
-
#not_if(command = nil, opts = {}, &block) ⇒ Object
A command or block that indicates whether to actually run this resource.
-
#notifies(action, resource_spec, timing = :delayed) ⇒ Object
Sets up a notification that will run a particular action on another resource if and when this resource is updated by an action.
-
#notifies_delayed(action, resource_spec) ⇒ Object
Helper for #notifies.
-
#notifies_immediately(action, resource_spec) ⇒ Object
Helper for #notifies.
-
#only_if(command = nil, opts = {}, &block) ⇒ Object
A command or block that indicates whether to actually run this resource.
-
#provider(arg = nil) ⇒ Object
The provider class for this resource.
- #provider=(arg) ⇒ Object
- #provider_for_action(action) ⇒ Object
-
#resolve_notification_references ⇒ Object
Iterates over all immediate and delayed notifications, calling resolve_resource_reference on each in turn, causing them to resolve lazy/forward references.
-
#resources(*args) ⇒ Object
Find existing resources by searching the list of existing resources.
-
#run_action(action, notification_type = nil, notifying_resource = nil) ⇒ Object
Runs the given action on this resource, immediately.
-
#should_skip?(action) ⇒ Boolean
Evaluates not_if and only_if conditionals.
-
#state ⇒ Hash{Symbol => Object}
Get the value of the state attributes in this resource as a hash.
-
#subscribes(action, resources, timing = :delayed) ⇒ Object
Subscribes to updates from other resources, causing a particular action to run on this resource when the other resource is updated.
-
#supports(args = {}) ⇒ Object
Sets a list of capabilities of the real resource.
- #supports=(args) ⇒ Object
- #to_hash ⇒ Object
-
#to_json(*a) ⇒ Object
Serialize this object as a hash.
-
#to_s ⇒ Object
Generic Ruby and Data Structure Stuff (for user).
- #to_text ⇒ Object
-
#updated? ⇒ Boolean
Whether or not this resource was updated during an action.
-
#updated_by_last_action(true_or_false) ⇒ Boolean
Whether or not this resource was updated during the most recent action.
-
#updated_by_last_action? ⇒ Boolean
Whether or not this resource was updated during the most recent action.
- #validate_action(action) ⇒ Object
-
#validate_resource_spec!(resource_spec) ⇒ Object
Helper for #notifies.
Methods included from Mixin::Provides
Methods included from Mixin::DescendantsTracker
#descendants, descendants, direct_descendants, #direct_descendants, find_descendants_by_name, #find_descendants_by_name, #inherited, store_inherited
Methods included from Mixin::ConvertToClassName
constantize, convert_to_class_name, convert_to_snake_case, filename_to_qualified_string, snake_case_basename
Methods included from Mixin::Deprecation
Methods included from Mixin::ParamsValidate
#lazy, #set_or_return, #validate
Methods included from DSL::RebootPending
Methods included from DSL::PlatformIntrospection
#platform?, #platform_family?, #value_for_platform, #value_for_platform_family
Methods included from DSL::RegistryHelper
#registry_data_exists?, #registry_get_subkeys, #registry_get_values, #registry_has_subkeys?, #registry_key_exists?, #registry_value_exists?
Methods included from DSL::DataQuery
#data_bag, #data_bag_item, #search
Methods included from EncryptedDataBagItem::CheckEncrypted
Constructor Details
#initialize(name, run_context = nil) ⇒ Resource
Create a new Resource.
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/chef/resource.rb', line 94 def initialize(name, run_context=nil) name(name) @run_context = run_context @noop = nil @before = nil @params = Hash.new @provider = nil @allowed_actions = [ :nothing ] @action = :nothing @updated = false @updated_by_last_action = false @supports = {} @ignore_failure = false @retries = 0 @retry_delay = 2 @not_if = [] @only_if = [] @source_line = nil # We would like to raise an error when the user gives us a guard # interpreter and a ruby_block to the guard. In order to achieve this # we need to understand when the user overrides the default guard # interpreter. Therefore we store the default separately in a different # attribute. @guard_interpreter = nil @default_guard_interpreter = :default @elapsed_time = 0 @sensitive = false end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_symbol, *args, &block) ⇒ Object
If an unknown method is invoked, determine whether the enclosing Provider’s lexical scope can fulfill the request. E.g. This happens when the Resource’s block invokes new_resource.
955 956 957 958 959 960 961 |
# File 'lib/chef/resource.rb', line 955 def method_missing(method_symbol, *args, &block) if enclosing_provider && enclosing_provider.respond_to?(method_symbol) enclosing_provider.send(method_symbol, *args, &block) else raise NoMethodError, "undefined method `#{method_symbol.to_s}' for #{self.class.to_s}" end end |
Instance Attribute Details
#allowed_actions ⇒ Array<Symbol>
The list of actions this Resource is allowed to have. Setting action will fail unless it is in this list. Default: [ :nothing ]
751 752 753 |
# File 'lib/chef/resource.rb', line 751 def allowed_actions @allowed_actions end |
#cookbook_name ⇒ String
Returns The cookbook this resource was declared in.
894 895 896 |
# File 'lib/chef/resource.rb', line 894 def cookbook_name @cookbook_name end |
#declared_type ⇒ String
The actual name that was used to create this resource. Sometimes, when you say something like ‘package ’blah’‘, the system will create a different resource (i.e. YumPackage). When this happens, the user will expect to see the thing they wrote, not the type that was returned. May be nil, in which case callers should read #resource_name. See #declared_key.
918 919 920 |
# File 'lib/chef/resource.rb', line 918 def declared_type @declared_type end |
#default_guard_interpreter ⇒ Class, ... (readonly)
The guard interpreter that will be used to process only_if and not_if statements by default. If left unset, or set to :default, the guard interpreter used will be Chef::GuardInterpreter::DefaultGuardInterpreter.
Must be a resource class like Chef::Resource::Execute, or a corresponding to the name of a resource. The resource must descend from Chef::Resource::Execute.
TODO this needs to be coerced on input so that retrieval is consistent.
742 743 744 |
# File 'lib/chef/resource.rb', line 742 def default_guard_interpreter @default_guard_interpreter end |
#elapsed_time ⇒ Integer (readonly)
The time it took (in seconds) to run the most recently-run action. Not cumulative across actions. This is set to 0 as soon as a new action starts running, and set to the elapsed time at the end of the action.
action. Not cumulative.
441 442 443 |
# File 'lib/chef/resource.rb', line 441 def elapsed_time @elapsed_time end |
#enclosing_provider ⇒ Chef::Provider
Returns The provider this resource was declared in (if it was declared in an LWRP). When you call methods that do not exist on this Resource, Chef will try to call the method on the provider as well before giving up.
903 904 905 |
# File 'lib/chef/resource.rb', line 903 def enclosing_provider @enclosing_provider end |
#ignore_failure(arg = nil) ⇒ Object
Whether to ignore failures. If set to true, and this resource when an action is run, the resource will be marked as failed but no exception will be thrown (and no error will be output). Defaults to false.
TODO ignore_failure and retries seem to be mutually exclusive; I doubt that was intended.
502 503 504 |
# File 'lib/chef/resource.rb', line 502 def ignore_failure(arg=nil) set_or_return(:ignore_failure, arg, kind_of: [ TrueClass, FalseClass ]) end |
#not_if_args ⇒ Object (readonly)
??? TODO unreferenced. Delete?
429 430 431 |
# File 'lib/chef/resource.rb', line 429 def not_if_args @not_if_args end |
#only_if_args ⇒ Object (readonly)
??? TODO unreferenced. Delete?
431 432 433 |
# File 'lib/chef/resource.rb', line 431 def only_if_args @only_if_args end |
#params ⇒ Object
XXX: this is required for definition params inside of the scope of a subresource to work correctly.
886 887 888 |
# File 'lib/chef/resource.rb', line 886 def params @params end |
#recipe_name ⇒ String
Returns The recipe this resource was declared in.
897 898 899 |
# File 'lib/chef/resource.rb', line 897 def recipe_name @recipe_name end |
#resource_name ⇒ String (readonly)
The name of this resource (e.g. file)
822 823 824 |
# File 'lib/chef/resource.rb', line 822 def resource_name @resource_name end |
#retries(arg = nil) ⇒ Integer
The number of times to retry this resource if it fails by throwing an exception while running an action. Default: 0
When the retries have run out, the Resource will throw the last exception.
400 401 402 |
# File 'lib/chef/resource.rb', line 400 def retries(arg=nil) set_or_return(:retries, arg, kind_of: Integer) end |
#retry_delay(arg = nil) ⇒ Integer
The number of seconds to wait between retries. Default: 2.
411 412 413 |
# File 'lib/chef/resource.rb', line 411 def retry_delay(arg=nil) set_or_return(:retry_delay, arg, kind_of: Integer) end |
#run_context ⇒ Chef::RunContext
where the context for the current Chef run is stored, including the node and the resource collection.
891 892 893 |
# File 'lib/chef/resource.rb', line 891 def run_context @run_context end |
#sensitive(arg = nil) ⇒ Boolean
Whether to treat this resource’s data as sensitive. If set, no resource data will be displayed in log output.
423 424 425 |
# File 'lib/chef/resource.rb', line 423 def sensitive(arg=nil) set_or_return(:sensitive, arg, :kind_of => [ TrueClass, FalseClass ]) end |
#source_line ⇒ String
Returns The source line where this resource was declared. Expected to come from caller() or a stack trace, it usually follows one of these formats:
/some/path/to/file.rb:80:in `wombat_tears'
C:/some/path/to/file.rb:80 in 1`wombat_tears'.
910 911 912 |
# File 'lib/chef/resource.rb', line 910 def source_line @source_line end |
#updated ⇒ Boolean
Whether or not this resource was updated during an action. If multiple actions are set on the resource, this will be true if any action caused an update to happen.
760 761 762 |
# File 'lib/chef/resource.rb', line 760 def updated @updated end |
Class Method Details
.dsl_name ⇒ String
The DSL name of this resource (e.g. package or yum_package)
813 814 815 |
# File 'lib/chef/resource.rb', line 813 def self.dsl_name convert_to_snake_case(name, 'Chef::Resource') end |
.identity_attr(attr_name = nil) ⇒ Object
Set or return the “identity attribute” for this resource class. This is generally going to be the “name attribute” for this resource. In other words, the resource type plus this attribute uniquely identify a given bit of state that chef manages. For a File resource, this would be the path, for a package resource, it will be the package name. This will show up in chef-client’s audit records as a searchable field.
717 718 719 720 721 722 723 724 725 726 727 |
# File 'lib/chef/resource.rb', line 717 def self.identity_attr(attr_name=nil) @identity_attr ||= nil @identity_attr = attr_name if attr_name # If this class doesn't have an identity attr, we'll defer to the superclass: if @identity_attr || !superclass.respond_to?(:identity_attr) @identity_attr else superclass.identity_attr end end |
.json_create(o) ⇒ Object
649 650 651 652 653 654 655 |
# File 'lib/chef/resource.rb', line 649 def self.json_create(o) resource = self.new(o["instance_vars"]["@name"]) o["instance_vars"].each do |k,v| resource.instance_variable_set("@#{k}".to_sym, v) end resource end |
.provider_base(arg = nil) ⇒ Module
The module where Chef should look for providers for this resource. The provider for MyResource will be looked up using provider_base::MyResource. Defaults to Chef::Provider.
868 869 870 871 |
# File 'lib/chef/resource.rb', line 868 def self.provider_base(arg=nil) @provider_base ||= arg @provider_base ||= Chef::Provider end |
.resource_for_node(short_name, node) ⇒ Object
Returns a resource based on a short_name and node
Parameters
- short_name<Symbol>
-
short_name of the resource (ie :directory)
- node<Chef::Node>
-
Node object to look up platform and version in
Returns
- <Chef::Resource>
-
returns the proper Chef::Resource class
1092 1093 1094 1095 1096 1097 |
# File 'lib/chef/resource.rb', line 1092 def self.resource_for_node(short_name, node) require 'chef/resource_resolver' klass = Chef::ResourceResolver.new(node, short_name).resolve raise Chef::Exceptions::NoSuchResourceType.new(short_name, node) if klass.nil? klass end |
.resource_matching_short_name(short_name) ⇒ Object
Returns the class of a Chef::Resource based on the short name
Parameters
- short_name<Symbol>
-
short_name of the resource (ie :directory)
Returns
- <Chef::Resource>
-
returns the proper Chef::Resource class
1105 1106 1107 1108 1109 1110 1111 1112 |
# File 'lib/chef/resource.rb', line 1105 def self.resource_matching_short_name(short_name) begin rname = convert_to_class_name(short_name.to_s) Chef::Resource.const_get(rname) rescue NameError nil end end |
.state_attrs(*attr_names) ⇒ Object
Set or return the list of “state attributes” implemented by the Resource subclass. State attributes are attributes that describe the desired state of the system, such as file permissions or ownership. In general, state attributes are attributes that could be populated by examining the state of the system (e.g., File.stat can tell you the permissions on an existing file). Contrarily, attributes that are not “state attributes” usually modify the way Chef itself behaves, for example by providing additional options for a package manager to use when installing a package.
This list is used by the Chef client auditing system to extract information from resources to describe changes made to the system.
699 700 701 702 703 704 705 706 707 708 709 |
# File 'lib/chef/resource.rb', line 699 def self.state_attrs(*attr_names) @state_attrs ||= [] @state_attrs = attr_names unless attr_names.empty? # Return *all* state_attrs that this class has, including inherited ones if superclass.respond_to?(:state_attrs) superclass.state_attrs + @state_attrs else @state_attrs end end |
Instance Method Details
#action(arg = nil) ⇒ Array[Symbol]
The action or actions that will be taken when this resource is run.
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
# File 'lib/chef/resource.rb', line 163 def action(arg=nil) if arg action_list = arg.kind_of?(Array) ? arg : [ arg ] action_list = action_list.collect { |a| a.to_sym } action_list.each do |action| validate( { action: action }, { action: { kind_of: Symbol, equal_to: @allowed_actions } } ) end @action = action_list else @action end end |
#after_created ⇒ Object
A hook called after a resource is created. Meant to be overriden by subclasses.
850 851 852 |
# File 'lib/chef/resource.rb', line 850 def after_created nil end |
#as_json(*a) ⇒ Object
as_json does most of the to_json heavy lifted. It exists here in case activesupport is loaded. activesupport will call as_json and skip over to_json. This ensure json is encoded as expected
621 622 623 624 625 626 627 628 629 630 631 |
# File 'lib/chef/resource.rb', line 621 def as_json(*a) safe_ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS instance_vars = Hash.new safe_ivars.each do |iv| instance_vars[iv.to_s.sub(/^@/, '')] = instance_variable_get(iv) end { 'json_class' => self.class.name, 'instance_vars' => instance_vars } end |
#cookbook_version ⇒ Object
The cookbook in which this Resource was defined (if any).
1004 1005 1006 1007 1008 |
# File 'lib/chef/resource.rb', line 1004 def cookbook_version if cookbook_name run_context.cookbook_collection[cookbook_name] end end |
#custom_exception_message(e) ⇒ String
Preface an exception message with generic Resource information.
1049 1050 1051 |
# File 'lib/chef/resource.rb', line 1049 def (e) "#{self} (#{defined_at}) had an error: #{e.class.name}: #{e.}" end |
#customize_exception(e) ⇒ Object
1053 1054 1055 1056 1057 |
# File 'lib/chef/resource.rb', line 1053 def customize_exception(e) new_exception = e.exception((e)) new_exception.set_backtrace(e.backtrace) new_exception end |
#declared_key ⇒ Object
We usually want to store and reference resources by their declared type and not the actual type that was looked up by the Resolver (IE, “package” becomes YumPackage class). If we have not been provided the declared key we want to fall back on the old to_s key.
971 972 973 974 |
# File 'lib/chef/resource.rb', line 971 def declared_key return to_s if declared_type.nil? "#{declared_type}[#{@name}]" end |
#defined_at ⇒ Object
984 985 986 987 988 989 990 991 992 993 994 995 996 997 |
# File 'lib/chef/resource.rb', line 984 def defined_at # The following regexp should match these two sourceline formats: # /some/path/to/file.rb:80:in `wombat_tears' # C:/some/path/to/file.rb:80 in 1`wombat_tears' # extracting the path to the source file and the line number. (file, line_no) = source_line.match(/(.*):(\d+):?.*$/).to_a[1,2] if source_line if cookbook_name && recipe_name && source_line "#{cookbook_name}::#{recipe_name} line #{line_no}" elsif source_line "#{file} line #{line_no}" else "dynamically defined" end end |
#delayed_notifications ⇒ Object
980 981 982 |
# File 'lib/chef/resource.rb', line 980 def delayed_notifications run_context.delayed_notifications(self) end |
#epic_fail(arg = nil) ⇒ Object
Equivalent to #ignore_failure.
510 511 512 |
# File 'lib/chef/resource.rb', line 510 def epic_fail(arg=nil) ignore_failure(arg) end |
#events ⇒ Object
1010 1011 1012 |
# File 'lib/chef/resource.rb', line 1010 def events run_context.events end |
#guard_interpreter(arg = nil) ⇒ Class, ...
The guard interpreter that will be used to process only_if and not_if statements. If left unset, the #default_guard_interpreter will be used.
Must be a resource class like Chef::Resource::Execute, or a corresponding to the name of a resource. The resource must descend from Chef::Resource::Execute.
TODO this needs to be coerced on input so that retrieval is consistent.
457 458 459 460 461 462 463 |
# File 'lib/chef/resource.rb', line 457 def guard_interpreter(arg=nil) if arg.nil? @guard_interpreter || @default_guard_interpreter else set_or_return(:guard_interpreter, arg, :kind_of => Symbol) end end |
#identity ⇒ Object
The value of the identity attribute, if declared. Falls back to #name if no identity attribute is declared.
483 484 485 486 487 488 489 |
# File 'lib/chef/resource.rb', line 483 def identity if identity_attr = self.class.identity_attr send(identity_attr) else name end end |
#immediate_notifications ⇒ Object
976 977 978 |
# File 'lib/chef/resource.rb', line 976 def immediate_notifications run_context.immediate_notifications(self) end |
#inspect ⇒ Object
611 612 613 614 615 616 |
# File 'lib/chef/resource.rb', line 611 def inspect ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS ivars.inject("<#{to_s}") do |str, ivar| str << " #{ivar}: #{instance_variable_get(ivar).inspect}" end << ">" end |
#is(*args) ⇒ Object
TODO Seems unused. Delete?
1035 1036 1037 1038 1039 1040 1041 |
# File 'lib/chef/resource.rb', line 1035 def is(*args) if args.size == 1 args.first else return *args end end |
#load_from(resource) ⇒ Object
Make this resource into an exact (shallow) copy of the other resource.
519 520 521 522 523 524 525 |
# File 'lib/chef/resource.rb', line 519 def load_from(resource) resource.instance_variables.each do |iv| unless iv == :@source_line || iv == :@action || iv == :@not_if || iv == :@only_if self.instance_variable_set(iv, resource.instance_variable_get(iv)) end end end |
#name(name = nil) ⇒ String
The name of this particular resource.
This special resource attribute is set automatically from the declaration of the resource, e.g.
execute 'Vitruvius' do
command 'ls'
end
Will set the name to “Vitruvius”.
This is also used in to_s to show the resource name, e.g. execute[Vitruvius].
This is also used for resource notifications and subscribes in the same manner.
This will coerce any object into a string via #to_s. Arrays are a special case so that ‘package [“foo”, “bar”]` becomes package[foo, bar] instead of the more awkward `package[[“foo”, “bar”]]` that #to_s would produce.
146 147 148 149 150 151 152 153 154 155 |
# File 'lib/chef/resource.rb', line 146 def name(name=nil) if !name.nil? if name.is_a?(Array) @name = name.join(', ') else @name = name.to_s end end @name end |
#node ⇒ Chef::Node
The node the current Chef run is using.
Corresponds to run_context.node.
58 59 60 |
# File 'lib/chef/resource.rb', line 58 def node run_context && run_context.node end |
#noop(tf = nil) ⇒ Object
??? TODO Seems unused. Delete?
1026 1027 1028 1029 1030 1031 1032 |
# File 'lib/chef/resource.rb', line 1026 def noop(tf=nil) if !tf.nil? raise ArgumentError, "noop must be true or false!" unless tf == true || tf == false @noop = tf end @noop end |
#not_if(command = nil, opts = {}, &block) ⇒ Object
A command or block that indicates whether to actually run this resource. The command or block is run just before the action actually executes, and the action will be skipped if the block returns true.
If a block is specified, it must return false in order for the Resource to be executed.
If a command is specified, the resource’s #guard_interpreter will run the command and interpret the results according to opts. For example, the default execute resource will be treated as false if the command returns a non-zero exit code, and true if it returns 0. Thus, in the default case:
-
‘not_if “your command”` will perform the action only if `your command`
returns a non-zero code.
-
‘only_if “your command”, valid_exit_codes: [ 1, 2, 3 ]` will perform the action only if `your command` returns something other than 1, 2, or 3.
383 384 385 386 387 388 |
# File 'lib/chef/resource.rb', line 383 def not_if(command=nil, opts={}, &block) if command || block_given? @not_if << Conditional.not_if(self, command, opts, &block) end @not_if end |
#notifies(action, resource_spec, timing = :delayed) ⇒ Object
Sets up a notification that will run a particular action on another resource if and when this resource is updated by an action.
If the action does nothing–does not update this resource, the notification never triggers.)
Only one resource may be specified per notification.
delayed notifications will only ever happen once per resource, so if multiple resources all notify a single resource to perform the same action, the action will only happen once. However, if they ask for different actions, each action will happen once, in the order they were updated.
immediate notifications will cause the action to be triggered once per notification, regardless of how many other resources have triggered the notification as well.
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
# File 'lib/chef/resource.rb', line 233 def notifies(action, resource_spec, timing=:delayed) # when using old-style resources(:template => "/foo.txt") style, you # could end up with multiple resources. validate_resource_spec!(resource_spec) resources = [ resource_spec ].flatten resources.each do |resource| case timing.to_s when 'delayed' notifies_delayed(action, resource) when 'immediate', 'immediately' notifies_immediately(action, resource) else raise ArgumentError, "invalid timing: #{timing} for notifies(#{action}, #{resources.inspect}, #{timing}) resource #{self} "\ "Valid timings are: :delayed, :immediate, :immediately" end end true end |
#notifies_delayed(action, resource_spec) ⇒ Object
Helper for #notifies
939 940 941 |
# File 'lib/chef/resource.rb', line 939 def notifies_delayed(action, resource_spec) run_context.notifies_delayed(Notification.new(resource_spec, action, self)) end |
#notifies_immediately(action, resource_spec) ⇒ Object
Helper for #notifies
934 935 936 |
# File 'lib/chef/resource.rb', line 934 def notifies_immediately(action, resource_spec) run_context.notifies_immediately(Notification.new(resource_spec, action, self)) end |
#only_if(command = nil, opts = {}, &block) ⇒ Object
A command or block that indicates whether to actually run this resource. The command or block is run just before the action actually executes, and the action will be skipped if the block returns false.
If a block is specified, it must return true in order for the Resource to be executed.
If a command is specified, the resource’s #guard_interpreter will run the command and interpret the results according to opts. For example, the default execute resource will be treated as false if the command returns a non-zero exit code, and true if it returns 0. Thus, in the default case:
-
‘only_if “your command”` will perform the action only if `your command`
returns 0.
-
‘only_if “your command”, valid_exit_codes: [ 1, 2, 3 ]` will perform the action only if `your command` returns 1, 2, or 3.
353 354 355 356 357 358 |
# File 'lib/chef/resource.rb', line 353 def only_if(command=nil, opts={}, &block) if command || block_given? @only_if << Conditional.only_if(self, command, opts, &block) end @only_if end |
#provider(arg = nil) ⇒ Object
The provider class for this resource.
If this is not set, provider_for_action will dynamically determine the provider.
675 676 677 678 679 680 681 682 |
# File 'lib/chef/resource.rb', line 675 def provider(arg=nil) klass = if arg.kind_of?(String) || arg.kind_of?(Symbol) lookup_provider_constant(arg) else arg end set_or_return(:provider, klass, kind_of: [ Class ]) end |
#provider=(arg) ⇒ Object
683 684 685 |
# File 'lib/chef/resource.rb', line 683 def provider=(arg) provider(arg) end |
#provider_for_action(action) ⇒ Object
1018 1019 1020 1021 1022 1023 |
# File 'lib/chef/resource.rb', line 1018 def provider_for_action(action) require 'chef/provider_resolver' provider = Chef::ProviderResolver.new(node, self, action).resolve.new(self, run_context) provider.action = action provider end |
#resolve_notification_references ⇒ Object
Iterates over all immediate and delayed notifications, calling resolve_resource_reference on each in turn, causing them to resolve lazy/forward references.
924 925 926 927 928 929 930 931 |
# File 'lib/chef/resource.rb', line 924 def resolve_notification_references run_context.immediate_notifications(self).each { |n| n.resolve_resource_reference(run_context.resource_collection) } run_context.delayed_notifications(self).each {|n| n.resolve_resource_reference(run_context.resource_collection) } end |
#resources(*args) ⇒ Object
Find existing resources by searching the list of existing resources. Possible forms are:
find(:file => "foobar")
find(:file => [ "foobar", "baz" ])
find("file[foobar]", "file[baz]")
find("file[foobar,baz]")
Calls ‘run_context.resource_collection.find(*args)`
78 79 80 |
# File 'lib/chef/resource.rb', line 78 def resources(*args) run_context.resource_collection.find(*args) end |
#run_action(action, notification_type = nil, notifying_resource = nil) ⇒ Object
Runs the given action on this resource, immediately.
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 |
# File 'lib/chef/resource.rb', line 536 def run_action(action, notification_type=nil, =nil) # reset state in case of multiple actions on the same resource. @elapsed_time = 0 start_time = Time.now events.resource_action_start(self, action, notification_type, ) # Try to resolve lazy/forward references in notifications again to handle # the case where the resource was defined lazily (ie. in a ruby_block) resolve_notification_references validate_action(action) if Chef::Config[:verbose_logging] || Chef::Log.level == :debug # This can be noisy Chef::Log.info("Processing #{self} action #{action} (#{defined_at})") end # ensure that we don't leave @updated_by_last_action set to true # on accident updated_by_last_action(false) # Don't modify @retries directly and keep it intact, so that the # recipe_snippet from ResourceFailureInspector can print the value # that was set in the resource block initially. remaining_retries = retries begin return if should_skip?(action) provider_for_action(action).run_action rescue Exception => e if ignore_failure Chef::Log.error("#{(e)}; ignore_failure is set, continuing") events.resource_failed(self, action, e) elsif remaining_retries > 0 events.resource_failed_retriable(self, action, remaining_retries, e) remaining_retries -= 1 Chef::Log.info("Retrying execution of #{self}, #{remaining_retries} attempt(s) left") sleep retry_delay retry else events.resource_failed(self, action, e) raise customize_exception(e) end ensure @elapsed_time = Time.now - start_time # Reporting endpoint doesn't accept a negative resource duration so set it to 0. # A negative value can occur when a resource changes the system time backwards @elapsed_time = 0 if @elapsed_time < 0 events.resource_completed(self) end end |
#should_skip?(action) ⇒ Boolean
Evaluates not_if and only_if conditionals. Returns a falsey value if any of the conditionals indicate that this resource should be skipped, i.e., if an only_if evaluates to false or a not_if evaluates to true.
If this resource should be skipped, returns the first conditional that “fails” its check. Subsequent conditionals are not evaluated, so in general it’s not a good idea to rely on side effects from not_if or only_if commands/blocks being evaluated.
Also skips conditional checking when the action is :nothing
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 |
# File 'lib/chef/resource.rb', line 1069 def should_skip?(action) conditional_action = ConditionalActionNotNothing.new(action) conditionals = [ conditional_action ] + only_if + not_if conditionals.find do |conditional| if conditional.continue? false else events.resource_skipped(self, action, conditional) Chef::Log.debug("Skipping #{self} due to #{conditional.description}") true end end end |
#state ⇒ Hash{Symbol => Object}
Get the value of the state attributes in this resource as a hash.
470 471 472 473 474 475 |
# File 'lib/chef/resource.rb', line 470 def state self.class.state_attrs.inject({}) do |state_attrs, attr_name| state_attrs[attr_name] = send(attr_name) state_attrs end end |
#subscribes(action, resources, timing = :delayed) ⇒ Object
Subscribes to updates from other resources, causing a particular action to run on this resource when the other resource is updated.
If multiple resources are specified, this resource action will be run if any of them change.
This notification will only trigger once, no matter how many other resources are updated (or how many actions are run by a particular resource).
316 317 318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/chef/resource.rb', line 316 def subscribes(action, resources, timing=:delayed) resources = [resources].flatten resources.each do |resource| if resource.is_a?(String) resource = Chef::Resource.new(resource, run_context) end if resource.run_context.nil? resource.run_context = run_context end resource.notifies(action, self, timing) end true end |
#supports(args = {}) ⇒ Object
Sets a list of capabilities of the real resource. For example, :remount (for filesystems) and :restart (for services).
TODO Calling resource.supports({}) will not set this to empty; it will do a get instead. That’s wrong.
835 836 837 838 839 840 841 |
# File 'lib/chef/resource.rb', line 835 def supports(args={}) if args.any? @supports = args else @supports end end |
#supports=(args) ⇒ Object
842 843 844 |
# File 'lib/chef/resource.rb', line 842 def supports=(args) supports(args) end |
#to_hash ⇒ Object
639 640 641 642 643 644 645 646 647 |
# File 'lib/chef/resource.rb', line 639 def to_hash safe_ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS instance_vars = Hash.new safe_ivars.each do |iv| key = iv.to_s.sub(/^@/,'').to_sym instance_vars[key] = instance_variable_get(iv) end instance_vars end |
#to_json(*a) ⇒ Object
Serialize this object as a hash
634 635 636 637 |
# File 'lib/chef/resource.rb', line 634 def to_json(*a) results = as_json Chef::JSONCompat.to_json(results, *a) end |
#to_s ⇒ Object
Generic Ruby and Data Structure Stuff (for user)
590 591 592 |
# File 'lib/chef/resource.rb', line 590 def to_s "#{@resource_name}[#{@name}]" end |
#to_text ⇒ Object
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 |
# File 'lib/chef/resource.rb', line 594 def to_text return "suppressed sensitive resource output" if sensitive ivars = instance_variables.map { |ivar| ivar.to_sym } - HIDDEN_IVARS text = "# Declared in #{@source_line}\n\n" text << self.class.dsl_name + "(\"#{name}\") do\n" ivars.each do |ivar| if (value = instance_variable_get(ivar)) && !(value.respond_to?(:empty?) && value.empty?) value_string = value.respond_to?(:to_text) ? value.to_text : value.inspect text << " #{ivar.to_s.sub(/^@/,'')} #{value_string}\n" end end [@not_if, @only_if].flatten.each do |conditional| text << " #{conditional.to_text}\n" end text << "end\n" end |
#updated? ⇒ Boolean
Whether or not this resource was updated during an action. If multiple actions are set on the resource, this will be true if any action caused an update to happen.
769 770 771 |
# File 'lib/chef/resource.rb', line 769 def updated? updated end |
#updated_by_last_action(true_or_false) ⇒ Boolean
Whether or not this resource was updated during the most recent action. This is set to false at the beginning of each action.
781 782 783 784 |
# File 'lib/chef/resource.rb', line 781 def updated_by_last_action(true_or_false) @updated ||= true_or_false @updated_by_last_action = true_or_false end |
#updated_by_last_action? ⇒ Boolean
Whether or not this resource was updated during the most recent action. This is set to false at the beginning of each action.
792 793 794 |
# File 'lib/chef/resource.rb', line 792 def updated_by_last_action? @updated_by_last_action end |
#validate_action(action) ⇒ Object
1014 1015 1016 |
# File 'lib/chef/resource.rb', line 1014 def validate_action(action) raise ArgumentError, "nil is not a valid action for resource #{self}" if action.nil? end |
#validate_resource_spec!(resource_spec) ⇒ Object
Helper for #notifies
964 965 966 |
# File 'lib/chef/resource.rb', line 964 def validate_resource_spec!(resource_spec) run_context.resource_collection.validate_lookup_spec!(resource_spec) end |