Update cookbooks and add wordpress cookbook

This commit is contained in:
Greg Karékinian
2016-02-19 18:09:49 +01:00
parent 9ba973e3ac
commit 820b0ab3f8
606 changed files with 22421 additions and 14084 deletions

View File

@@ -1,5 +1,90 @@
# Changelog
## v2.6.0
* New backwards-compatibility helper: `Poise::Backports::VERIFY_PATH`. Use it
like `verify "myapp -t #{Poise::Backports::VERIFY_PATH}" if defined?(verify)`
for backwards-compatible usage of file verifications.
* Fixed Poise's implementation of lazy defaults to more closely match Chef's
even when both are used in conjunction. Lazy defaults will no longer be
evaluated when setting a value or getting an existing non-default value.
## v2.5.0
* New property for inversion resources: `provider_no_auto`. Set one or more
provider names that will be ignored for automatic resolution for that instance.
* Support `variables` as an alias for `options` in template content properties
to match the `template` resource.
* Template content properties are no longer validated after creation for
non-default actions.
* Formalize the extra-verbose logging mode for Poise and expose it via helpers.
* Extra-verbose logging mode can now be enabled by creating a `/poise_debug` file.
* New helper: `poise_shell_out`. Like normal `shell_out` but sets group and
environment variables automatically to better defaults.
## v2.4.0
* Added return value to `Container#register_subresource` to track if the resource
was already added.
* Improve inspect output for subresources and containers.
* Ensure notifications work with subresources.
* Inversion providers process name equivalences.
## v2.3.2
* Improve handling of deeply nested subresources.
## v2.3.1
* Ensure a container with a parent link to its own type doesn't use self as the
default parent.
* Improve handling of `load_current_resource` in providers that call it via
`super`.
## v2.3.0
* New helper: `ResourceSubclass`, a helper for subclassing a resource while
still using the providers as the base class.
* New feature: Non-default containers. Use `container_default: false` to mark
a container class as ineligible for default lookup.
* New feature: parent attribute defaults. You can set a `parent_default` to
provide a default value for the parent of a resource. This supports the
`lazy { }` helper as with normal default values.
* New feature: use `forced_keys: [:name]` on an option collector property to
force keys that would otherwise be clobbered by resource methods.
* Can enable verbose logging mode via a node attribute in addition to an
environment variable.
## v2.2.3
* Add `ancestor_send` utility method for use in other helpers.
* Improve subresource support for use in mixins.
## v2.2.2
* Fix 2.2.1 for older versions of Chef.
## v2.2.1
* Fixed delayed notifications inside `notifying_block`.
* Default actions as expected within LWRPs.
## v2.2.0
* Compatibility with Chef 12.4.1 and Chefspec 4.3.0.
* New helper `ResourceCloning`: Disables resource cloning between Poise-based
resources. This is enabled by default.
* Subresource parent references can be set to nil.
## v2.1.0
* Compatibility with Chef 12.4.
* Add `#property` as an alias for `#attribute` in resources. This provides
forward compatibility with future versions of Chef.
* Freeze default resource attribute values. **This may break your code**,
however this is not a major release because any code broken by this change
was itself already a bug.
## v2.0.1
* Make the ChefspecHelpers helper a no-op if chefspec is not already loaded.

View File

@@ -10,7 +10,7 @@
## What is Poise?
The poise cookbook is a set of libraries for writing reusable cookbooks. It
providers helpers for common patterns and a standard structure to make it easier to create flexible cookbooks.
provides helpers for common patterns and a standard structure to make it easier to create flexible cookbooks.
## Writing your first resource
@@ -21,35 +21,51 @@ the resource, which is in turn based on the class name. This means that the file
An example of a simple shell to start from:
```ruby
class Chef
class Resource::MyApp < Resource
include Poise
require 'poise'
require 'chef/resource'
require 'chef/provider'
module MyApp
class Resource < Chef::Resource
include Poise
provides(:my_app)
actions(:enable)
attribute(:path, kind_of: String)
... # Other attribute definitions
# Other attribute definitions.
end
class Provider::MyApp < Provider
class Provider < Chef::Provider
include Poise
provides(:my_app)
def action_enable
converge_by("enable resource #{new_resource.name}") do
notifying_block do
... # Normal Chef recipe code goes here
end
notifying_block do
... # Normal Chef recipe code goes here
end
end
end
end
```
Starting from the top, first we declare the resource class, which inherits from
`Chef::Resource`. This is similar to the `resources/` file in an LWRP, and a similar DSL can be used. In order to load the helpers into the class, we
include the `Poise` mixin. Then we use the familiar DSL, though with a few additions we'll cover later.
Starting from the top, first we require the libraries we will be using. Then we
create a module to hold our resource and provider. If your cookbook declares
multiple resources and/or providers, you might want additional nesting here.
Then we declare the resource class, which inherits from `Chef::Resource`. This
is similar to the `resources/` file in an LWRP, and a similar DSL can be used.
We then include the `Poise` mixin to load our helpers, and then call
`provides(:my_app)` to tell Chef this class will implement the `my_app`
resource. Then we use the familiar DSL, though with a few additions we'll cover
later.
Then we declare the provider class, again similar to the `providers/` file in an LWRP. We include the `Poise` mixin again to get access to all the helpers. Rather than use the `action :enable do ... end` DSL from LWRPs, we just define the action method directly, and use the `converge_by` method to provide a description of what the action does. The implementation of action comes from a block of recipe code wrapped with `notifying_block` to capture changes in much the same way as `use_inline_resources`, see below for more information about all the features of `notifying_block`.
Then we declare the provider class, again similar to the `providers/` file in an
LWRP. We include the `Poise` mixin again to get access to all the helpers and
call `provides()` to tell Chef what provider this is. Rather than use the
`action :enable do ... end` DSL from LWRPs, we just define the action method
directly. The implementation of action comes from a block of recipe code
wrapped with `notifying_block` to capture changes in much the same way as
`use_inline_resources`, see below for more information about all the features of
`notifying_block`.
We can then use this resource like any other Chef resource:
@@ -177,6 +193,25 @@ end
This will be converted to `{key1: 'value1', key2: 'value2'}`. You can also pass a Hash to an option collector attribute just as you would with a normal attribute.
## Debugging Poise
Poise has its own extra-verbose level of debug logging that can be enabled in
three different ways. You can either set the environment variable `$POISE_DEBUG`,
set a node attribute `node['POISE_DEBUG']`, or touch the file `/POISE_DEBUG`.
You will see a log message `Extra verbose logging enabled` at the start of the
run to confirm Poise debugging has been enabled. Make sure you also set Chef's
log level to `debug`, usually via `-l debug` on the command line.
## Upgrading from Poise 1.x
The biggest change when upgrading from Poise 1.0 is that the mixin is no longer
loaded automatically. You must add `require 'poise'` to your code is you want to
load it, as you would with normal Ruby code outside of Chef. It is also highly
recommended to add `provides(:name)` calls to your resources and providers, this
will be required in Chef 13 and will display a deprecation warning if you do
not. This also means you can move your code out of the `Chef` module namespace
and instead declare it in your own namespace. An example of this is shown above.
## Sponsors
The Poise test server infrastructure is generously sponsored by [Rackspace](https://rackspace.com/). Thanks Rackspace!

View File

@@ -22,12 +22,44 @@ require 'poise/utils/resource_provider_mixin'
module Poise
include Poise::Utils::ResourceProviderMixin
autoload :Backports, 'poise/backports'
autoload :Helpers, 'poise/helpers'
autoload :NOT_PASSED, 'poise/backports/not_passed'
autoload :Provider, 'poise/provider'
autoload :Resource, 'poise/resource'
autoload :Subcontext, 'poise/subcontext'
autoload :Utils, 'poise/utils'
autoload :VERSION, 'poise/version'
# Check if Poise's extra debugging output is enabled. This produces a *lot*
# of logging.
#
# @param node [Chef::Node, Chef::RunContext] Optional node to check for
# attributes. If not given, Chef.node is used instead.
# @return [Boolean]
def self.debug?(node=nil)
node = node.node if node.is_a?(Chef::RunContext)
node ||= Chef.node if defined?(Chef.node)
@debug_file_upper = ::File.exist?('/POISE_DEBUG') unless defined?(@debug_file_upper)
@debug_file_lower = ::File.exist?('/poise_debug') unless defined?(@debug_file_lower)
!!(
(ENV['POISE_DEBUG'] && ENV['POISE_DEBUG'] != 'false') ||
(ENV['poise_debug'] && ENV['poise_debug'] != 'false') ||
(node && node['POISE_DEBUG']) ||
(node && node['poise_debug']) ||
@debug_file_upper ||
@debug_file_lower
)
end
# Log a message only if Poise's extra debugging output is enabled.
#
# @see #debug?
# @param msg [String] Log message.
# @return [void]
def self.debug(msg)
Chef::Log.debug(msg) if debug?
end
end
# Callable form to allow passing in options:
@@ -57,7 +89,7 @@ def Poise(options={})
# Resource-specific options.
if klass < Chef::Resource
klass.poise_subresource(options[:parent], options[:parent_optional], options[:parent_auto]) if options[:parent]
klass.poise_subresource_container(options[:container_namespace]) if options[:container]
klass.poise_subresource_container(options[:container_namespace], options[:container_default]) if options[:container]
klass.poise_fused if options[:fused]
klass.poise_inversion(options[:inversion_options_resource]) if options[:inversion]
end
@@ -69,3 +101,7 @@ def Poise(options={})
mod
end
# Display a message if poise_debug is enabled. Off in ChefSpec so I don't get
# extra logging stuff that I don't care about.
Poise.debug('[Poise] Extra verbose logging enabled') unless defined?(ChefSpec)

View File

@@ -0,0 +1,28 @@
#
# Copyright 2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Poise
# Backported features from Chef to be able to use them with older versions.
#
# @since 2.3.0
module Backports
autoload :NOT_PASSED, 'poise/backports/not_passed'
autoload :VERIFY_PATH, 'poise/backports/verify_path'
end
autoload :NOT_PASSED, 'poise/backports/not_passed'
end

View File

@@ -0,0 +1,52 @@
#
# Copyright 2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
begin
require 'chef/constants'
rescue LoadError
# This space left intentionally blank.
end
module Poise
module Backports
# A sentinel value for optional arguments where nil is a valid value.
# @since 2.3.0
# @!parse NOT_PASSED = Object.new
NOT_PASSED = if defined?(Chef::NOT_PASSED)
Chef::NOT_PASSED
else
# Copyright 2015, Chef Software Inc.
# Used under Apache License, Version 2.0.
Object.new.tap do |not_passed|
def not_passed.to_s
"NOT_PASSED"
end
def not_passed.inspect
to_s
end
not_passed.freeze
end
end
end
# An alias to {Backports::NOT_PASSED} to avoid typing so much.
#
# @since 2.3.0
# @see Backports::NOT_PASSED
NOT_PASSED = Backports::NOT_PASSED
end

View File

@@ -0,0 +1,33 @@
#
# Copyright 2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Poise
module Backports
# The correct interpolation key for any version of Chef.
# @since 2.6.0
# @example
# file '/path' do
# content my_content
# verify "myapp -t #{Poise::Backports::VERIFY_PATH}"
# end
VERIFY_PATH = if Gem::Version.create(Chef::VERSION) < Gem::Version.create('12.5.0')
'%{file}'
else
'%{path}'
end
end
end

View File

@@ -26,7 +26,9 @@ module Poise
autoload :LWRPPolyfill, 'poise/helpers/lwrp_polyfill'
autoload :NotifyingBlock, 'poise/helpers/notifying_block'
autoload :OptionCollector, 'poise/helpers/option_collector'
autoload :ResourceCloning, 'poise/helpers/resource_cloning'
autoload :ResourceName, 'poise/helpers/resource_name'
autoload :ResourceSubclass, 'poise/helpers/resource_subclass'
autoload :Subresources, 'poise/helpers/subresources'
autoload :TemplateContent, 'poise/helpers/template_content'
end

View File

@@ -60,9 +60,13 @@ module Poise
# Create a resource-level matcher for this resource.
#
# @see Resource::ResourceName.provides
def provides(name)
def provides(name, *args, &block)
super(name, *args, &block)
ChefSpec.define_matcher(name) if defined?(ChefSpec)
super
# Call #actions here to grab any actions from a parent class.
actions.each do |action|
ChefspecMatchers.create_matcher(name, action)
end
end
# Create matchers for all declared actions.
@@ -72,7 +76,7 @@ module Poise
super.tap do |actions|
actions.each do |action|
ChefspecMatchers.create_matcher(resource_name, action)
end
end if resource_name && resource_name != :resource && !names.empty?
end
end

View File

@@ -65,9 +65,9 @@ module Poise
# @return [String]
def poise_defined_in_cookbook(run_context, file=nil)
file ||= poise_defined_in
Chef::Log.debug("[#{self.name}] Checking cookbook name for #{file}")
Poise.debug("[#{self.name}] Checking cookbook name for #{file}")
Poise::Utils.find_cookbook_name(run_context, file).tap do |cookbook|
Chef::Log.debug("[#{self.name}] found cookbook #{cookbook.inspect}")
Poise.debug("[#{self.name}] found cookbook #{cookbook.inspect}")
end
end

View File

@@ -19,6 +19,7 @@ require 'chef/node_map'
require 'chef/provider'
require 'chef/resource'
require 'poise/backports'
require 'poise/helpers/defined_in'
require 'poise/error'
require 'poise/helpers/inversion/options_resource'
@@ -77,13 +78,28 @@ module Poise
# end
def provider(val=nil)
if val && !val.is_a?(Class)
provider_class = Poise::Helpers::Inversion.provider_for(resource_name, node, val)
Chef::Log.debug("[#{self}] Checking for an inversion provider for #{val}: #{provider_class && provider_class.name}")
resource_names = [resource_name]
# If subclass_providers! might be in play, check for those names too.
resource_names.concat(self.class.subclass_resource_equivalents) if self.class.respond_to?(:subclass_resource_equivalents)
# Silly ruby tricks to find the first provider that exists and no more.
provider_class = resource_names.lazy.map {|name| Poise::Helpers::Inversion.provider_for(name, node, val) }.select {|x| x }.first
Poise.debug("[#{self}] Checking for an inversion provider for #{val}: #{provider_class && provider_class.name}")
val = provider_class if provider_class
end
super
end
# Set or return the array of provider names to be blocked from
# auto-resolution.
#
# @param val [String, Array<String>] Value to set.
# @return [Array<String>]
def provider_no_auto(val=nil)
# Coerce to an array.
val = Array(val).map(&:to_s) if val
set_or_return(:provider_no_auto, val, kind_of: Array, default: [])
end
# @!classmethods
module ClassMethods
# Options resource class.
@@ -117,6 +133,9 @@ module Poise
define_singleton_method(:name) do
"#{enclosing_class}::OptionsResource"
end
define_singleton_method(:inversion_resource_class) do
enclosing_class
end
provides(options_resource_name)
inversion_resource(name)
end
@@ -126,6 +145,9 @@ module Poise
define_singleton_method(:name) do
"#{enclosing_class}::OptionsProvider"
end
define_singleton_method(:inversion_resource_class) do
enclosing_class
end
provides(options_resource_name)
end
end
@@ -134,9 +156,9 @@ module Poise
#
# @param name [Symbol] Resource name
# return [void]
def provides(name)
def provides(name, *args, &block)
create_inversion_options_resource!(name) if inversion_options_resource
super if defined?(super)
super(name, *args, &block) if defined?(super)
end
def included(klass)
@@ -170,40 +192,48 @@ module Poise
module ClassMethods
# @overload inversion_resource()
# Return the inversion resource name for this class.
# @return [Symbol]
# @return [Symbo, nill]
# @overload inversion_resource(val)
# Set the inversion resource name for this class. You can pass either
# a symbol in DSL format or a resource class that uses Poise. This
# name is used to determine which resources the inversion provider is
# a candidate for.
# @param val [Symbol, Class] Name to set.
# @return [Symbol]
def inversion_resource(val=nil)
if val
# @return [Symbol, nil]
def inversion_resource(val=Poise::NOT_PASSED)
if val != Poise::NOT_PASSED
val = val.resource_name if val.is_a?(Class)
Chef::Log.debug("[#{self.name}] Setting inversion resource to #{val}")
@poise_inversion_resource = val.to_sym
end
@poise_inversion_resource || (superclass.respond_to?(:inversion_resource) ? superclass.inversion_resource : nil)
if defined?(@poise_inversion_resource)
@poise_inversion_resource
else
Poise::Utils.ancestor_send(self, :inversion_resource, default: nil)
end
end
# @overload inversion_attribute()
# Return the inversion attribute name(s) for this class.
# @return [Array<String>]
# @return [Array<String>, nil]
# @overload inversion_attribute(val)
# Set the inversion attribute name(s) for this class. This is
# used by {.resolve_inversion_attribute} to load configuration data
# from node attributes. To specify a nested attribute pass an array
# of strings corresponding to the keys.
# @param val [String, Array<String>] Attribute path.
# @return [Array<String>]
def inversion_attribute(val=nil)
if val
# @return [Array<String>, nil]
def inversion_attribute(val=Poise::NOT_PASSED)
if val != Poise::NOT_PASSED
# Coerce to an array of strings.
val = Array(val).map {|name| name.to_s }
@poise_inversion_attribute = val
end
@poise_inversion_attribute || (superclass.respond_to?(:inversion_attribute) ? superclass.inversion_attribute : nil)
if defined?(@poise_inversion_attribute)
@poise_inversion_attribute
else
Poise::Utils.ancestor_send(self, :inversion_attribute, default: nil)
end
end
# Default attribute paths to check for inversion options. Based on
@@ -235,6 +265,7 @@ module Poise
def resolve_inversion_attribute(node)
# Default to using just the name of the cookbook.
attribute_names = inversion_attribute || default_inversion_attributes(node)
return {} if attribute_names.empty?
attribute_names.inject(node) do |memo, key|
memo[key] || begin
raise Poise::Error.new("Attribute #{key} not set when expanding inversion attribute for #{self.name}: #{memo}")
@@ -257,19 +288,21 @@ module Poise
# Class-level defaults.
opts.update(default_inversion_options(node, resource))
# Resource options for all providers.
opts.update(resource.options)
opts.update(resource.options) if resource.respond_to?(:options)
# Global provider from node attributes.
opts.update(provider: attrs['provider']) if attrs['provider']
# Attribute options for all providers.
opts.update(attrs['options']) if attrs['options']
# Resource options for this provider.
opts.update(resource.options(provides))
opts.update(resource.options(provides)) if resource.respond_to?(:options)
# Attribute options for this resource name.
opts.update(attrs[resource.name]) if attrs[resource.name]
# Options resource options for all providers.
opts.update(run_state['*']) if run_state['*']
# Options resource options for this provider.
opts.update(run_state[provides]) if run_state[provides]
# Vomitdebug output for tracking down weirdness.
Poise.debug("[#{resource}] Resolved inversion options: #{opts.inspect}")
end
end
@@ -323,10 +356,17 @@ module Poise
# @return [Boolean]
def provides?(node, resource)
raise Poise::Error.new("Inversion resource name not set for #{self.name}") unless inversion_resource
return false unless resource.resource_name == inversion_resource
resource_name_equivalents = {resource.resource_name => true}
# If subclass_providers! might be in play, check for those names too.
if resource.class.respond_to?(:subclass_resource_equivalents)
resource.class.subclass_resource_equivalents.each do |name|
resource_name_equivalents[name] = true
end
end
return false unless resource_name_equivalents[inversion_resource]
provider_name = resolve_inversion_provider(node, resource)
Chef::Log.debug("[#{resource}] Checking provides? on #{self.name}. Got provider_name #{provider_name.inspect}")
provider_name == provides.to_s || ( provider_name == 'auto' && provides_auto?(node, resource) )
Poise.debug("[#{resource}] Checking provides? on #{self.name}. Got provider_name #{provider_name.inspect}")
provider_name == provides.to_s || ( provider_name == 'auto' && !resource.provider_no_auto.include?(provides.to_s) && provides_auto?(node, resource) )
end
# Subclass hook to provide auto-detection for providers.

View File

@@ -14,6 +14,8 @@
# limitations under the License.
#
require 'chef/version'
module Poise
module Helpers
@@ -29,13 +31,28 @@ module Poise
# attribute(:path, default: lazy { name + '_temp' })
# end
module LazyDefault
# Check if this version of Chef already supports lazy defaults. This is
# true for Chef 12.5+.
#
# @since 2.0.3
# @api private
# @return [Boolean]
def self.needs_polyfill?
@needs_polyfill ||= Gem::Requirement.new('< 12.5.pre').satisfied_by?(Gem::Version.new(Chef::VERSION))
end
# Override the default set_or_return to support lazy evaluation of the
# default value. This only actually matters when it is called from a class
# level context via #attributes.
def set_or_return(symbol, arg, validation)
if validation && validation[:default].is_a?(Chef::DelayedEvaluator)
if LazyDefault.needs_polyfill? && validation && validation[:default].is_a?(Chef::DelayedEvaluator)
validation = validation.dup
validation[:default] = instance_eval(&validation[:default])
if (arg.nil? || arg == Poise::NOT_PASSED) && (!instance_variable_defined?(:"@#{symbol}") || instance_variable_get(:"@#{symbol}").nil?)
validation[:default] = instance_eval(&validation[:default])
else
# Clear the default.
validation.delete(:default)
end
end
super(symbol, arg, validation)
end

View File

@@ -14,6 +14,8 @@
# limitations under the License.
#
require 'chef/resource'
require 'poise/utils/resource_provider_mixin'
@@ -30,35 +32,92 @@ module Poise
module Resource
def initialize(*args)
super
# Try to not stomp on stuff if already set in a parent
@action = self.class.default_action if @action == :nothing
# Try to not stomp on stuff if already set in a parent. Coerce @action
# to an array because this behavior may change in the future in Chef.
@action = self.class.default_action if Array(@action) == [:nothing]
(@allowed_actions << self.class.actions).flatten!.uniq!
end
# @!classmethods
module ClassMethods
# @overload default_action()
# Get the default action for this resource class. If no explicit
# default is set, the first action in the list will be used.
# @see #actions
# @return [Array<Symbol>]
# @overload default_action(name)
# Set the default action for this resource class. If this action is
# not already allowed, it will be added.
# @note It is idiomatic to use {#actions} instead, with the first
# action specified being the default.
# @param name [Symbol, Array<Symbol>] Name of the action(s).
# @return [Array<Symbol>]
# @example
# class MyApp < Chef::Resource
# include Poise
# default_action(:install)
# end
def default_action(name=nil)
if name
name = Array(name).flatten.map(&:to_sym)
@default_action = name
actions(name)
actions(*name)
end
if @default_action
@default_action
elsif respond_to?(:superclass) && superclass != Chef::Resource && superclass.respond_to?(:default_action) && superclass.default_action && Array(superclass.default_action) != %i{nothing}
superclass.default_action
elsif first_non_nothing = actions.find {|action| action != :nothing }
[first_non_nothing]
else
%i{nothing}
end
@default_action || ( respond_to?(:superclass) && superclass.respond_to?(:default_action) && superclass.default_action ) || actions.first || :nothing
end
# @overload actions()
# Get all actions allowed for this resource class. This includes
# any actions allowed on parent classes.
# @return [Array<Symbol>]
# @overload actions(*names)
# Set actions as allowed for this resource class. These must
# correspond with action methods in the provider class(es).
# @param names [Array<Symbol>] One or more actions to set.
# @return [Array<Symbol>]
# @example
# class MyApp < Chef::Resource
# include Poise
# actions(:install, :uninstall)
# end
def actions(*names)
@actions ||= ( respond_to?(:superclass) && superclass.respond_to?(:actions) ? superclass.actions.dup : [] )
(@actions << names).flatten!.uniq!
@actions
@actions ||= ( respond_to?(:superclass) && superclass.respond_to?(:actions) && superclass.actions.dup ) || ( respond_to?(:superclass) && superclass != Chef::Resource && superclass.respond_to?(:allowed_actions) && superclass.allowed_actions.dup ) || []
(@actions << names).tap {|actions| actions.flatten!; actions.uniq! }
end
def attribute(name, opts)
# Ruby 1.8 can go to hell
# Create a resource property (née attribute) on this resource class.
# This follows the same usage as the helper of the same name in Chef
# LWRPs.
#
# @param name [Symbol] Name of the property.
# @param opts [Hash<Symbol, Object>] Validation options and flags.
# @return [void]
# @example
# class MyApp < Chef::Resource
# include Poise
# attribute(:path, name_attribute: true)
# attribute(:port, kind_of: Integer, default: 8080)
# end
def attribute(name, opts={})
# Freeze the default value. This is done upstream too in Chef 12.5+.
opts[:default].freeze if opts && opts[:default]
# Ruby 1.8 can go to hell.
define_method(name) do |arg=nil, &block|
arg = block if arg.nil? # Try to allow passing either
arg = block if arg.nil? # Try to allow passing either.
set_or_return(name, arg, opts)
end
end
# For forward compat with Chef 12.5+.
alias_method :property, :attribute
def included(klass)
super
klass.extend(ClassMethods)
@@ -70,6 +129,17 @@ module Poise
# Helper to handle load_current_resource for direct subclasses of Provider
module Provider
module LoadCurrentResource
def load_current_resource
@current_resource = if new_resource
new_resource.class.new(new_resource.name, run_context)
else
# Better than nothing, subclass can overwrite anyway.
Chef::Resource.new(nil, run_context)
end
end
end
# @!classmethods
module ClassMethods
def included(klass)
@@ -78,14 +148,11 @@ module Poise
# Mask Chef::Provider#load_current_resource because it throws NotImplementedError.
if klass.is_a?(Class) && klass.superclass == Chef::Provider
klass.class_exec do
def load_current_resource
end
end
klass.send(:include, LoadCurrentResource)
end
# Reinstate the Chef DSL, removed in Chef 12.
klass.class_exec { include Chef::DSL::Recipe }
klass.send(:include, Chef::DSL::Recipe)
end
end

View File

@@ -44,18 +44,25 @@ module Poise
class OptionEvalContext
attr_reader :_options
def initialize(parent)
def initialize(parent, forced_keys)
@parent = parent
@forced_keys = forced_keys
@_options = {}
end
def method_missing(method_sym, *args, &block)
# Deal with forced keys.
if @forced_keys.include?(method_sym)
@_options[method_sym] = args.first || block if !args.empty? || block
return @_options[method_sym]
end
# Try the resource context.
@parent.send(method_sym, *args, &block)
rescue NameError
# Even though method= in the block will set a variable instead of
# calling method_missing, still try to cope in case of self.method=.
method_sym = method_sym.to_s.chomp('=').to_sym
if args.length > 0 || block
if !args.empty? || block
@_options[method_sym] = args.first || block
elsif !@_options.include?(method_sym)
# We haven't seen this name before, re-raise the NameError.
@@ -86,8 +93,12 @@ module Poise
# @param parser [Proc, Symbol] Optional parser method. If a symbol it is
# called as a method on self. Takes a non-hash value and returns a
# hash of its parsed representation.
def option_collector_attribute(name, default: {}, parser: nil)
# @param forced_keys [Array<Symbol>, Set<Symbol>] Method names that will be forced
# to be options rather than calls to the parent resource.
def option_collector_attribute(name, default: {}, parser: nil, forced_keys: Set.new)
raise Poise::Error.new("Parser must be a Proc or Symbol: #{parser.inspect}") if parser && !(parser.is_a?(Proc) || parser.is_a?(Symbol))
# Cast to a set at definition time.
forced_keys = Set.new(forced_keys) unless forced_keys.is_a?(Set)
# Unlike LWRPBase.attribute, I don't care about Ruby 1.8. Worlds tiniest violin.
define_method(name.to_sym) do |arg=nil, &block|
iv_sym = :"@#{name}"
@@ -110,7 +121,7 @@ module Poise
value.update(arg)
end
if block
ctx = OptionEvalContext.new(self)
ctx = OptionEvalContext.new(self, forced_keys)
ctx.instance_exec(&block)
value.update(ctx._options)
end

View File

@@ -0,0 +1,72 @@
#
# Copyright 2013-2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module Poise
module Helpers
# A resource mixin to disable resource cloning.
#
# @since 2.2.0
# @example
# class MyResource < Chef::Resource
# include Poise::Helpers::ResourceCloning
# end
module ResourceCloning
# Override to disable resource cloning on Chef 12.0.
#
# @api private
def load_prior_resource(*args)
# Do nothing.
end
# Override to disable resource cloning on Chef 12.1+.
#
# @api private
def load_from(*args)
# Do nothing.
end
# Monkeypatch for Chef::ResourceBuilder to silence the warning if needed.
#
# @api private
module ResourceBuilderPatch
# @api private
def self.install!
begin
require 'chef/resource_builder'
Chef::ResourceBuilder.send(:prepend, ResourceBuilderPatch)
rescue LoadError
# For 12.0, this is already taken care of.
end
end
# @api private
def emit_cloned_resource_warning
super unless resource.is_a?(ResourceCloning)
end
# @api private
def emit_harmless_cloning_debug
super unless resource.is_a?(ResourceCloning)
end
end
# Install the patch.
ResourceBuilderPatch.install!
end
end
end

View File

@@ -51,7 +51,7 @@ module Poise
# include Poise::Resource::ResourceName
# provides(:my_resource)
# end
def provides(name)
def provides(name, *args, &block)
# Patch self.constantize so this can cope with anonymous classes.
# This does require that the anonymous class define self.name though.
if self.name && respond_to?(:constantize)
@@ -61,9 +61,9 @@ module Poise
end
end
# Store the name for later.
@provides_name = name
@provides_name ||= name
# Call the original if present. The defined? is for old Chef.
super if defined?(super)
super(name, *args, &block) if defined?(super)
end
# Retreive the DSL name for the resource class. If not set explicitly
@@ -72,11 +72,19 @@ module Poise
# @param auto [Boolean] Try to auto-detect based on class name.
# @return [Symbol]
def resource_name(auto=true)
return @provides_name if @provides_name
@provides_name || if name && name.start_with?('Chef::Resource')
Chef::Mixin::ConvertToClassName.convert_to_snake_case(name, 'Chef::Resource').to_sym
elsif name
Chef::Mixin::ConvertToClassName.convert_to_snake_case(name.split('::').last).to_sym
# In 12.4+ we need to proxy through the super class for setting.
return super(auto) if defined?(super) && (auto.is_a?(Symbol) || auto.is_a?(String))
return @provides_name unless auto
@provides_name || if name
mode = if name.start_with?('Chef::Resource')
[name, 'Chef::Resource']
else
[name.split('::').last]
end
Chef::Mixin::ConvertToClassName.convert_to_snake_case(*mode).to_sym
elsif defined?(super)
# No name on 12.4+ probably means this is an LWRP, use super().
super()
end
end

View File

@@ -0,0 +1,82 @@
#
# Copyright 2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'poise/error'
require 'poise/helpers/resource_name'
module Poise
module Helpers
# A resource mixin to help subclass existing resources.
#
# @since 2.3.0
module ResourceSubclass
include ResourceName
module ClassMethods
def subclass_providers!(superclass_resource_name=nil, resource_name: nil)
resource_name ||= self.resource_name
superclass_resource_name ||= if superclass.respond_to?(:resource_name)
superclass.resource_name
elsif superclass.respond_to?(:dsl_name)
superclass.dsl_name
else
raise Poise::Error.new("Unable to determine superclass resource name for #{superclass}. Please specify name manually via subclass_providers!('name').")
end.to_sym
# Deal with the node maps.
node_maps = {}
node_maps['handler map'] = Chef.provider_handler_map if defined?(Chef.provider_handler_map)
node_maps['priority map'] = Chef.provider_priority_map if defined?(Chef.provider_priority_map)
# Patch anything in the descendants tracker.
Chef::Provider.descendants.each do |provider|
node_maps["#{provider} node map"] = provider.node_map if defined?(provider.node_map)
end if defined?(Chef::Provider.descendants)
node_maps.each do |map_name, node_map|
map = node_map.respond_to?(:map, true) ? node_map.send(:map) : node_map.instance_variable_get(:@map)
if map.include?(superclass_resource_name)
Chef::Log.debug("[#{self}] Copying provider mapping in #{map_name} from #{superclass_resource_name} to #{resource_name}")
map[resource_name] = map[superclass_resource_name].dup
end
end
# Add any needed equivalent names.
if superclass.respond_to?(:subclass_resource_equivalents)
subclass_resource_equivalents.concat(superclass.subclass_resource_equivalents)
else
subclass_resource_equivalents << superclass_resource_name
end
subclass_resource_equivalents.uniq!
end
# An array of names for the resources this class is equivalent to for
# the purposes of provider resolution.
#
# @return [Array<Symbol>]
def subclass_resource_equivalents
@subclass_resource_names ||= [resource_name.to_sym]
end
# @api private
def included(klass)
super
klass.extend(ClassMethods)
end
end
extend ClassMethods
end
end
end

View File

@@ -27,10 +27,24 @@ module Poise
private
def subcontext_block(parent_context=nil, &block)
# Setup a sub-run-context.
# Setup a subcontext.
parent_context ||= @run_context
sub_run_context = parent_context.dup
# Reset state for the subcontext. In 12.4+ this uses the built-in
# support, otherwise do it manually.
if defined?(sub_run_context.initialize_child_state)
sub_run_context.initialize_child_state
else
# Audits was added in 12.1 I think.
sub_run_context.audits = {} if defined?(sub_run_context.audits)
# Dup and clear to preserve the default behavior without copy-pasta.
sub_run_context.immediate_notification_collection = parent_context.immediate_notification_collection.dup.clear
sub_run_context.delayed_notification_collection = parent_context.delayed_notification_collection.dup.clear
end
# Create the subcollection.
sub_run_context.resource_collection = Poise::Subcontext::ResourceCollection.new(parent_context.resource_collection)
# Create an accessor for the parent run context.
sub_run_context.define_singleton_method(:parent_run_context) { parent_context }
# Declare sub-resources within the sub-run-context. Since they
# are declared here, they do not pollute the parent run-context.

View File

@@ -37,6 +37,10 @@ module Poise
@resource = resource
end
def inspect
to_text
end
def to_text
if @resource.nil?
'nil'
@@ -56,8 +60,12 @@ module Poise
# string), or a type:name hash.
# @param val [String, Hash, Chef::Resource] Parent resource to set.
# @return [Chef::Resource, nil]
def parent(val=nil)
_parent(:parent, self.class.parent_type, self.class.parent_optional, self.class.parent_auto, val)
def parent(*args)
# Lie about this method if the parent type is true.
if self.class.parent_type == true
raise NoMethodError.new("undefined method `parent' for #{self}")
end
_parent(:parent, self.class.parent_type, self.class.parent_optional, self.class.parent_auto, self.class.parent_default, *args)
end
# Register ourself with parents in case this is not a nested resource.
@@ -67,7 +75,7 @@ module Poise
super
self.class.parent_attributes.each_key do |name|
parent = self.send(name)
parent.register_subresource(self) if parent
parent.register_subresource(self) if parent && parent.respond_to?(:register_subresource)
end
end
@@ -77,40 +85,68 @@ module Poise
#
# @since 2.0.0
# @see #parent
def _parent(name, parent_type, parent_optional, parent_auto, val=nil)
def _parent(name, parent_type, parent_optional, parent_auto, parent_default, *args)
# Allow using a DSL symbol as the parent type.
if parent_type.is_a?(Symbol)
parent_type = Chef::Resource.resource_for_node(parent_type, node)
end
# Grab the ivar for local use.
parent_ref = instance_variable_get(:"@#{name}")
if val
if val.is_a?(String) && !val.include?('[')
raise Poise::Error.new('Cannot use a string parent without defining a parent type') if parent_type == Chef::Resource
val = "#{parent_type.resource_name}[#{val}]"
end
if val.is_a?(String) || val.is_a?(Hash)
parent = @run_context.resource_collection.find(val)
if !args.empty?
val = args.first
if val.nil?
# Unsetting the parent.
parent = parent_ref = nil
else
parent = val
if val.is_a?(String) && !val.include?('[')
raise Poise::Error.new("Cannot use a string #{name} without defining a parent type") if parent_type == Chef::Resource
# Try to find the most recent instance of parent_type with a
# matching name. This takes subclassing parent_type into account.
found_val = nil
iterator = run_context.resource_collection.respond_to?(:recursive_each) ? :recursive_each : :each
# This will find the last matching value due to overwriting
# found_val as it goes. Will be the nearest match.
run_context.resource_collection.public_send(iterator) do |res|
found_val = res if res.is_a?(parent_type) && res.name == val
end
# If found_val is nil, fall back to using lookup even though
# it won't work with subclassing, better than nothing?
val = found_val || "#{parent_type.resource_name}[#{val}]"
end
if val.is_a?(String) || val.is_a?(Hash)
parent = @run_context.resource_collection.find(val)
else
parent = val
end
if !parent.is_a?(parent_type)
raise Poise::Error.new("Parent resource is not an instance of #{parent_type.name}: #{val.inspect}")
end
parent_ref = ParentRef.new(parent)
end
if !parent.is_a?(parent_type)
raise Poise::Error.new("Parent resource is not an instance of #{parent_type.name}: #{val.inspect}")
elsif !parent_ref || !parent_ref.resource
if parent_default
parent = if parent_default.is_a?(Chef::DelayedEvaluator)
instance_eval(&parent_default)
else
parent_default
end
end
parent_ref = ParentRef.new(parent)
elsif !parent_ref
if parent_auto
# The @parent_ref means we won't run this if we previously set
# ParentRef.new(nil). This means auto-lookup only happens during
# after_created.
if !parent && !parent_ref && parent_auto
# Automatic sibling lookup for sequential composition.
# Find the last instance of the parent class as the default parent.
# This is super flaky and should only be a last resort.
parent = Poise::Helpers::Subresources::DefaultContainers.find(parent_type, run_context)
parent = Poise::Helpers::Subresources::DefaultContainers.find(parent_type, run_context, self_resource: self)
end
# Can't find a valid parent, if it wasn't optional raise an error.
raise Poise::Error.new("No parent found for #{self}") unless parent || parent_optional
raise Poise::Error.new("No #{name} found for #{self}") unless parent || parent_optional
parent_ref = ParentRef.new(parent)
else
parent = parent_ref.resource
end
raise Poise::Error.new("Cannot set the #{name} of #{self} to itself") if parent.equal?(self)
# Store the ivar back.
instance_variable_set(:"@#{name}", parent_ref)
# Return the actual resource.
@@ -128,9 +164,12 @@ module Poise
def parent_type(type=nil)
if type
raise Poise::Error.new("Parent type must be a class, symbol, or true, got #{type.inspect}") unless type.is_a?(Class) || type.is_a?(Symbol) || type == true
@parent_type = type
# Setting to true shouldn't actually do anything if a type was already set.
@parent_type = type unless type == true && !@parent_type.nil?
end
@parent_type || (superclass.respond_to?(:parent_type) ? superclass.parent_type : Chef::Resource)
# First ancestor_send looks for a non-true && non-default value,
# second one is to check for default vs true if no real value is found.
@parent_type || Poise::Utils.ancestor_send(self, :parent_type, ignore: [Chef::Resource, true]) || Poise::Utils.ancestor_send(self, :parent_type, default: Chef::Resource)
end
# @overload parent_optional()
@@ -145,7 +184,7 @@ module Poise
@parent_optional = val
end
if @parent_optional.nil?
superclass.respond_to?(:parent_optional) ? superclass.parent_optional : false
Poise::Utils.ancestor_send(self, :parent_optional, default: false)
else
@parent_optional
end
@@ -163,12 +202,32 @@ module Poise
@parent_auto = val
end
if @parent_auto.nil?
superclass.respond_to?(:parent_auto) ? superclass.parent_auto : true
Poise::Utils.ancestor_send(self, :parent_auto, default: true)
else
@parent_auto
end
end
# @overload parent_default()
# Get the default value for the default parent link on this resource.
# @since 2.3.0
# @return [Object, Chef::DelayedEvaluator]
# @overload parent_default(val)
# Set the default value for the default parent link on this resource.
# @since 2.3.0
# @param val [Object, Chef::DelayedEvaluator] Default value to set.
# @return [Object, Chef::DelayedEvaluator]
def parent_default(*args)
unless args.empty?
@parent_default = args.first
end
if defined?(@parent_default)
@parent_default
else
Poise::Utils.ancestor_send(self, :parent_default)
end
end
# Create a new kind of parent link.
#
# @since 2.0.0
@@ -178,11 +237,11 @@ module Poise
# @param optional [Boolean] If the parent is optional.
# @param auto [Boolean] If the parent is auto-detected.
# @return [void]
def parent_attribute(name, type: Chef::Resource, optional: false, auto: true)
def parent_attribute(name, type: Chef::Resource, optional: false, auto: true, default: nil)
name = :"parent_#{name}"
(@parent_attributes ||= {})[name] = type
define_method(name) do |val=nil|
_parent(name, type, optional, auto, val)
define_method(name) do |*args|
_parent(name, type, optional, auto, default, *args)
end
end
@@ -193,7 +252,7 @@ module Poise
def parent_attributes
{}.tap do |attrs|
# Grab superclass's attributes if possible.
attrs.update(superclass.parent_attributes) if superclass.respond_to?(:parent_attributes)
attrs.update(Poise::Utils.ancestor_send(self, :parent_attributes, default: {}))
# Local default parent.
attrs[:parent] = parent_type
# Extra locally defined parents.

View File

@@ -31,6 +31,10 @@ module Poise
# is used to show the value of @subresources during Chef's error formatting.
# @api private
class NoPrintingResourceCollection < Chef::ResourceCollection
def inspect
to_text
end
def to_text
"[#{all_resources.map(&:to_s).join(', ')}]"
end
@@ -40,23 +44,29 @@ module Poise
include Chef::DSL::Recipe
attr_reader :subresources
attr_reader :subcontexts
def initialize(*args)
super
@subresources = NoPrintingResourceCollection.new
@subcontexts = []
end
def after_created
super
# Register
Poise::Helpers::Subresources::DefaultContainers.register!(self, run_context)
# Register as a default container if needed.
Poise::Helpers::Subresources::DefaultContainers.register!(self, run_context) if self.class.container_default
# Add all internal subresources to the resource collection.
unless @subresources.empty?
Chef::Log.debug("[#{self}] Adding subresources to collection:")
# Because after_create is run before adding the container to the resource collection
# we need to jump through some hoops to get it swapped into place.
self_ = self
order_fixer = Chef::Resource::RubyBlock.new('subresource_order_fixer', @run_context)
# respond_to? is for <= 12.0.2, remove some day when I stop caring.
order_fixer.declared_type = 'ruby_block' if order_fixer.respond_to?(:declared_type=)
order_fixer.block do
Chef::Log.debug("[#{self_}] Running order fixer")
collection = self_.run_context.resource_collection
# Delete the current container resource from its current position.
collection.all_resources.delete(self_)
@@ -71,12 +81,30 @@ module Poise
# Step back so we re-run the "current" resource, which is now the
# container.
collection.iterator.skip_back
Chef::Log.debug("Collection: #{@run_context.resource_collection.map(&:to_s).join(', ')}")
end
@run_context.resource_collection.insert(order_fixer)
@subresources.each do |r|
Chef::Log.debug(" * #{r}")
@run_context.resource_collection.insert(r)
@subcontexts.each do |ctx|
# Copy all resources to the outer context.
ctx.resource_collection.each do |r|
Chef::Log.debug(" * #{r}")
# Fix the subresource to use the outer run context.
r.run_context = @run_context
@run_context.resource_collection.insert(r)
end
# Copy all notifications to the outer context.
%w{immediate delayed}.each do |notification_type|
ctx.send(:"#{notification_type}_notification_collection").each do |key, notifications|
notifications.each do |notification|
parent_notifications = @run_context.send(:"#{notification_type}_notification_collection")[key]
unless parent_notifications.any? { |existing_notification| existing_notification.duplicates?(notification) }
parent_notifications << notification
end
end
end
end
end
Chef::Log.debug("Collection: #{@run_context.resource_collection.map(&:to_s).join(', ')}")
end
end
@@ -90,7 +118,7 @@ module Poise
created_at ||= caller[0]
# Run this inside a subcontext to avoid adding to the current resource collection.
# It will end up added later, indirected via @subresources to ensure ordering.
subcontext_block do
@subcontexts << subcontext_block do
namespace = if self.class.container_namespace == true
# If the value is true, use the name of the container resource.
self.name
@@ -111,8 +139,13 @@ module Poise
end
resource << super(type, sub_name, created_at) do
# Apply the correct parent before anything else so it is available
# in after_created for the subresource.
parent(self_) if respond_to?(:parent)
# in after_created for the subresource. It might raise
# NoMethodError is there isn't a real parent.
begin
parent(self_) if respond_to?(:parent)
rescue NoMethodError
# This space left intentionally blank.
end
# Run the resource block.
instance_exec(&block) if block
end
@@ -124,11 +157,19 @@ module Poise
resource.first
end
# Register a resource as part of this container. Returns true if the
# resource was added to the collection and false if it was already
# known.
#
# @note Return value added in 2.4.0.
# @return [Boolean]
def register_subresource(resource)
subresources.lookup(resource)
false
rescue Chef::Exceptions::ResourceNotFound
Chef::Log.debug("[#{self}] Adding #{resource} to subresources")
subresources.insert(resource)
true
end
private
@@ -145,16 +186,39 @@ module Poise
def container_namespace(val=nil)
@container_namespace = val unless val.nil?
if @container_namespace.nil?
# Not set here, look at the superclass of true by default for backwards compat.
superclass.respond_to?(:container_namespace) ? superclass.container_namespace : true
# Not set here, look at the superclass or true by default for backwards compat.
Poise::Utils.ancestor_send(self, :container_namespace, default: true)
else
@container_namespace
end
end
# @overload container_default()
# Get the default mode for this resource. If false, this resource
# class will not be used for default container lookups. Defaults to
# true.
# @since 2.3.0
# @return [Boolean]
# @overload container_default(val)
# Set the default mode for this resource.
# @since 2.3.0
# @param val [Boolean] Default mode to set.
# @return [Boolean]
def container_default(val=nil)
@container_default = val unless val.nil?
if @container_default.nil?
# Not set here, look at the superclass or true by default for backwards compat.
Poise::Utils.ancestor_send(self, :container_default, default: true)
else
@container_default
end
end
def included(klass)
super
klass.extend(ClassMethods)
klass.const_get(:HIDDEN_IVARS) << :@subcontexts
klass.const_get(:FORBIDDEN_IVARS) << :@subcontexts
end
end

View File

@@ -47,10 +47,10 @@ module Poise
# @param klass [Class] Resource class to search for.
# @param run_context [Chef::RunContext] Context of the current run.
# @return [Chef::Resource]
def self.find(klass, run_context)
def self.find(klass, run_context, self_resource: nil)
CONTAINER_MUTEX.synchronize do
containers(run_context).reverse_each do |resource|
return resource if resource.is_a?(klass)
return resource if resource.is_a?(klass) && (!self_resource || self_resource != resource)
end
# Nothing found.
nil
@@ -65,6 +65,8 @@ module Poise
# @param run_context [Chef::RunContext] Context of the current run.
# @return [Array<Chef::Resource>]
def self.containers(run_context)
# For test cases where nil gets used sometimes.
return [] unless run_context && run_context.node && run_context.node.run_state
run_context.node.run_state[:poise_default_containers] ||= []
end
end

View File

@@ -68,6 +68,9 @@ module Poise
# Template variables if using a template
attribute("#{name_prefix}options", option_collector: true)
# Make an alias for #variables to match the template resource.
alias_method("#{name_prefix}variables", "#{name_prefix}options")
# The big one, get/set content, but if you are getting and no
# explicit content was given, try to render the template
define_method("#{name_prefix}content") do |arg=nil, no_compute=false|
@@ -97,7 +100,7 @@ module Poise
old_after_created = instance_method(:after_created)
define_method(:after_created) do
old_after_created.bind(self).call
send("_#{name_prefix}validate")
send("_#{name_prefix}validate") if Array(action) == Array(self.class.default_action)
end
end

View File

@@ -15,6 +15,7 @@
#
require 'poise/helpers'
require 'poise/utils'
module Poise
@@ -35,6 +36,7 @@ module Poise
include Poise::Helpers::IncludeRecipe
include Poise::Helpers::LWRPPolyfill
include Poise::Helpers::NotifyingBlock
include Poise::Utils::ShellOut
# @!classmethods
module ClassMethods

View File

@@ -15,6 +15,7 @@
#
require 'poise/helpers'
require 'poise/utils'
module Poise
@@ -34,18 +35,22 @@ module Poise
module Resource
include Poise::Helpers::ChefspecMatchers
include Poise::Helpers::DefinedIn
include Poise::Helpers::LazyDefault
include Poise::Helpers::LazyDefault if Poise::Helpers::LazyDefault.needs_polyfill?
include Poise::Helpers::LWRPPolyfill
include Poise::Helpers::OptionCollector
include Poise::Helpers::ResourceCloning
include Poise::Helpers::ResourceName
include Poise::Helpers::ResourceSubclass
include Poise::Helpers::TemplateContent
include Poise::Utils::ShellOut
# @!classmethods
module ClassMethods
def poise_subresource_container(namespace=nil)
def poise_subresource_container(namespace=nil, default=nil)
include Poise::Helpers::Subresources::Container
# false is a valid value.
container_namespace(namespace) unless namespace.nil?
container_default(default) unless default.nil?
end
def poise_subresource(parent_type=nil, parent_optional=nil, parent_auto=nil)

View File

@@ -40,7 +40,10 @@ module Poise
@parent.lookup(resource)
end
# Iterate and expand all nested contexts
# Iterate over all resources, expanding parent context in order.
#
# @param block [Proc] Iteration block
# @return [void]
def recursive_each(&block)
if @parent
if @parent.respond_to?(:recursive_each)
@@ -51,6 +54,22 @@ module Poise
end
each(&block)
end
# Iterate over all resources in reverse order.
#
# @since 2.3.0
# @param block [Proc] Iteration block
# @return [void]
def reverse_recursive_each(&block)
reverse_each(&block)
if @parent
if @parent.respond_to?(:recursive_each)
@parent.reverse_recursive_each(&block)
else
@parent.reverse_each(&block)
end
end
end
end
end
end

View File

@@ -36,8 +36,8 @@ module Poise
# ever fire because the superclass re-raises if there is an error.
return super if error
delayed_actions.each do |notification|
notifications = run_context.delayed_notifications(@resource)
if run_context.delayed_notifications(@resource).any? { |existing_notification| existing_notification.duplicates?(notification) }
notifications = run_context.parent_run_context.delayed_notifications(@resource)
if notifications.any? { |existing_notification| existing_notification.duplicates?(notification) }
Chef::Log.info( "#{@resource} not queuing delayed action #{notification.action} on #{notification.resource}"\
" (delayed), as it's already been queued")
else

View File

@@ -20,6 +20,7 @@ require 'poise/error'
module Poise
module Utils
autoload :ResourceProviderMixin, 'poise/utils/resource_provider_mixin'
autoload :ShellOut, 'poise/utils/shell_out'
extend self
@@ -37,15 +38,14 @@ module Poise
# end
def find_cookbook_name(run_context, filename)
possibles = {}
Chef::Log.debug("[Poise] Checking cookbook for #{filename.inspect}")
Poise.debug("[Poise] Checking cookbook for #{filename.inspect}")
run_context.cookbook_collection.each do |name, ver|
# This special method is added by Halite::Gem#as_cookbook_version.
if ver.respond_to?(:halite_root)
# The join is there because ../poise-ruby/lib starts with ../poise so
# we want a trailing /.
Chef::Log.debug("")
if filename.start_with?(File.join(ver.halite_root, ''))
Chef::Log.debug("[Poise] Found matching halite_root in #{name}: #{ver.halite_root.inspect}")
Poise.debug("[Poise] Found matching halite_root in #{name}: #{ver.halite_root.inspect}")
possibles[ver.halite_root] = name
end
else
@@ -53,9 +53,9 @@ module Poise
ver.segment_filenames(seg).each do |file|
# Put this behind an environment variable because it is verbose
# even for normal debugging-level output.
Chef::Log.debug("[Poise] Checking #{seg} in #{name}: #{file.inspect}") if ENV['POISE_DEBUG']
Poise.debug("[Poise] Checking #{seg} in #{name}: #{file.inspect}")
if file == filename
Chef::Log.debug("[Poise] Found matching #{seg} in #{name}: #{file.inspect}")
Poise.debug("[Poise] Found matching #{seg} in #{name}: #{file.inspect}")
possibles[file] = name
end
end
@@ -66,5 +66,112 @@ module Poise
# Sort the items by matching path length, pick the name attached to the longest.
possibles.sort_by{|key, value| key.length }.last[1]
end
# Try to find an ancestor to call a method on.
#
# @since 2.2.3
# @since 2.3.0
# Added ignore parameter.
# @param obj [Object] Self from the caller.
# @param msg [Symbol] Method to try to call.
# @param args [Array<Object>] Method arguments.
# @param default [Object] Default return value if no valid ancestor exists.
# @param ignore [Array<Object>] Return value to ignore when scanning ancesors.
# @return [Object]
# @example
# val = @val || Poise::Utils.ancestor_send(self, :val)
def ancestor_send(obj, msg, *args, default: nil, ignore: [default])
# Class is a subclass of Module, if we get something else use its class.
obj = obj.class unless obj.is_a?(Module)
ancestors = []
if obj.respond_to?(:superclass)
# Check the superclass first if present.
ancestors << obj.superclass
end
# Make sure we don't check obj itself.
ancestors.concat(obj.ancestors.drop(1))
ancestors.each do |mod|
if mod.respond_to?(msg)
val = mod.send(msg, *args)
# If we get the default back, assume we should keep trying.
return val unless ignore.include?(val)
end
end
# Nothing valid found, use the default.
default
end
# Create a helper to invoke a module with some parameters.
#
# @since 2.3.0
# @param mod [Module] The module to wrap.
# @param block [Proc] The module to implement to parameterization.
# @return [void]
# @example
# module MyMixin
# def self.my_mixin_name(name)
# # ...
# end
# end
#
# Poise::Utils.parameterized_module(MyMixin) do |name|
# my_mixin_name(name)
# end
def parameterized_module(mod, &block)
raise Poise::Error.new("Cannot parameterize an anonymous module") unless mod.name && !mod.name.empty?
parent_name_parts = mod.name.split(/::/)
# Grab the last piece which will be the method name.
mod_name = parent_name_parts.pop
# Find the enclosing module or class object.
parent = parent_name_parts.inject(Object) {|memo, name| memo.const_get(name) }
# Object is a special case since we need #define_method instead.
method_type = if parent == Object
:define_method
else
:define_singleton_method
end
# Scoping hack.
self_ = self
# Construct the method.
parent.send(method_type, mod_name) do |*args|
self_.send(:check_block_arity!, block, args)
# Create a new anonymous module to be returned from the method.
Module.new do
# Fake the name.
define_singleton_method(:name) do
super() || mod.name
end
# When the stub module gets included, activate our behaviors.
define_singleton_method(:included) do |klass|
super(klass)
klass.send(:include, mod)
klass.instance_exec(*args, &block)
end
end
end
end
private
# Check that the given arguments match the given block. This is needed
# because Ruby will nil-pad mismatched argspecs on blocks rather than error.
#
# @since 2.3.0
# @param block [Proc] Block to check.
# @param args [Array<Object>] Arguments to check.
# @return [void]
def check_block_arity!(block, args)
# Convert the block to a lambda-style proc. You can't make this shit up.
obj = Object.new
obj.define_singleton_method(:block, &block)
block = obj.method(:block).to_proc
# Check
required_args = block.arity < 0 ? ~block.arity : block.arity
if args.length < required_args || (block.arity >= 0 && args.length > block.arity)
raise ArgumentError.new("wrong number of arguments (#{args.length} for #{required_args}#{block.arity < 0 ? '+' : ''})")
end
end
end
end

View File

@@ -48,10 +48,10 @@ module Poise
# Cargo this .included to things which include us.
inner_klass.extend(mod)
# Dispatch to submodules, inner_klass is the most recent includer.
if inner_klass < Chef::Resource
if inner_klass < Chef::Resource || inner_klass.name.to_s.end_with?('::Resource')
# Use klass::Resource to look up relative to the original module.
inner_klass.class_exec { include klass::Resource }
elsif inner_klass < Chef::Provider
elsif inner_klass < Chef::Provider || inner_klass.name.to_s.end_with?('::Provider')
# As above, klass::Provider.
inner_klass.class_exec { include klass::Provider }
end

View File

@@ -0,0 +1,85 @@
#
# Copyright 2015, Noah Kantrowitz
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'etc'
require 'chef/mixin/shell_out'
module Poise
module Utils
# A mixin to provider a better shell_out.
#
# @since 2.5.0
# @example
# Poise::Utils::ShellOut.poise_shell_out('ruby myapp.rb', user: 'myuser')
module ShellOut
extend self
include Chef::Mixin::ShellOut
# An enhanced version of Chef's `shell_out` which sets some default
# parameters. If possible it will set $HOME, $USER, $LOGNAME, and the
# group to run as.
#
# @param command_args [Array] Command arguments to be passed to `shell_out`.
# @param options [Hash<Symbol, Object>] Options to be passed to `shell_out`,
# with modifications.
# @return [Mixlib::ShellOut]
def poise_shell_out(*command_args, **options)
# Allow the env option shorthand.
options[:environment] ||= {}
if options[:env]
options[:environment].update(options[:env])
options.delete(:env)
end
# Convert environment keys to strings to be safe.
options[:environment] = options[:environment].inject({}) do |memo, (key, value)|
memo[key.to_s] = value.to_s
memo
end
# Populate some standard environment variables.
ent = begin
if options[:user].is_a?(Integer)
Etc.getpwuid(options[:user])
elsif options[:user]
Etc.getpwnam(options[:user])
end
rescue ArgumentError
nil
end
username = ent ? ent.name : options[:name]
if username
options[:environment]['HOME'] ||= Dir.home(username)
options[:environment]['USER'] ||= username
# On the off chance they set one manually but not the other.
options[:environment]['LOGNAME'] ||= options[:environment]['USER']
end
# Set the default group on Unix.
options[:group] ||= ent.gid if ent
# Call Chef's shell_out wrapper.
shell_out(*command_args, **options)
end
# The `error!` version of {#poise_shell_out}.
#
# @see #poise_shell_out
# @return [Mixlib::ShellOut]
def poise_shell_out!(*command_args)
poise_shell_out(*command_args).tap(&:error!)
end
end
end
end

View File

@@ -16,5 +16,5 @@
module Poise
VERSION = '2.0.1'
VERSION = '2.6.0'
end

File diff suppressed because one or more lines are too long