6 Commits

Author SHA1 Message Date
Greg Karékinian
b550c1b79e Remove deleted servers 2023-06-29 16:58:28 +02:00
Greg Karékinian
1f29d8a01a Get rid of compat_resource and mariadb 2023-06-29 16:49:06 +02:00
Greg Karékinian
462bdabf01 Get rid of the chef-sugar dependency
It's now deprecated
2023-06-29 16:41:08 +02:00
Greg Karékinian
7683de09a2 Update the elasticsearch cookbook 2023-06-29 16:39:09 +02:00
Greg Karékinian
68ce3c4834 Update the firewall cookbook to the latest version
This gives us comments from the named resources
2023-06-29 15:08:44 +02:00
Greg Karékinian
916ae8094c Get rid of the build-essential cookbook
The build_essential resource has been part of Chef since 14.0
2023-06-29 14:48:49 +02:00
284 changed files with 4823 additions and 18474 deletions

View File

@@ -2,44 +2,38 @@
source 'https://supermarket.chef.io'
cookbook 'mediawiki',
git: 'https://github.com/67P/mediawiki-cookbook.git',
ref: 'nginx'
cookbook 'elasticsearch', '~> 5.1.3'
cookbook 'firewall', '~> 6.2.16'
cookbook 'redisio', '~> 6.4.1'
cookbook 'postfix', '= 5.0.2'
cookbook 'php', '~> 8.0.0'
cookbook 'composer', '~> 2.7.0'
cookbook 'users', '~> 5.3.1'
cookbook 'hostname', '= 0.4.2'
cookbook 'firewall', '~> 2.6.3'
cookbook 'nginx', '= 9.0.0'
cookbook 'fail2ban', '~> 7.0.4'
# Remove when cookbooks stop depending on it, the build_essential resource is
# part of Chef 14 (https://docs.chef.io/resource_build_essential.html)
cookbook 'build-essential', '~> 8.2.1'
cookbook 'mysql', '~> 8.7.3'
# cookbook 'postgresql', '= 7.1.8'
cookbook 'apt', '~> 7.3.0'
cookbook 'git', '~> 10.0.0'
cookbook 'hostsfile', '~> 3.0.1'
cookbook 'ohai', '~> 5.2.5'
cookbook 'nodejs', '~> 7.3.1'
cookbook 'timezone_iii', '= 1.0.4'
cookbook 'ark', '>= 5.0.0'
cookbook 'logrotate', '= 2.2.0'
cookbook 'openssl', '~> 8.5.5'
cookbook 'ntp', '= 3.4.0'
cookbook 'apache2', '= 3.3.0'
cookbook 'chef-sugar', '= 5.1.12'
cookbook 'compat_resource', '= 12.19.0'
cookbook 'homebrew', '= 3.0.0'
cookbook 'mariadb', '= 0.3.1'
cookbook 'ruby_build', '~> 2.5.0'
cookbook 'ipfs',
git: 'https://gitea.kosmos.org/kosmos/ipfs-cookbook.git',
ref: 'v0.7.0'
cookbook 'elasticsearch', '= 4.3.0'
cookbook 'java', '~> 4.3.0'
cookbook 'ulimit', '~> 1.0.0'
cookbook 'mediawiki',
git: 'https://github.com/67P/mediawiki-cookbook.git',
ref: 'nginx'
cookbook 'apache2', '= 3.3.0'
cookbook 'apt', '~> 7.3.0'
cookbook 'ark', '>= 5.0.0'
cookbook 'composer', '~> 2.7.0'
cookbook 'fail2ban', '~> 7.0.4'
cookbook 'git', '~> 10.0.0'
cookbook 'golang', '~> 5.3.1'
cookbook 'hostname', '= 0.4.2'
cookbook 'hostsfile', '~> 3.0.1'
cookbook 'java', '~> 4.3.0'
cookbook 'logrotate', '= 2.2.0'
cookbook 'mysql', '~> 8.7.3'
cookbook 'nginx', '= 9.0.0'
cookbook 'nodejs', '~> 7.3.1'
cookbook 'ntp', '= 3.4.0'
cookbook 'ohai', '~> 5.2.5'
cookbook 'openssl', '~> 8.5.5'
cookbook 'php', '~> 8.0.0'
cookbook 'postfix', '= 5.0.2'
cookbook 'timezone_iii', '= 1.0.4'
cookbook 'ulimit', '~> 1.0.0'
cookbook 'users', '~> 5.3.1'
cookbook 'zerotier', '~> 1.0.7'
cookbook 'ruby_build', '~> 2.5.0'

View File

@@ -2,16 +2,12 @@ DEPENDENCIES
apache2 (= 3.3.0)
apt (~> 7.3.0)
ark (>= 5.0.0)
build-essential (~> 8.2.1)
chef-sugar (= 5.1.12)
compat_resource (= 12.19.0)
composer (~> 2.7.0)
elasticsearch (= 4.3.0)
elasticsearch (~> 5.1.3)
fail2ban (~> 7.0.4)
firewall (~> 2.6.3)
firewall (~> 6.2.16)
git (~> 10.0.0)
golang (~> 5.3.1)
homebrew (= 3.0.0)
hostname (= 0.4.2)
hostsfile (~> 3.0.1)
ipfs
@@ -20,7 +16,6 @@ DEPENDENCIES
ref: v0.7.0
java (~> 4.3.0)
logrotate (= 2.2.0)
mariadb (= 0.3.1)
mediawiki
git: https://github.com/67P/mediawiki-cookbook.git
revision: 78641e53635ba6cbd4a2a51fd597adb8fef1e8ad
@@ -48,26 +43,20 @@ GRAPH
build-essential (8.2.1)
mingw (>= 1.1)
seven_zip (>= 0.0.0)
chef-sugar (5.1.12)
chocolatey (3.0.0)
compat_resource (12.19.0)
composer (2.7.0)
apt (>= 0.0.0)
php (>= 0.0.0)
windows (>= 0.0.0)
elasticsearch (4.3.0)
apt (>= 0.0.0)
elasticsearch (5.1.3)
ark (>= 0.0.0)
chef-sugar (>= 0.0.0)
yum (>= 0.0.0)
fail2ban (7.0.4)
yum-epel (>= 0.0.0)
firewall (2.6.5)
chef-sugar (>= 0.0.0)
firewall (6.2.16)
git (10.0.0)
golang (5.3.1)
ark (>= 6.0)
homebrew (3.0.0)
homebrew (5.4.1)
hostname (0.4.2)
hostsfile (>= 0.0.0)
hostsfile (3.0.1)
@@ -77,15 +66,11 @@ GRAPH
homebrew (>= 0.0.0)
windows (>= 0.0.0)
logrotate (2.2.0)
mariadb (0.3.1)
apt (>= 0.0.0)
yum (>= 0.0.0)
yum-epel (>= 0.0.0)
mediawiki (0.5.0)
apache2 (>= 0.0.0)
nginx (>= 0.0.0)
php (>= 0.0.0)
mingw (2.1.3)
mingw (2.1.7)
seven_zip (>= 0.0.0)
mysql (8.7.4)
nginx (9.0.0)
@@ -112,7 +97,6 @@ GRAPH
ulimit (1.0.0)
users (5.3.1)
windows (7.0.2)
yum (7.2.0)
yum-epel (4.2.3)
zerotier (1.0.7)
ohai (>= 0.0.0)

View File

@@ -1,26 +0,0 @@
*~
*#
.#*
\#*#
.*.sw[a-z]
*.un~
*.tmp
*.bk
*.bkup
.kitchen.local.yml
Berksfile.lock
Gemfile.lock
.bundle/
.cache/
.kitchen/
.vagrant/
.vagrant.d/
.yardoc/
bin/
coverage/
doc/
pkg/
tmp/
vendor/
.rspec

View File

@@ -1,16 +0,0 @@
driver:
name: vagrant
provisioner:
name: chef_zero
deprecations_as_errors: true
platforms:
- name: centos-6
- name: centos-7
- name: ubuntu-16.04
- name: ubuntu-18.04
suites:
- name: default
run_list: chef-sugar::default

View File

@@ -1,309 +0,0 @@
# Chef Sugar Changelog
This file is used to list changes made in each version of the chef-sugar cookbook and gem.
<!-- latest_release -->
<!-- latest_release -->
<!-- release_rollup -->
<!-- release_rollup -->
<!-- latest_stable_release -->
## [v5.1.12](https://github.com/chef/chef-sugar/tree/v5.1.12) (2020-11-11)
#### Merged Pull Requests
- Don&#39;t define which helper on Chef 16+ to avoid conflicts [#21](https://github.com/chef/chef-sugar/pull/21) ([tas50](https://github.com/tas50))
<!-- latest_stable_release -->
## [v5.1.11](https://github.com/chef/chef-sugar/tree/v5.1.11) (2020-08-14)
#### Merged Pull Requests
- Fix Ruby 2.3 tests [#19](https://github.com/chef/chef-sugar/pull/19) ([tas50](https://github.com/tas50))
- Only require libs if we haven&#39;t already loaded them [#20](https://github.com/chef/chef-sugar/pull/20) ([tas50](https://github.com/tas50))
## [v5.1.9](https://github.com/chef/chef-sugar/tree/v5.1.9) (2019-11-13)
#### Merged Pull Requests
- Don&#39;t fail if Chef::VERSION isn&#39;t defined [#18](https://github.com/chef/chef-sugar/pull/18) ([lamont-granquist](https://github.com/lamont-granquist))
## [v5.1.8](https://github.com/chef/chef-sugar/tree/v5.1.8) (2019-11-13)
#### Merged Pull Requests
- Wire up Expeditor and support both chef-sugar and chef-sugar-ng [#8](https://github.com/chef/chef-sugar/pull/8) ([tas50](https://github.com/tas50))
- Add github templates and a code of conduct [#9](https://github.com/chef/chef-sugar/pull/9) ([tas50](https://github.com/tas50))
- Beginning of chef-sugar deprecation [#10](https://github.com/chef/chef-sugar/pull/10) ([lamont-granquist](https://github.com/lamont-granquist))
- Use Expeditor to set the version in the metadata.rb file [#11](https://github.com/chef/chef-sugar/pull/11) ([tas50](https://github.com/tas50))
- Switch gemfile back to chef-sugar [#12](https://github.com/chef/chef-sugar/pull/12) ([tas50](https://github.com/tas50))
- Fix metadata.rb version updatig logic and use SPDX compliant license strings [#14](https://github.com/chef/chef-sugar/pull/14) ([tas50](https://github.com/tas50))
- Additional Chef-15 greenification [#13](https://github.com/chef/chef-sugar/pull/13) ([lamont-granquist](https://github.com/lamont-granquist))
- Move test deps to the Gemfile [#15](https://github.com/chef/chef-sugar/pull/15) ([tas50](https://github.com/tas50))
- Get the tests green [#17](https://github.com/chef/chef-sugar/pull/17) ([tas50](https://github.com/tas50))
- Deprecate chef-sugar node API [#16](https://github.com/chef/chef-sugar/pull/16) ([lamont-granquist](https://github.com/lamont-granquist))
## v5.0.1 (2019-03-13)
- Modifies the behavior of `systemd?` so that it works equally well on physical/virtual
machines as well as within containers.
## v5.0.0 (2018-12-26)
- BREAKING CHANGE: Require Chef 13 or later
- Trim out test files and the cookbook from the gem artifact to slim install size
## v4.2.1 (2018-12-06)
- Repackaged with an older stove to remove the metadata.rb on the Supermarket for older chef-client releases
## v4.2.0 (2018-12-05)
- Added a new parallels? helper
- Added support for the Raspberry Pi 1 and Zero to armhf? helper
- Added a centos_final? helper
## v4.1.0 (2018-08-16)
- Improve the detection of linux hosts with the linux? helper. Amazon Linux and obscure distros will now be properly detected.
## v4.0.1 (2018-08-09)
- Add new Debian, Mint, macOS codenames
- Add new Ubuntu codenames: artful, bionic, cosmic
## v4.0.0 (2018-01-26)
- Require Ruby 2.2 or later and Chef 12.10 or later
- Cookbook now installs the chef-sugar gem via a metadata installation so chef-sugar::default on your runlist is no longer needed
- Added additional metadata to the cookbook: supports, issue_url, source_url, chef_version.
- Requirements improved in the readme
## v3.6.0 (2017-10-26)
- Add Ubuntu zesty and debian stretch detection
- Add softlayer? helper
- Add aarch64? helper
## v3.5.0 (2016-07-12)
- Improve the systemd check to not fail on older kernels or Windows hosts
- Add detection of macOS 10.11 and 10.12
## v3.4.0 (2016-07-18)
### Improvements
- Add `virtual?` and `physical?` methods
- Add Scaleway C1 server (arm arch) support
- Add IMB s390x support
- Add missing Ubuntu release names
### Bug Fixes
- Drop Ruby 2.0.0 support from Travis test matrix
- Pin to Rack 1.6 (dev dep)
## v3.3.0 (2016-01-11)
### Improvements
- Break up `Chef::Sugar::Constraints` into a class and a dsl file
- Add `platform_version` method with full constraints comparison support
## v3.2.0 (2015-12-10)
### Improvements
- Add platform matchers for `debian` and `fedora`
- Add `openvz` support under virtualization
- Add init system detection support
- Add support for `nexus`, `ios_xr` platforms and `wrlinux` platform_family
- Add additional `aix` helpers
### Bug Fixes
- Properly expose `Architecture#i386?` in the DSL
## v3.1.1 (2015-06-23)
### Improvements
- Update Intel CPU types based on existing Fauxhai data
- Update SPARC logic and 32/64-bit logic for x86 and i386
### Bug Fixes
- Fix 32-bit logic
- Fix default behavior to include chef-sugar at compile time
- Fix Chef 12.1.0 warnings for chef_gem compile time install
- Fix `redhat_enterprise_linux?` matcher
## v3.0.2 (2015-03-26)
### Improvements
- Add helpers for `ppc64` and `ppc64le` architecture
### Bug Fixes
- Adjustments to error message
## v3.0.1 (2015-03-20)
### Breaking Changes
- Rename `compile_time` `to at_compile_time` - if your recipes are affected by this breaking change, your Chef Client run will produce a verbose error message with details on how to fix the error.
## v3.0.0 (2015-03-17)
### Breaking Changes
- Drop support for Ruby 1.9 (it might still work, but it is no longer officially supported)
### Improvements
- Remove accidentially committed gem source
- Bump development dependencies
- Add `digitalocean?` matcher
- Expose the `rhel` platform as `el`
- Add `ppc64le` platform
- Add helper for determining if architecture is SPARC
- Add helper for determining if architecture is Intel
- Add dynamic platform/version matchers for Solaris
### Bug Fixes
- Reset namespace_options when reaching top-level resources
## v2.5.0 (2015-01-05)
### Improvements
- Add `data_bag_item_for_environment` function
- Add `kvm?` matcher
- Add `virtualbox?` matcher
### Bug Fixes
- Use `.key?` to check for hash key presence, raising an `AttributeDoesNotExist` error sooner
## v2.4.1 (2014-10-12)
- No changes from v2.4.0 - forced a new version upload to the Chef Supermarket
## v2.4.0 (2014-10-12)
### Improvements
- Add `docker?` matcher
## v2.3.2 (2014-10-07)
### Big Fixues
- Include `amd64` in `_64_bit?` check
## v2.3.1 (2014-10-07)
### Improvements
- Check all 64-bit architectures that may be reported by Ohai
### Bug Fixes
- Be more tolerant of `nil` values return from sub functions
- Check to make sure `node['domain']` is not `nil` before calling `#include?`
## v2.3.0 (2014-09-24)
### Improvements
- Add `vmware?` matcher
- Allow the attribute DSL to access parent attributes
### Bug Fixes
- Return `true` or `false` from all Boolean methods (instead of `nil` or truthy values)
## v2.2.0 (2014-08-20)
### Improvements
- Add `smartos?` matcher
- Add `omnios?` matcher
## v2.1.0 (2014-06-26)
### Improvements
- Add `solaris2?` matcher
- Add `aix?` matcher
- Add 'lxc?' matcher
### Bug Fixes
- Fix a bug in namespace memoization during attribute initialization
## v2.0.0 (2014-06-16)
### Breaking
- Remove `not_linux?` method
- Remove `not_windows?` method
### Improvements
- Miscellaneous spelling fixes
- Update a failing unit test for `installed?`
- Add Mac OS X to the list of platforms (Yosemite)
- Upgrade to RSpec 3
- Fix `which` (and `installed?` and `installed_at_version?`) when given an absolute path
- Fix `linux?` check to only return true on real linuxes
## v1.3.0 (2014-05-05)
- Check both `$stdout` and `$stderr` in `version_for`
- Add additional platform versions
- Make `includes_recipe?` a top-level API (instead of just Node)
- Match on the highest version number instead of direct equality checking on platform versions
- Define `Object#blank?` as a core extension
- Define `String#flush` as a core extension
- Remove Stove
## v1.2.6 (2014-03-16)
- Fix a bug in `vagrant?` returning false on newer Vagrant versions
- Remove Coveralls
## v1.2.4 (2014-03-13)
- See (1.2.2), but I botched the release
## v1.2.2 (2014-03-13)
- Fix a critical bug with `encrypted_data_bag_item` using the wrong key
## v1.2.0 (2014-03-09)
- Add `namespace` functionality for specifying attributes in a DSL
- Add constraints helpers for comparing version strings
- Add `require_chef_gem` to safely require and degrade if a gem is not installed
- Add `deep_fetch` and `deep_fetch!` to fetch deeply nested keys
- Accept an optional secret key in `encrypted_data_bag_item` helper and raise a helpful error if one is not set (NOTE: this changes the airity of the method, but it's backward-compatible because Ruby is magic)
- Add Stove for releasing
- Updated copyrights for 2014
## v1.1.0 (2013-12-10)
- Add `cloudstack?` helper
- Add data bag helpers
- Remove foodcritic checks
- Upgrade development gem versions
- Randomize spec order
## v1.0.1 (2013-10-15)
- Add development recipe
- Add `compile_time`, `before`, and `after` filters
## v1.0.0 (2013-10-15)
- First public release

View File

@@ -1 +0,0 @@
Please refer to the Chef Community Code of Conduct at https://www.chef.io/code-of-conduct/

View File

@@ -1,20 +0,0 @@
Contributing to Chef Sugar
===============================
The process for contributing to Chef sugar is rather straight-forward. It is unlikely that you'll need to modify the actual Chef recipe, so it's assumed that you want to work on the Gem itself.
1. Fork the repository on GitHub.
2. Clone your fork.
3. Create a new, semantically-named branch:
$ git checkout -b my_feature_branch
4. Make any changes, ensuring you write adequate test coverage.
5. Document your changes (YARD).
6. Run the tests (make sure they pass).
7. Submit a Pull Request on GitHub.
8. (optional) Ping me on Twitter (@sethvargo)
Additionally, please **DO NOT**:
- Modify the version of the cookbook or gem.
- Update the CHANGELOG
- Make unnecessary changes to the gemspec

View File

@@ -1,84 +0,0 @@
### Chef Sugar is being deprecated, this is the internal list of the TODO tasks
TASKS in order:
* ~~pull cloud.rb into core-chef~~
* pull data_bag.rb into core-chef
* ~~pull run_context.rb into core-chef~~
* ~~pull vagrant.rb into core-chef~~
* ~~pull virtualization.rb into core-chef~~
* deprecate ip.rb with no replacement (although maybe a new ohai attribute?)
* deprecate kernel.rb with no replacement
* ~~deprecate node.rb with no replacement~~
* deprecate ruby.rb with no replacement
* determine what to do about filters.rb
* determine what to do about remaining platform.rb
* determine what to do about shell.rb
* determine what to do about core_extensions
NOTES on files:
architecture.rb is COMPLETED
cloud.rb is COMPLETED
constraint.rb / constraint_dsl.rb tasks:
* replace with Chef::VersionString objects
core_extensions
* pile of monkeypatches that makes my eyes twitch a little bit. how much do we want to become activerecord? counter-argument is
that some activerecord-ish helpers are SUUUPER useful. but we should probably copy them from activerecord since those are more
likely to get pulled directly into core-chef.
data_bag
* we should pull this into core-chef or something comparable (TBD)
docker.rb is COMPLETED
filters.rb tasks
* incorporate the before/after syntax into the find_resource/edit_resource API (probably renamed, with deprecation done here)
* deprecate the at_compile_time helper in favor of moving the `compile_time true` property into Chef::Resource directly
init.rb is COMPLETED
* unless we get user complaints, runit is dead to us and this is done
ip.rb
* needs to be deprecated with no replacement (could push this into another ohai attribute -- or have we done it already?)
kernel.rb (the require_chef_gem trivial helper)
* needs to be deprecated with no replacement.
kitchen.rb is COMPLETED
node.rb (the method_missing syntax)
* needs to be deprecated with no replacement.
platform.rb tasks:
* decide what to do about the `debian_before_squeeze` platform version helpers.
* decide what to do about the `platform_version` helper (can we wire this up to a Chef::VersionString object instead?)
platform_family.rb is COMPLETED
ruby.rb tasks:
* needs to be deprecated with no replacement (nobody has used it since ruby 2.0, so its clearly not being used)
run_context.rb is COMPLETED
shell.rb: (collection of helpers including `which`)
* TBD
vagrant.rb is COMPLETED
virtualization.rb is COMPLETED

View File

@@ -1,34 +0,0 @@
source "https://rubygems.org"
gemspec name: "chef-sugar"
group :debug do
gem "pry"
gem "pry-byebug" unless Gem::Version.new(RUBY_VERSION) < Gem::Version.new("2.4")
gem "pry-stack_explorer", "~> 0.4.0" # pin until we drop ruby < 2.6
end
group :test do
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new("2.5")
gem "chefspec", "~> 7.4.0" # supports Chef 13+ aka ruby 2.3+
gem "chef", "~> 13" # also needed to support Ruby 2.3
elsif Gem::Version.new(RUBY_VERSION) < Gem::Version.new("2.6")
gem "chefspec"
gem "chef-zero", "~> 14"
gem "chef", "~> 15" # also needed to support Ruby 2.3
else
gem "chefspec"
end
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new("2.4")
gem "rubyzip", "< 2"
else
gem "rubyzip"
end
gem "rake"
gem "rspec"
end
group :kitchen do
gem "kitchen-vagrant"
gem "license-acceptance", "~> 1.0" if Gem::Version.new(RUBY_VERSION) < Gem::Version.new("2.4")
gem "test-kitchen"
end

View File

@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2013-2015 Seth Vargo
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.

View File

@@ -1,546 +0,0 @@
# Chef Sugar
[![Gem Version](http://img.shields.io/gem/v/chef-sugar.svg?style=flat-square)][gem]
[![Build status](https://badge.buildkite.com/f44140e4898b4935bfc3bba523efc2a7592d7c9a1bae3faf5c.svg?branch=master)](https://buildkite.com/chef-oss/chef-chef-sugar-master-verify)
# CHEF SUGAR DEPRECATION WARNING
Chef Sugar is in the process of being migrated into Chef Infra Client 15 and Chef Infra Client 16. The bulk of that work has already
been completed. After it is completed there will be no need for this cookbook and gem, and it will no longer be supported. No
issues or patches are being accepted at this time.
The final major version release of Chef Sugar will raise and will not be functional. Users on Chef Infra Client <= 14 or old versions of 15
will need to have a pessimistic pin on chef-sugar, or simply upgrade.
## Requirements
### Platforms
- any platform
### Chef
- Chef 13.0+
### Cookbooks
- none
## Installation
If you want to develop/hack on chef-sugar, please see the CONTRIBUTING.md.
If you are using Berkshelf, add `chef-sugar` to your `Berksfile`:
```ruby
cookbook 'chef-sugar'
```
Otherwise, you can use `knife` or download the tarball directly from the community site:
```ruby
knife cookbook site install chef-sugar
```
## Usage
Simply depend on this cookbook in the metadata of your cookbook and the gem will be installed and required..
Requiring the Chef Sugar Gem will automatically extend the Recipe DSL, `Chef::Resource`, and `Chef::Provider` with helpful convenience methods.
### Module Method
If you are working outside of the Recipe DSL, you can use the module methods instead of the Recipe DSL. In general, the module methods have the same name as their Recipe-DSL counterparts, but require the node object as a parameter. For example:
In a Recipe:
```ruby
# cookbook/recipes/default.rb
do_something if windows?
```
In a Library as a singleton:
```ruby
# cookbook/libraries/default.rb
def only_on_windows(&block)
yield if Chef::Sugar::PlatformFamily.windows?(@node)
end
```
In a Library as a Mixin:
```ruby
# cookbook/libraries/default.rb
include Chef::Sugar::PlatformFamily
def only_on_windows(&block)
yield if windows?(@node)
end
```
## API
**Note:** For the most extensive API documentation, please see the YARD documentation.
### Architecture
**Note:** Some of the architecture commands begin with an underscore (`_`) because Ruby does not permit methods to start with a numeric.
- `_64_bit?`
- `_32_bit?`
- `intel?`
- `sparc?`
- `ppc64?`
- `ppc64le?`
- `powerpc?`
#### Examples
```ruby
execute 'build[my binary]' do
command '...'
not_if { _64_bit? }
end
```
### Cloud
- `azure?`
- `cloud?`
- `digitalocean?`
- `ec2?`
- `eucalyptus?`
- `gce?`
- `linode?`
- `openstack?`
- `cloudstack?`
- `rackspace?`
- `softlayer?`
#### Examples
```ruby
template '/tmp/config' do
variables(
# See also: best_ip_for
ipaddress: cloud? ? node['local_ipv4'] : node['public_ipv4']
)
end
```
### Core Extensions
**Note:** Core extensions are **not** included by default. You must require the `chef/sugar/core_extensions` module manually to gain access to these APIs:
```ruby
require 'chef/sugar/core_extensions'
```
- `String#satisfies?`
- `String#satisfied_by?`
- `Array#satisfied_by?`
- `Object#blank?`
#### Examples
```ruby
# Checking version constraints
'1.0.0'.satisfies?('~> 1.0') #=> true
'~> 1.0'.satisfied_by?('1.0') #=> true
```
```ruby
# Check for an object's presence
''.blank? #=> true
['hello'].blank? #=> false
```
### Data Bag
- `encrypted_data_bag_item` - a handy DSL method for loading encrypted data bag items the same way you load a regular data bag item; this requires `Chef::Config[:encrypted_data_bag_secret]` is set!
- `encrypted_data_bag_item_for_environment` - find the encrypted data bag entry for the current node's Chef environment.
- `data_bag_item_for_environment` - find the data bag entry for the current node's Chef environment.
#### Examples
```ruby
encrypted_data_bag_item('accounts', 'hipchat')
```
```ruby
encrypted_data_bag_item_for_environment('accounts', 'github')
```
```ruby
data_bag_item_for_environment('accounts', 'github')
```
### Docker
Chef Sugar looks for hints to see if the node being converged is a Docker container. When [Ohai supports checking other nodes](https://github.com/opscode/ohai/pull/428), Chef Sugar will automatically pick up the information.
- `docker?`
#### Examples
```ruby
template '/runme' do
only_if { docker?(node) }
end
```
### Attributes
Chef Sugar adds more Chef-like DSL to attribute definitions. Instead of using the Ruby hash syntax, you can define attributes using nested namespaces. This DSL may be more friendly to non-Ruby developers. It can safely be mixed-and-matched with the standard syntax.
```ruby
# This is functionally the same as default['apache2']['config']['root'] = '/var/www'
namespace 'apache2' do
namespace 'config' do
root '/var/www'
end
end
```
```ruby
# Specify multiple keys instead of nesting namespaces
namespace 'apache2', 'config' do
root '/var/www'
end
```
```ruby
# Specify different nested precedence levels
namespace 'apache2', precedence: normal do
namespace 'config', precedence: override do
root '/var/www' #=> override['apache2']['config']['root'] = '/var/www'
end
end
```
### Constraints
- `constraints` - create a new constraint (or requirement) that can be used to test version validations.
- `chef_version` - (DSL only) a wrapper for `version(Chef::VERSION)`
- `version` - create a new version that can be used to test constraint validation.
#### Examples
```ruby
# Check if a version is satisfied by a constraint
version('1.2.3').satisfies?('~> 1.2.0')
```
```ruby
# Check if a constraint is satisfied by a version
constraint('~> 1.2.0').satisfied_by?('1.2.3')
```
```ruby
# Support multiple constraints
version('1.2.3').satisfies?('> 1.2', '< 2.0')
constraint('> 1.2', '< 2.0').satisfied_by?('1.2.3')
```
```ruby
# Only perform an operation if Chef is at a certain version
package 'apache2' do
not_if { chef_version.satisfies?('~> 11.0') } # Ignore Chef 11
end
```
### Kernel
- `require_chef_gem` - "safely" require a gem. Loading a gem with Chef is sometimes difficult and confusing. The errors that Chef produces are also sometimes not very intuitive. In the event you require a gem to exist on the system, you can use `require_chef_gem`, which will attempt to require the gem and then produce helpful output if the gem is not installed:
```
Chef could not load the gem `#{name}'! You may need to install the gem
manually with `gem install #{name}', or include a recipe before you can
use this resource. Please consult the documentation for this cookbook
for proper usage.
```
#### Examples
```ruby
# LWRP
require_chef_gem 'pry'
```
```ruby
class Chef
class Provider
class MyProvider > Provider
require_chef_gem 'pry'
end
end
end
```
### Init
- `systemd?` - detect if init system is systemd
- `upstart?` - detect if init system is upstart
- `runit?` - detect if init system is runit
#### Examples
```ruby
systemd_service 'my-service' do
description 'My Service'
install do
wanted_by 'multi-user.target'
end
service do
exec_start '/usr/bin/myserviced'
end
action [:create, :enable, :start]
only_if { systemd? }
end
cookbook_file '/etc/init/my-service.conf' do
source 'my-service.conf'
only_if { upstart? }
end
```
### IP
- `best_ip_for` - determine the best IP address for the given "other" node, preferring local IP addresses over public ones.
#### Examples
```ruby
redis = search('node', 'role:redis').first
template '/tmp/config' do
variables(
ipaddress: best_ip_for(redis)
)
end
```
### Node
Additional methods for the `node` object
- `deep_fetch` - safely fetch a nested attribute.
- `deep_fetch!` - fetch a nested attribute, raising a more semantic error if the key does not exist.
- `in?` - determine if the node is in the given Chef environment.
#### Examples
```ruby
credentials = if node.in?('production')
Chef::EncryptedDataBag.new('...')
else
data_bag('...')
end
```
```ruby
node.deep_fetch('apache2', 'config', 'root') => node['apache2']['config']['root']
```
### Platform
- `amazon_linux?`
- `centos?`
- `linux_mint?`
- `oracle_linux?`
- `redhat_enterprise_linux?`
- `scientific_linux?`
- `ubuntu?`
- `solaris2?`
- `aix?`
- `smartos?`
- `omnios?`
- `raspbian?`
- `nexus?`
- `ios_xr?`
There are also a series of dynamically defined matchers that map named operating system release versions and comparison operators in the form "#{platform}_#{operator}_#{name}?". For example:
- `debian_after_squeeze?`
- `linuxmint_after_or_at_olivia?`
- `mac_os_x_lion?`
- `centos_final?`
- `ubuntu_before_lucid?`
- `ubuntu_before_or_at_maverick?`
- `solaris_10?`
- `solaris_11?`
To get a full list, run the following in IRB:
```ruby
require 'chef/sugar'
puts Chef::Sugar::Platform.instance_methods
```
#### Examples
```ruby
if ubuntu?
execute 'apt-get update'
end
```
### Platform Family
- `arch_linux?`
- `debian?`
- `fedora?`
- `freebsd?`
- `gentoo?`
- `linux?`
- `mac_os_x?`
- `openbsd?`
- `rhel?`
- `slackware?`
- `suse?`
- `windows?`
- `wrlinux?`
#### Examples
```ruby
node['attribute'] = if windows?
'C:\Foo\BarDrive'
else
'/foo/bar_drive'
end
```
### Ruby
**Note:** The applies to the Ruby found at `node['languages']['ruby']`.
- `ruby_20?`
- `ruby_19?`
#### Examples
```ruby
log 'This has been known to fail on Ruby 2.0' if ruby_20?
```
### Run Context
- `includes_recipe?` - determines if the current run context includes the recipe
```ruby
if includes_recipe?('apache2::default')
apache_module 'my_module' do
# ...
end
end
```
### Shell
- `which`
- `dev_null`
- `installed?`
- `installed_at_version?`
- `version_for`
#### Examples
```ruby
log "Using `mongo` at `#{which('mongo')}`"
if installed?('apt')
execute 'apt-get update'
end
execute 'install[thing]' do
command "... 2>&1 #{dev_null}"
not_if { installed_at_version?('thing', node['thing']['version']) }
end
log "Skipping git install, version is at #{version_for('mongo', '-v')}"
```
### Vagrant
- `vagrant?`
#### Examples
```ruby
http_request 'http://...' do
not_if { vagrant? }
end
```
### Virtualization
- `kvm?`
- `lxc?`
- `parallels?`
- `virtualbox?`
- `vmware?`
- `openvz?`
#### Examples
```ruby
service 'ntpd' do
action [:enable, :start]
not_if { lxc? }
end
```
### Filters
- `at_compile_time` - accepts a block of resources to run at compile time
- `before` - insert resource in the collection before the given resource
- `after` - insert resource in the collection after the given resource
#### Examples
```ruby
at_compile_time do
package 'apache2'
end
# This is equivalent to
package 'apache2' do
action :nothing
end.run_action(:install)
```
```ruby
before 'service[apache2]' do
log 'I am before the apache 2 service fires!'
end
```
```ruby
after 'service[apache2]' do
log 'I am after the apache 2 service fires!'
end
```
## License & Authors
- Author: Seth Vargo (sethvargo@gmail.com)
```text
Copyright 2013-2015 Seth Vargo
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.
```
[gem]: https://rubygems.org/gems/chef-sugar

View File

@@ -1,9 +0,0 @@
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new do |t|
t.rspec_opts = [
'--color',
'--format progress',
].join(' ')
end
task default: :spec

View File

@@ -1 +0,0 @@
5.1.12

View File

@@ -1,24 +0,0 @@
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'chef/sugar/version'
Gem::Specification.new do |spec|
spec.name = 'chef-sugar-ng'
spec.version = Chef::Sugar::VERSION
spec.authors = ['Seth Vargo']
spec.email = ['sethvargo@gmail.com']
spec.description = 'A series of helpful sugar of the Chef core and ' \
'other resources to make a cleaner, more lean recipe ' \
'DSL, enforce DRY principles, and make writing Chef ' \
'recipes an awesome experience!'
spec.summary = 'A collection of helper methods and modules that ' \
'make working with Chef recipes awesome.'
spec.homepage = 'https://github.com/chef/chef-sugar'
spec.license = 'Apache-2.0'
spec.required_ruby_version = '>= 2.3'
spec.files = %w{LICENSE} + Dir.glob("lib/**/*", File::FNM_DOTMATCH).reject { |f| File.directory?(f) }
spec.require_paths = ['lib']
end

View File

@@ -1,24 +0,0 @@
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'chef/sugar/version'
Gem::Specification.new do |spec|
spec.name = 'chef-sugar'
spec.version = Chef::Sugar::VERSION
spec.authors = ['Seth Vargo']
spec.email = ['sethvargo@gmail.com']
spec.description = 'A series of helpful sugar of the Chef core and ' \
'other resources to make a cleaner, more lean recipe ' \
'DSL, enforce DRY principles, and make writing Chef ' \
'recipes an awesome experience!'
spec.summary = 'A collection of helper methods and modules that ' \
'make working with Chef recipes awesome.'
spec.homepage = 'https://github.com/chef/chef-sugar'
spec.license = 'Apache-2.0'
spec.required_ruby_version = '>= 2.3'
spec.files = %w{LICENSE} + Dir.glob("lib/**/*", File::FNM_DOTMATCH).reject { |f| File.directory?(f) }
spec.require_paths = ['lib']
end

View File

@@ -1,51 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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 'chef/recipe'
require 'chef/resource'
require 'chef/provider'
class Chef
module Sugar
require_relative 'sugar/architecture'
require_relative 'sugar/cloud'
require_relative 'sugar/constraints'
require_relative 'sugar/constraints_dsl'
require_relative 'sugar/data_bag'
require_relative 'sugar/docker'
require_relative 'sugar/filters'
require_relative 'sugar/init'
require_relative 'sugar/ip'
require_relative 'sugar/kernel'
require_relative 'sugar/kitchen'
require_relative 'sugar/node'
require_relative 'sugar/platform'
require_relative 'sugar/platform_family'
require_relative 'sugar/ruby'
require_relative 'sugar/run_context'
require_relative 'sugar/shell'
require_relative 'sugar/vagrant'
require_relative 'sugar/version'
require_relative 'sugar/virtualization'
end
end
Chef::Recipe.send(:include, Chef::Sugar::DSL)
Chef::Recipe.send(:include, Chef::Sugar::RecipeDSL) # TODO: this is a hack
Chef::Resource.send(:include, Chef::Sugar::DSL)
Chef::Provider.send(:include, Chef::Sugar::DSL)
Object.send(:include, Chef::Sugar::Kernel)

View File

@@ -1,176 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module Architecture
extend self
# these helpers have been moved to core-chef
if !defined?(Chef::VERSION) || Gem::Requirement.new("< 15.4.70").satisfied_by?(Gem::Version.new(Chef::VERSION))
#
# Determine if the current architecture is 64-bit
#
# @return [Boolean]
#
def _64_bit?(node)
%w(amd64 x86_64 ppc64 ppc64le s390x ia64 sparc64 aarch64 arch64 arm64 sun4v sun4u s390x)
.include?(node['kernel']['machine']) || ( node['kernel']['bits'] == '64' )
end
#
# Determine if the current architecture is 32-bit
#
# @todo Make this more than "not 64-bit"
#
# @return [Boolean]
#
def _32_bit?(node)
!_64_bit?(node)
end
#
# Determine if the current architecture is i386
#
# @return [Boolean]
#
def i386?(node)
_32_bit?(node) && intel?(node)
end
#
# Determine if the current architecture is Intel.
#
# @return [Boolean]
#
def intel?(node)
%w(i86pc i386 x86_64 amd64 i686)
.include?(node['kernel']['machine'])
end
#
# Determine if the current architecture is SPARC.
#
# @return [Boolean]
#
def sparc?(node)
%w(sun4u sun4v)
.include?(node['kernel']['machine'])
end
#
# Determine if the current architecture is Powerpc64 Big Endian
#
# @return [Boolean]
#
def ppc64?(node)
%w(ppc64)
.include?(node['kernel']['machine'])
end
#
# Determine if the current architecture is Powerpc64 Little Endian
#
# @return [Boolean]
#
def ppc64le?(node)
%w(ppc64le)
.include?(node['kernel']['machine'])
end
#
# Determine if the current architecture is PowerPC
#
# @return [Boolean]
#
def powerpc?(node)
%w(powerpc)
.include?(node['kernel']['machine'])
end
#
# Determine if the current architecture is ARM with Hard Float
#
# @return [Boolean]
#
def armhf?(node)
# Add more arm variants as needed here
%w(armv6l armv7l)
.include?(node['kernel']['machine'])
end
#
# Determine if the current architecture is AArch64
#
# @return [Boolean]
#
def aarch64?(node)
# Add more arm variants as needed here
%w(aarch64)
.include?(node['kernel']['machine'])
end
#
# Determine if the current architecture is s390x
#
# @return [Boolean]
#
def s390x?(node)
%w(s390x)
.include?(node['kernel']['machine'])
end
end
end
module DSL
if !defined?(Chef::VERSION) || Gem::Requirement.new("< 15.4.70").satisfied_by?(Gem::Version.new(Chef::VERSION))
# @see Chef::Sugar::Architecture#_64_bit?
def _64_bit?; Chef::Sugar::Architecture._64_bit?(node); end
# @see Chef::Sugar::Architecture#_32_bit?
def _32_bit?; Chef::Sugar::Architecture._32_bit?(node); end
# @see Chef::Sugar::Architecture#intel?
def i386?; Chef::Sugar::Architecture.i386?(node); end
# @see Chef::Sugar::Architecture#intel?
def intel?; Chef::Sugar::Architecture.intel?(node); end
# @see Chef::Sugar::Architecture#sparc?
def sparc?; Chef::Sugar::Architecture.sparc?(node); end
# @see Chef::Sugar::Architecture#ppc64?
def ppc64?; Chef::Sugar::Architecture.ppc64?(node); end
# @see Chef::Sugar::Architecture#ppc64le?
def ppc64le?; Chef::Sugar::Architecture.ppc64le?(node); end
# @see Chef::Sugar::Architecture#powerpc?
def powerpc?; Chef::Sugar::Architecture.powerpc?(node); end
# @see Chef::Sugar::Architecture#arm?
def armhf?; Chef::Sugar::Architecture.armhf?(node); end
# @see Chef::Sugar::Architecture#aarch64?
def aarch64?; Chef::Sugar::Architecture.aarch64?(node); end
# @see Chef::Sugar::Architecture#s390x?
def s390x?; Chef::Sugar::Architecture.s390x?(node); end
end
end
end
end

View File

@@ -1,192 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module Cloud
extend self
#
# Return true if the current current node is in "the cloud".
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def cloud?(node)
node.key?('cloud')
end
#
# Return true if the current current node is in EC2
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def ec2?(node)
node.key?('ec2')
end
#
# Return true if the current current node is in GCE
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def gce?(node)
node.key?('gce')
end
#
# Return true if the current current node is in Rackspace
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def rackspace?(node)
node.key?('rackspace')
end
#
# Return true if the current current node is in Eucalyptus
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def eucalyptus?(node)
node.key?('eucalyptus')
end
alias_method :euca?, :eucalyptus?
#
# Return true if the current current node is in Linode
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def linode?(node)
node.key?('linode')
end
#
# Return true if the current current node is in Openstack
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def openstack?(node)
node.key?('openstack')
end
#
# Return true if the current current node is in Cloudstack
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def cloudstack?(node)
node.key?('cloudstack')
end
#
# Return true if the current current node is in Azure
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def azure?(node)
node.key?('azure')
end
#
# Return true if the current current node is in DigitalOcean
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def digitalocean?(node)
node.key?('digital_ocean')
end
#
# Return true if the current current node is in SoftLayer
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def softlayer?(node)
node.key?('softlayer')
end
end
module DSL
# @see Chef::Sugar::Cloud#cloud?
def cloud?; Chef::Sugar::Cloud.cloud?(node); end
# @see Chef::Sugar::Cloud#ec2?
def ec2?; Chef::Sugar::Cloud.ec2?(node); end
# @see Chef::Sugar::Cloud#gce?
def gce?; Chef::Sugar::Cloud.gce?(node); end
# @see Chef::Sugar::Cloud#rackspace?
def rackspace?; Chef::Sugar::Cloud.rackspace?(node); end
# @see Chef::Sugar::Cloud#eucalyptus?
def eucalyptus?; Chef::Sugar::Cloud.eucalyptus?(node); end
alias_method :euca?, :eucalyptus?
# @see Chef::Sugar::Cloud#linode?
def linode?; Chef::Sugar::Cloud.linode?(node); end
# @see Chef::Sugar::Cloud#openstack?
def openstack?; Chef::Sugar::Cloud.openstack?(node); end
# @see Chef::Sugar::Cloud#cloudstack?
def cloudstack?; Chef::Sugar::Cloud.cloudstack?(node); end
# @see Chef::Sugar::Cloud#azure?
def azure?; Chef::Sugar::Cloud.azure?(node); end
# @see Chef::Sugar::Cloud#digitalocean?
def digitalocean?; Chef::Sugar::Cloud.digitalocean?(node); end
# @see Chef::Sugar::Cloud#softlayer?
def softlayer?; Chef::Sugar::Cloud.softlayer?(node); end
end
end
end

View File

@@ -1,108 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module Constraints
#
# This class is a wrapper around a version requirement that adds a nice
# DSL for comparing constraints:
#
# @example Comparing a single constraint
# Constraint.new('~> 1.2.3').satisfied_by?('1.2.7')
#
# @example Comparing multiple constraints
# Constraint.new('> 1.2.3', '< 2.0.0').satisfied_by?('1.2.7')
#
class Constraint
#
# Create a new constraint object.
#
# @param [String, Array<String>] constraints
# the list of constraints
#
def initialize(*constraints)
@requirement = Gem::Requirement.new(*constraints)
end
#
# Determine if the given version string is satisfied by this constraint
# or group of constraints.
#
# @example Given a satisified constraint
# Constraint.new('~> 1.2.0').satisfied_by?('1.2.5') #=> true
#
# @example Given an unsatisfied constraint
# Constraint.new('~> 1.2.0').satisfied_by?('2.0.0') #=> false
#
#
# @param [String] version
# the version to compare
#
# @return [Boolean]
# true if the constraint is satisfied, false otherwise
#
def satisfied_by?(version)
@requirement.satisfied_by?(Gem::Version.new(version))
end
end
#
# This class exposes a single version constraint object that wraps the
# string representation of a version string and proved helpful comparator
# methods.
#
# @example Create a new version
# Chef::Sugar::Version('1.2.3')
#
# @example Compare a version with constraints
# Chef::Sugar::Version('1.2.3').satisfies?('~> 1.3.4', '< 2.0.5')
#
class Version < String
#
# Create a new version object.
#
# @param [String] version
# the version to create
#
def initialize(version)
super
@version = Gem::Version.new(version)
end
#
# Determine if the given constraint is satisfied by this version.
#
# @example Given a satisified version
# Version.new('1.2.5').satisfies?('~> 1.2.0') #=> true
#
# @example Given an unsatisfied version
# Version.new('2.0.0').satisfies?('~> 1.2.0') #=> false
#
#
# @param [String, Array<String>] constraints
# the constraints to satisfy
#
# @return [Boolean]
# true if the version satisfies the constraints, false otherwise
#
def satisfies?(*constraints)
Gem::Requirement.new(*constraints).satisfied_by?(@version)
end
end
end
end
end

View File

@@ -1,83 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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_relative 'constraints'
class Chef
module Sugar
#
# The Constraints DSL methods were broken out into this separate
# file to allow projects (such as Omnibus) to consume the
# Chef::Sugar::Constraints classes without the DSL methods
# stepping on existing methods of the same name.
#
module Constraints
extend self
#
# Shortcut method for creating a new {Version} object.
#
# @param [String] version
# the version (as a string) to create
#
# @return [Chef::Sugar::Constraints::Version]
# the new version object
#
def version(version)
Chef::Sugar::Constraints::Version.new(version)
end
#
# Shortcut method for creating a new {Constraint} object.
#
# @param [String, Array<String>] constraints
# the list of constraints to use
#
# @return [Chef::Sugar::Constraints::Constraint]
# the new constraint object
#
def constraint(*constraints)
Chef::Sugar::Constraints::Constraint.new(*constraints)
end
end
module DSL
# @see Chef::Sugar::Constraints#version
def version(version)
Chef::Sugar::Constraints::Version.new(version)
end
# @see Chef::Sugar::Constraints#constraint
def constraint(*constraints)
Chef::Sugar::Constraints.constraint(*constraints)
end
#
# This wrapper/convenience method is only available in the recipe DSL. It
# creates a new version object from the {Chef::VERSION}.
#
# @example Check if Chef 11+
# chef_version.satisfies?('>= 11.0.0')
#
# @return [Chef::Sugar::Constraints::Version]
# a version object, wrapping the current {Chef::VERSION}
#
def chef_version
version(Chef::VERSION)
end
end
end
end

View File

@@ -1,19 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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_relative 'core_extensions/array'
require_relative 'core_extensions/string'
require_relative 'core_extensions/object'

View File

@@ -1,34 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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_relative '../constraints'
class Array
#
# Treat an array of objects as version constraints.
#
# @see Chef::Sugar::Constraints::Constraint
#
# @example Using pure Array<String> objects like constraints
# ['> 2.0.0', '< 3.0.0'].satisfied_by?('2.1.0')
#
# @param [String] version
# the version to check if it is satisfied
#
def satisfied_by?(version)
Chef::Sugar::Constraints::Constraint.new(*dup).satisfied_by?(version)
end unless method_defined?(:satisfied_by?)
end

View File

@@ -1,27 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Object
# An object is blank if it's false, empty, or a whitespace string.
# This is implemented in rails.
#
# @example foo.nil? || foo.empty? can be replaced by foo.blank?
#
# @return [true, false]
def blank?
respond_to?(:empty?) ? empty? : !self
end unless method_defined?(:blank?)
end

View File

@@ -1,66 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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_relative '../constraints'
class String
#
# Treat strings as version objects.
#
# @see Chef::Sugar::Constraints::Version
#
# @example Using pure string objects like versions
# '1.2.3'.satisfies?('~> 1.2.0')
#
# @param [String, Array<String>] constraints
# the list of constraints to satisfy
#
def satisfies?(*constraints)
Chef::Sugar::Constraints::Version.new(dup).satisfies?(*constraints)
end unless method_defined?(:satisfies?)
#
# Treat strings as version constraints.
#
# @see Chef::Sugar::Constraints::Constraint
#
# @example Using pure string objects like constraints
# '~> 1.2.0'.satisfied_by?('1.2.3')
#
# @param [String] version
# the version to check if it is satisfied
#
def satisfied_by?(version)
Chef::Sugar::Constraints::Constraint.new(dup).satisfied_by?(version)
end unless method_defined?(:satisfied_by?)
#
# Left-flush a string based off of the number of whitespace characters on the
# first line. This is especially useful for heredocs when whitespace matters.
#
# @example Remove leading whitespace and flush
# <<-EOH.flush
# def method
# 'This is a string!'
# end
# EOH #=>"def method\n 'This is a string!'\nend"
#
# @return [String]
#
def flush
gsub(/^#{self[/\A\s*/]}/, '').chomp
end unless method_defined?(:flush)
end

View File

@@ -1,146 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module DataBag
class EncryptedDataBagSecretNotGiven < StandardError
def initialize
super <<-EOH
You did not set your `encrypted_data_bag_secret'! In order to use the
`encrypted_data_bag_item' helper, you must load your encrypted data bag secret
into the `Chef::Config'.
Alternatively, you can pass the secret key as the last parameter to the method
call. For more information, please see
http://docs.opscode.com/chef/essentials_data_bags.html#access-from-recipe.
EOH
end
end
extend self
#
# Helper method for loading an encrypted data bag item in a similar
# syntax/recipe DSL method.
#
# @param [String] bag
# the name of the encrypted data bag
# @param [String] id
# the id of the encrypted data bag
# @param [String] secret
# the encrypted data bag secret raw value
#
# @return [Hash]
#
def encrypted_data_bag_item(bag, id, secret = nil)
Chef::Log.debug "Loading encrypted data bag item #{bag}/#{id}"
if secret.nil? && Chef::Config[:encrypted_data_bag_secret].nil?
raise EncryptedDataBagSecretNotGiven.new
end
secret ||= File.read(Chef::Config[:encrypted_data_bag_secret]).strip
Chef::EncryptedDataBagItem.load(bag, id, secret)
end
#
# This algorithm attempts to find the data bag entry for the current
# node's Chef environment. If there are no environment-specific
# values, the "default" bucket is used. The data bag must follow the
# schema:
#
# {
# "default": {...},
# "environment_name": {...},
# "other_environment": {...},
# }
#
# @param [Node] node
# the current Chef node
# @param [String] bag
# the name of the encrypted data bag
# @param [String] id
# the id of the encrypted data bag
# @param [String] secret
# the encrypted data bag secret (default's to the +Chef::Config+ value)
#
# @return [Hash]
#
def encrypted_data_bag_item_for_environment(node, bag, id, secret = nil)
data = encrypted_data_bag_item(bag, id, secret)
if data[node.chef_environment]
Chef::Log.debug "Using #{node.chef_environment} as the key"
data[node.chef_environment]
else
Chef::Log.debug "#{node.chef_environment} key does not exist, using `default`"
data['default']
end
end
#
# This algorithm attempts to find the data bag entry for the current
# node's Chef environment. If there are no environment-specific
# values, the "default" bucket is used. The data bag must follow the
# schema:
#
# {
# "default": {...},
# "environment_name": {...},
# "other_environment": {...},
# }
#
# @param [Node] node
# the current Chef node
# @param [String] bag
# the name of the data bag
# @param [String] id
# the id of the data bag
#
# @return [Hash]
#
def data_bag_item_for_environment(node, bag, id)
data = Chef::DataBagItem.load(bag, id)
if data[node.chef_environment]
Chef::Log.debug "Using #{node.chef_environment} as the key"
data[node.chef_environment]
else
Chef::Log.debug "#{node.chef_environment} key does not exist, using `default`"
data['default']
end
end
end
module DSL
# @see Chef::Sugar::DataBag#encrypted_data_bag_item
def encrypted_data_bag_item(bag, id, secret = nil)
Chef::Sugar::DataBag.encrypted_data_bag_item(bag, id, secret)
end
# @see Chef::Sugar::DataBag#encrypted_data_bag_item_for_environment
def encrypted_data_bag_item_for_environment(bag, id, secret = nil)
Chef::Sugar::DataBag.encrypted_data_bag_item_for_environment(node, bag, id, secret)
end
# @see Chef::Sugar::DataBag#data_bag_item_for_environment
def data_bag_item_for_environment(bag, id)
Chef::Sugar::DataBag.data_bag_item_for_environment(node, bag, id)
end
end
end
end

View File

@@ -1,45 +0,0 @@
#
# 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.
#
if defined?(Chef::Deprecated::Base)
class Chef
class Deprecated
class ChefSugar < Base
def id
28
end
def target
"chef_sugar.html"
end
end
end
end
end
class Chef
module Sugar
module Deprecation
if defined?(Chef::Deprecated::Base)
def deprecated(message)
Chef.deprecated(:chef_sugar, message)
end
else
def deprecated(message)
Chef::Log.warn(message)
end
end
extend self
end
end
end

View File

@@ -1,45 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module Docker
extend self
# these helpers have been moved to core chef
if !defined?(Chef::VERSION) || Gem::Requirement.new("< 15.4.70").satisfied_by?(Gem::Version.new(Chef::VERSION))
#
# Returns true if the current node is a docker container.
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def docker?(node)
File.exist?('/.dockerinit') || File.exist?('/.dockerenv')
end
end
end
module DSL
if !defined?(Chef::VERSION) || Gem::Requirement.new("< 15.4.70").satisfied_by?(Gem::Version.new(Chef::VERSION))
# @see Chef::Sugar::Docker#docker?
def docker?; Chef::Sugar::Docker.docker?(node); end
end
end
end
end

View File

@@ -1,227 +0,0 @@
class Chef
module Sugar
module Filters
#
# Evaluate resources at compile time instead of converge time.
#
class AtCompileTime
def initialize(recipe)
@recipe = recipe
end
def evaluate(&block)
instance_eval(&block)
end
def method_missing(m, *args, &block)
resource = @recipe.send(m, *args, &block)
if resource.is_a?(Chef::Resource)
actions = Array(resource.action)
resource.action(:nothing)
actions.each do |action|
resource.run_action(action)
end
end
resource
end
end
#
# A top-level class for manipulation the resource collection.
#
class Injector
def initialize(recipe, identifier, placement)
@recipe = recipe
@resource_collection = @recipe.run_context.resource_collection
@resource = @resource_collection.lookup(identifier)
@placement = placement
end
def evaluate(&block)
instance_eval(&block)
end
def insert_before(resource, new_resource)
@resource_collection.instance_eval do
# Remove the resource because it's automatically created
@resources.delete_at(@resources_by_name[new_resource.to_s])
@resources_by_name.delete(new_resource.to_s)
index = @resources_by_name[resource.to_s]
@resources.insert(index, new_resource)
@resources_by_name[new_resource.to_s] = index
end
end
def insert_after(resource, new_resource)
@resource_collection.instance_eval do
# Remove the resource because it's automatically created
@resources.delete_at(@resources_by_name[new_resource.to_s])
@resources_by_name.delete(new_resource.to_s)
index = @resources_by_name[resource.to_s] + 2
@resources.insert(index, new_resource)
@resources_by_name[new_resource.to_s] = index
end
end
def method_missing(m, *args, &block)
new_resource = @recipe.send(m, *args, &block)
case @placement
when :before
insert_before(@resource, new_resource)
when :after
insert_after(@resource, new_resource)
else
super
end
end
end
end
module DSL
#
# Dynamically run resources specified in the block during the compilation
# phase, instead of the convergence phase.
#
# @example The old way
# package('apache2') do
# action :nothing
# end.run_action(:install)
#
# @example The new way
# at_compile_time do
# package('apache2')
# end
#
# @example Resource actions are run in order
# at_compile_time do
# service 'apache2' do
# action [:enable, :start] # run_action(:enable), run_action(:start)
# end
# end
#
def at_compile_time(&block)
Chef::Sugar::Filters::AtCompileTime.new(self).evaluate(&block)
end
#
# Dynamically insert resources before an existing resource in the
# resource_collection.
#
# @example Write a custom template before the apache2 service actions
# are run
# before 'service[apache2]' do
# template '/etc/apache2/thing.conf' do
# source '...'
# end
# end
#
#
# @param [String] identifier
# the +resource[name]+ identifier string
#
def before(identifier, &block)
Chef::Sugar::Filters::Injector.new(self, identifier, :before).evaluate(&block)
end
#
# Dynamically insert resources after an existing resource in the
# resource_collection.
#
# @example Write a custom template after the apache2 service actions
# are run
# after 'service[apache2]' do
# template '/etc/apache2/thing.conf' do
# source '...'
# end
# end
#
#
# @param [String] identifier
# the +resource[name]+ identifier string
#
def after(identifier, &block)
Chef::Sugar::Filters::Injector.new(self, identifier, :after).evaluate(&block)
end
end
module RecipeDSL
#
# @deprecated The description is in the method body pretty accurately...
#
def compile_time(&block)
message = <<-EOH
The Chef Sugar recipe DSL method `compile_time' has been renamed to
`at_compile_time'! This is a breaking change that was released in a patch
version, so please continue reading to understand the necessary semantic
versioning violation.
Chef Software implemented a version of `compile_time' in Chef 12.1, breaking any
cookbook that uses or depends on Chef Sugar on Chef 12.1:
https://www.chef.io/blog/2015/03/03/chef-12-1-0-released
In order to progress Chef Sugar forward, the DSL method has been renamed to
avoid the namespace collision.
In short, you should change this:
compile_time do
# ...
end
to this:
at_compile_time do
# ...
end
EOH
if Chef::Resource::ChefGem.instance_methods(false).include?(:compile_time)
message << <<-EOH
You are running a version of Chef Client that includes the `compile_time'
attribute on core Chef resources (most likely Chef 12.1+). Instead of continuing
and having Chef provide you with an obscure error message, I am going to error
here. There is no way for the Chef Recipe to successfully continue unless you
change the Chef Sugar `compile_time' method to `at_compile_time' in your Chef
recipes.
You should NOT change resource-level `compile_time' attributes:
package "foo" do
compile_time true # Do NOT change these
end
I truly apologize for the inconvienence and hope the reason for introducing this
breaking change is clear. I am sorry if it causes extra work, but I promise this
error message is much more informative than "wrong number of arguments".
If you have any questions, please feel free to open an issue on GitHub at:
https://github.com/sethvargo/chef-sugar
Thank you, and have a great day!
EOH
raise RuntimeError, message
else
message << <<-EOH
You are running a version of Chef Client that does not include the
`compile_time' attribute on core Chef resources (most likely less than
Chef 12.1), so this is just a warning. Please consider changing the Chef Sugar
`compile_time' method to `at_compile_time' in your Chef recipes. If you upgrade
Chef, your recipes WILL break.
EOH
Chef::Log.warn(message)
at_compile_time(&block)
end
end
end
end
end

View File

@@ -1,61 +0,0 @@
#
# Copyright 2015, Nathan Williams <nath.e.will@gmail.com>
#
# 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.
#
class Chef
module Sugar
module Init
extend self
#
# Determine if the current init system is systemd.
#
# @return [Boolean]
#
def systemd?(node)
File.exist?('/bin/systemctl')
end
#
# Determine if the current init system is upstart.
#
# @return [Boolean]
#
def upstart?(node)
File.executable?('/sbin/initctl')
end
#
# Determine if the current init system is runit.
#
# @return [Boolean]
#
def runit?(node)
File.executable?('/sbin/runit-init')
end
end
module DSL
# @see Chef::Sugar::Init#systemd?
def systemd?; Chef::Sugar::Init.systemd?(node); end
# @see Chef::Sugar::Init#upstart?
def upstart?; Chef::Sugar::Init.upstart?(node); end
# @see Chef::Sugar::Init#runit?
def runit?; Chef::Sugar::Init.runit?(node); end
end
end
end

View File

@@ -1,48 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module IP
extend self
#
# The best IP address for the given node, in the context of
# the current node. Useful for choosing a local IP address
# over a public one to limit bandwidth on cloud providers.
#
# @param [Chef::Node] other
# the node to calculate the best IP address for
#
def best_ip_for(node, other)
if other['cloud']
if node['cloud'] && other['cloud']['provider'] == node['cloud']['provider']
other['cloud']['local_ipv4']
else
other['cloud']['public_ipv4']
end
else
other['ipaddress']
end
end
end
module DSL
# @see Chef::Sugar::IP#best_ip_for
def best_ip_for(other); Chef::Sugar::IP.best_ip_for(node, other); end
end
end
end

View File

@@ -1,49 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module Kernel
class ChefGemLoadError < StandardError
def initialize(name)
super <<-EOH
Chef could not load the gem `#{name}'! You may need to install the gem manually
with `gem install #{name}', or include a recipe before you can use this
resource. Please consult the documentation for this cookbook for proper usage.
EOH
end
end
#
# Require a gem that should have been installed by Chef, such as in a
# recipes as a +chef_gem+. This method will gracefully degrade if the
# gem cannot be loaded.
#
# @param [String] name
# the name of the gem to install
#
# @return [Boolean]
# true if the require is successful and false if the gem is already
# loaded
#
def require_chef_gem(name)
require(name)
rescue LoadError
raise ChefGemLoadError.new(name)
end
end
end
end

View File

@@ -1,45 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module Kitchen
extend self
# these helpers have been moved to core-chef
if !defined?(Chef::VERSION) || Gem::Requirement.new("< 15.4.70").satisfied_by?(Gem::Version.new(Chef::VERSION))
#
# Returns true if the current node is provisioned by Test Kitchen.
#
# @param [Chef::Node] node
# the node to check
#
# @return [Boolean]
#
def kitchen?(node)
!ENV['TEST_KITCHEN'].nil?
end
end
end
module DSL
if !defined?(Chef::VERSION) || Gem::Requirement.new("< 15.4.70").satisfied_by?(Gem::Version.new(Chef::VERSION))
# @see Chef::Sugar::Kitchen#kitchen?
def kitchen?; Chef::Sugar::Kitchen.kitchen?(node); end
end
end
end
end

View File

@@ -1,219 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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_relative "deprecation"
class Chef
class Node
class AttributeDoesNotExistError < StandardError
def initialize(keys, key)
hash = keys.map { |key| "['#{key}']" }
super <<-EOH
No attribute `node#{hash.join}' exists on
the current node. Specifically the `#{key}' attribute is not
defined. Please make sure you have spelled everything correctly.
EOH
end
end
#
# Determine if the current node is in the given Chef environment
# (or matches the given regular expression).
#
# @param [String, Regex] environment
#
# @return [Boolean]
#
def in?(environment)
Chef::Sugar::Deprecation.deprecated "the chef-sugar node.in? method is deprecated"
environment === chef_environment
end
#
# Safely fetch a deeply nested attribute by specifying a list of keys,
# bypassing Ruby's Hash notation. This method swallows +NoMethodError+
# exceptions, avoiding the most common error in Chef-land.
#
# This method will return +nil+ if any deeply nested key does not exist.
#
# @see [Node#deep_fetch!]
#
def deep_fetch(*keys)
Chef::Sugar::Deprecation.deprecated "the chef-sugar deep_fetch method is deprecated and should be replaced by node.read"
deep_fetch!(*keys)
rescue NoMethodError, AttributeDoesNotExistError
nil
end
#
# Deeply fetch a node attribute by specifying a list of keys, bypassing
# Ruby's Hash notation.
#
# This method will raise any exceptions, such as
# +undefined method `[]' for nil:NilClass+, just as if you used the native
# attribute notation. If you want a safely vivified hash, see {deep_fetch}.
#
# @example Fetch a deeply nested key
# node.deep_fetch(:foo, :bar, :zip) #=> node['foo']['bar']['zip']
#
# @param [Array<String, Symbol>] keys
# the list of keys to kdeep fetch
#
# @return [Object]
#
def deep_fetch!(*keys)
Chef::Sugar::Deprecation.deprecated "the chef-sugar deep_fetch method is deprecated and should be replaced by node.read!"
keys.map!(&:to_s)
keys.inject(attributes.to_hash) do |hash, key|
if hash.key?(key)
hash[key]
else
raise AttributeDoesNotExistError.new(keys, key)
end
end
end
#
# Dynamically define the current namespace. Multiple namespaces may be
# nested.
#
# @example Define a simple namespace
#
# namespace 'apache2' do
# # ...
# end
#
# @example Define a nested namespace
#
# namespace 'apache2', 'config' do
# # ...
# end
#
# @example Define a complex nested namespace
#
# namespace 'apache2' do
# namespace 'config' do
# # ...
# end
# end
#
# @example Define a namespace with a custom precedence level
#
# namespace 'apache2', precedence: normal do
# # Attributes here will use the "normal" level
# end
#
# @example Define different nested precedence levels
#
# namespace 'apache2', precedence: normal do
# # Attributes defined here will use the "normal" level
#
# namespace 'config', precedence: override do
# # Attributes defined here will use the "override" level
# end
# end
#
#
# @param [Array] args
# the list of arguments (such as the namespace and precedence levels)
# the user gave
# @param [Proc] block
# the nested evaluation context
#
# @return [nil]
# to prevent accidential method chaining if the block isn't closed
#
def namespace(*args, &block)
Chef::Sugar::Deprecation.deprecated "the chef-sugar attribute namespace setting is deprecated, please use traditional chef attribute notation"
@namespace_options = namespace_options.merge(args.last.is_a?(Hash) ? args.pop : {})
keys = args.map(&:to_s)
@current_namespace = current_namespace + keys
instance_eval(&block)
@current_namespace = current_namespace - keys
if @current_namespace.empty?
@namespace_options = nil
end
nil
end
alias_method :old_method_missing, :method_missing
#
# Provide a nice DSL for defining attributes. +method_missing+ is called
# on all the attribute names. For more information on how to use the DSL,
# see the class-level documentation.
#
# @return [nil]
# to prevent accidential method chaining if the block isn't closed
# @return [Object]
# If no argument is passed in, method becomes an attribute accessor
#
def method_missing(m, *args, &block)
old_method_missing(m, *args, &block)
rescue NoMethodError
# The Node Attribute's key is the method name
key = m.to_s
# If arguments are passed in, set node attribute with args as the value
if args.size > 0
vivified[key] = args.size == 1 ? args.first : args
return nil
# If no arguments are passed in, attempt to access corresponding attribute
else
deep_key = current_namespace.dup << key
return deep_fetch!(*deep_key)
end
end
private
#
# The namespace options.
#
# @return [Hash]
#
def namespace_options
@namespace_options ||= {
precedence: default
}
end
#
# The current namespace. This is actually a reverse-ordered array that
# vivifies the correct hash.#
#
# @return [Array<String>]
#
def current_namespace
@current_namespace ||= []
end
#
# The vivified (fake-filled) hash. It is assumed that the default value
# for non-existent keys in the hash is a new, empty hash.
#
# @return [Hash<String, Hash>]
#
def vivified
current_namespace.inject(namespace_options[:precedence]) do |hash, item|
hash[item] ||= {}
hash[item]
end
end
end
end

View File

@@ -1,331 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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_relative 'constraints'
class Chef
module Sugar
module Platform
extend self
PLATFORM_VERSIONS = {
'debian' => {
'squeeze' => '6',
'wheezy' => '7',
'jessie' => '8',
'stretch' => '9',
'buster' => '10',
},
'linuxmint' => {
'tara' => '19',
'sarah' => '18',
'qiana' => '17',
'petra' => '16',
'olivia' => '15',
'nadia' => '14',
'maya' => '13',
'lisa' => '12',
},
'mac_os_x' => {
'lion' => '10.7',
'mountain_lion' => '10.8',
'mavericks' => '10.9',
'yosemite' => '10.10',
'el_capitan' => '10.11',
'sierra' => '10.12',
'high_sierra' => '10.13',
'mojave' => '10.14',
},
'redhat' => {
'santiago' => '6',
'6' => '6',
'maipo' => '7',
'7' => '7',
'oompa' => '8',
'8' => '8'
},
'centos' => {
'final' => '6',
'6' => '6',
'core' => '7',
'7' => '7'
},
'solaris' => {
'7' => '5.7',
'8' => '5.8',
'9' => '5.9',
'10' => '5.10',
'11' => '5.11',
},
'ubuntu' => {
'lucid' => '10.04',
'maverick' => '10.10',
'natty' => '11.04',
'oneiric' => '11.10',
'precise' => '12.04',
'quantal' => '12.10',
'raring' => '13.04',
'saucy' => '13.10',
'trusty' => '14.04',
'utopic' => '14.10',
'vivid' => '15.04',
'wily' => '15.10',
'xenial' => '16.04',
'zesty' => '17.04',
'artful' => '17.10',
'bionic' => '18.04',
'cosmic' => '18.10',
},
}
COMPARISON_OPERATORS = {
'after' => ->(a, b) { a > b },
'after_or_at' => ->(a, b) { a >= b },
'' => ->(a, b) { a == b },
'before' => ->(a, b) { a < b },
'before_or_at' => ->(a, b) { a <= b },
}
# Dynamically define custom matchers at runtime in a matrix. For each
# Platform, we create a map of named versions to their numerical
# equivalents (e.g. debian_before_squeeze?).
PLATFORM_VERSIONS.each do |platform, versions|
versions.each do |name, version|
COMPARISON_OPERATORS.each do |operator, block|
method_name = "#{platform}_#{operator}_#{name}?".squeeze('_').to_sym
define_method(method_name) do |node|
# Find the highest precedence that we actually care about based
# off of what was given to us in the list.
length = version.split('.').size
check = node['platform_version'].split('.')[0...length].join('.')
# Calling #to_f will ensure we only check major versions since
# '10.04.4'.to_f #=> 10.04. We also use a regex to match on
# platform so things like `solaris2` match on `solaris`.
node['platform'] =~ %r(^#{platform}) && block.call(check.to_f, version.to_f)
end
end
end
end
# these helpers have been moved to core chef
if !defined?(Chef::VERSION) || Gem::Requirement.new("< 15.4.70").satisfied_by?(Gem::Version.new(Chef::VERSION))
#
# Determine if the current node is linux mint.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def linux_mint?(node)
node['platform'] == 'linuxmint'
end
alias_method :mint?, :linux_mint?
#
# Determine if the current node is ubuntu.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def ubuntu?(node)
node['platform'] == 'ubuntu'
end
#
# Determine if the current node is debian (platform, not platform_family).
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def debian_platform?(node)
node['platform'] == 'debian'
end
#
# Determine if the current node is amazon linux.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def amazon_linux?(node)
node['platform'] == 'amazon'
end
alias_method :amazon?, :amazon_linux?
#
# Determine if the current node is centos.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def centos?(node)
node['platform'] == 'centos'
end
#
# Determine if the current node is oracle linux.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def oracle_linux?(node)
node['platform'] == 'oracle'
end
alias_method :oracle?, :oracle_linux?
#
# Determine if the current node is scientific linux.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def scientific_linux?(node)
node['platform'] == 'scientific'
end
alias_method :scientific?, :scientific_linux?
#
# Determine if the current node is redhat enterprise.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def redhat_enterprise_linux?(node)
node['platform'] == 'redhat'
end
alias_method :redhat_enterprise?, :redhat_enterprise_linux?
#
# Determine if the current node is fedora (platform, not platform_family).
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def fedora_platform?(node)
node['platform'] == 'fedora'
end
#
# Determine if the current node is solaris2
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def solaris2?(node)
node['platform'] == 'solaris2'
end
alias_method :solaris?, :solaris2?
#
# Determine if the current node is aix
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def aix?(node)
node['platform'] == 'aix'
end
#
# Determine if the current node is smartos
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def smartos?(node)
node['platform'] == 'smartos'
end
#
# Determine if the current node is omnios
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def omnios?(node)
node['platform'] == 'omnios'
end
#
# Determine if the current node is raspbian
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def raspbian?(node)
node['platform'] == 'raspbian'
end
#
# Determine if the current node is a Cisco nexus device
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def nexus?(node)
node['platform'] == 'nexus'
end
#
# Determine if the current node is a Cisco IOS-XR device
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def ios_xr?(node)
node['platform'] == 'ios_xr'
end
end
#
# Return the platform_version for the node. Acts like a String
# but also provides a mechanism for checking version constraints.
#
# @param [Chef::Node] node
#
# @return [Chef::Sugar::Constraints::Version]
#
def platform_version(node)
Chef::Sugar::Constraints::Version.new(node['platform_version'])
end
end
module DSL
Chef::Sugar::Platform.instance_methods.each do |name|
define_method(name) do
Chef::Sugar::Platform.send(name, node)
end
end
end
end
end

View File

@@ -1,184 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module PlatformFamily
extend self
# these helpers have been moved to core chef
if !defined?(Chef::VERSION) || Gem::Requirement.new("< 15.4.70").satisfied_by?(Gem::Version.new(Chef::VERSION))
#
# Determine if the current node is a member of the arch family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def arch_linux?(node)
node['platform_family'] == 'arch'
end
alias_method :arch?, :arch_linux?
#
# Determine if the current node is a member of the debian family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def debian?(node)
node['platform_family'] == 'debian'
end
#
# Determine if the current node is a member of the fedora family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def fedora?(node)
node['platform_family'] == 'fedora'
end
#
# Determine if the current node is a member of the freebsd family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def freebsd?(node)
node['platform_family'] == 'freebsd'
end
#
# Determine if the current node is a member of the arch family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def gentoo?(node)
node['platform_family'] == 'gentoo'
end
#
# Determine if the current node is a member of the OSX family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def mac_os_x?(node)
node['platform_family'] == 'mac_os_x'
end
alias_method :osx?, :mac_os_x?
alias_method :mac?, :mac_os_x?
#
# Determine if the current node is a member of the openbsd family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def openbsd?(node)
node['platform_family'] == 'openbsd'
end
#
# Determine if the current node is a member of the redhat family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def rhel?(node)
node['platform_family'] == 'rhel'
end
alias_method :redhat?, :rhel?
alias_method :el?, :rhel?
#
# Determine if the current node is a member of the slackware family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def slackware?(node)
node['platform_family'] == 'slackware'
end
#
# Determine if the current node is a member of the suse family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def suse?(node)
node['platform_family'] == 'suse'
end
#
# Determine if the current node is a member of the windows family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def windows?(node)
node['platform_family'] == 'windows'
end
#
# Determine if the current node is a member of the wrlinux family.
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def wrlinux?(node)
node['platform_family'] == 'wrlinux'
end
#
# Determine if the current system is a linux derivative
#
# @param [Chef::Node] node
#
# @return [Boolean]
#
def linux?(node)
node['os'] == 'linux'
end
end
end
module DSL
Chef::Sugar::PlatformFamily.instance_methods.each do |name|
define_method(name) do
Chef::Sugar::PlatformFamily.send(name, node)
end
end
end
end
end

View File

@@ -1,51 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module Ruby
extend self
#
# Determine if the current Ruby version is 2.0.
#
# @return [Boolean]
#
def ruby_20?(node)
version = Gem::Version.new(node['languages']['ruby']['version'])
Gem::Requirement.new('~> 2.0.0').satisfied_by?(version)
end
#
# Determine if the current Ruby version is 1.9.
#
# @return [Boolean]
#
def ruby_19?(node)
version = Gem::Version.new(node['languages']['ruby']['version'])
Gem::Requirement.new('~> 1.9.0').satisfied_by?(version)
end
end
module DSL
# @see Chef::Sugar::Ruby#ruby_20?
def ruby_20?; Chef::Sugar::Ruby.ruby_20?(node); end
# @see Chef::Sugar::Ruby#ruby_19?
def ruby_19?; Chef::Sugar::Ruby.ruby_19?(node); end
end
end
end

View File

@@ -1,41 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module RunContext
extend self
#
# Determine if the current node includes the given recipe name.
#
# @param [String] recipe_name
#
def includes_recipe?(node, recipe_name)
node.recipe?(recipe_name)
end
alias_method :include_recipe?, :includes_recipe?
end
module DSL
# @see Chef::Sugar::IP#best_ip_for
def includes_recipe?(recipe_name)
Chef::Sugar::RunContext.includes_recipe?(node, recipe_name)
end
alias_method :include_recipe?, :includes_recipe?
end
end
end

View File

@@ -1,157 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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 'mixlib/shellout' unless defined?(Mixlib::ShellOut)
require 'pathname' unless defined?(Pathname)
class Chef
module Sugar
module Shell
extend self
# this helper has been moved to core chef
if !defined?(Chef::VERSION) || Gem::Requirement.new("< 16.0.257").satisfied_by?(Gem::Version.new(Chef::VERSION))
#
# Finds a command in $PATH
#
# @param [String] cmd
# the command to find
#
# @return [String, nil]
#
def which(cmd)
if Pathname.new(cmd).absolute?
File.executable?(cmd) ? cmd : nil
else
paths = ENV['PATH'].split(::File::PATH_SEPARATOR) + %w(/bin /usr/bin /sbin /usr/sbin)
paths.each do |path|
possible = File.join(path, cmd)
return possible if File.executable?(possible)
end
nil
end
end
end
#
# The platform-specific output path to +/dev/null+.
#
# @return [String]
#
def dev_null(node)
if defined?(ChefUtils)
ChefUtils.windows?(node) ? 'NUL' : '/dev/null'
else
Chef::Sugar::PlatformFamily.windows?(node) ? 'NUL' : '/dev/null'
end
end
#
# Boolean method to check if a command line utility is installed.
#
# @param [String] cmd
# the command to find
#
# @return [Boolean]
# true if the command is found in the path, false otherwise
#
def installed?(cmd)
!which(cmd).nil?
end
#
# Checks if the given binary is installed and exists at the given
# version. Also see {version_for}.
#
# @param [String] cmd
# the command to check
# @param [String] expected_version
# the version to check
# @param [String] flag
# the flag to use to check the version of the binary
#
# @return [Boolean]
# true if the command exists and is at the given version, false
# otherwise
#
def installed_at_version?(cmd, expected_version, flag = '--version')
return false if !installed?(cmd)
version = version_for(cmd, flag)
return false if version.nil?
if expected_version.is_a?(Regexp)
!version.match(expected_version).nil?
else
version.include?(expected_version)
end
end
#
# The version for a given command. This method does NOT check if the
# command exists! It is assumed the command existence has been
# checked with +which+ or similar. To simply check if an installed
# version is acceptable, please see {installed_at_version}.
#
# Assumptions:
# 1. The command exists.
# 2. The command outputs version information to +$stdout+ or +$stderr+.
# Did you know that java outputs its version to $stderr?
#
#
# @param [String] cmd
# the command to find the version for
# @param [String] flag
# the flag to use to get the version
#
# @return [String]
# the entire output of the version command (stderr and stdout)
#
def version_for(cmd, flag = '--version')
cmd = Mixlib::ShellOut.new("#{cmd} #{flag}")
cmd.run_command
cmd.error!
[cmd.stdout.strip, cmd.stderr.strip].join("\n")
end
end
module DSL
# this helper has been moved to core chef
if !defined?(Chef::VERSION) || Gem::Requirement.new("< 16.0.257").satisfied_by?(Gem::Version.new(Chef::VERSION))
# @see Chef::Sugar::Shell#which
def which(cmd); Chef::Sugar::Shell.which(cmd); end
end
# @see Chef::Sugar::Shell#dev_null
def dev_null; Chef::Sugar::Shell.dev_null(node); end
# @see Chef::Sugar::Shell#installed?
def installed?(cmd); Chef::Sugar::Shell.installed?(cmd); end
# @see Chef::Sugar::Shell#installed_at_version?
def installed_at_version?(cmd, version, flag = '--version')
Chef::Sugar::Shell.installed_at_version?(cmd, version, flag)
end
# @see Chef::Sugar::Shell#version_for
def version_for(cmd, flag = '--version')
Chef::Sugar::Shell.version_for(cmd, flag)
end
end
end
end

View File

@@ -1,77 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
module Vagrant
extend self
#
# Determine if the current node is running in vagrant mode.
#
# @param [Chef::Node] node
#
# @return [Boolean]
# true if the machine is currently running vagrant, false
# otherwise
#
def vagrant?(node)
vagrant_key?(node) || vagrant_domain?(node) || vagrant_user?(node)
end
private
#
# Check if the +vagrant+ key exists on the +node+ object. This key is no
# longer populated by vagrant, but it is kept around for legacy purposes.
#
# @param (see vagrant?)
# @return (see vagrant?)
#
def vagrant_key?(node)
node.key?('vagrant')
end
#
# Check if "vagrantup.com" is included in the node's domain. Technically,
# this would make Chef Sugar falsely detect +vagrant?+ on any of
# Hashicorp's servers. But if that edge case becomes a serious problem,
# @mitchellh has my phone number.
#
# @param (see vagrant?)
# @return (see vagrant?)
#
def vagrant_domain?(node)
node.key?('domain') && !node['domain'].nil? && node['domain'].include?('vagrantup.com')
end
#
# Check if the system contains a +vagrant+ user.
#
# @param (see vagrant?)
# @return (see vagrant?)
#
def vagrant_user?(node)
node.key?('etc') && node['etc'].key?('passwd') && node['etc']['passwd'].key?('vagrant')
end
end
module DSL
# @see Chef::Sugar::Vagrant#vagrant?
def vagrant?; Chef::Sugar::Vagrant.vagrant?(node); end
end
end
end

View File

@@ -1,21 +0,0 @@
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
class Chef
module Sugar
VERSION = "5.1.12"
end
end

View File

@@ -1,151 +0,0 @@
#
# Copyright 2014, Joseph J. Nuspl Jr. <nuspl@nvwls.com>
#
# 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.
#
class Chef
module Sugar
module Virtualization
extend self
#
# Determine if the current node is running under KVM.
#
# @param [Chef::Node] node
#
# @return [Boolean]
# true if the machine is currently running under KVM, false
# otherwise
#
def kvm?(node)
node.key?('virtualization') && node['virtualization']['system'] == 'kvm'
end
#
# Determine if the current node is running in a linux container.
#
# @param [Chef::Node] node
#
# @return [Boolean]
# true if the machine is currently running in a container, false
# otherwise
#
def lxc?(node)
node.key?('virtualization') && node['virtualization']['system'] == 'lxc'
end
#
# Determine if the current node is running under Parallels Desktop.
#
# @param [Chef::Node] node
#
# @return [Boolean]
# true if the machine is currently running under Parallels Desktop, false
# otherwise
#
def parallels?(node)
node.key?('virtualization') && node['virtualization']['system'] == 'parallels'
end
#
# Determine if the current node is running under VirtualBox.
#
# @param [Chef::Node] node
#
# @return [Boolean]
# true if the machine is currently running under VirtualBox, false
# otherwise
#
def virtualbox?(node)
node.key?('virtualization') && node['virtualization']['system'] == 'vbox'
end
#
# Determine if the current node is running under VMware.
#
# @param [Chef::Node] node
#
# @return [Boolean]
# true if the machine is currently running under VMware, false
# otherwise
#
def vmware?(node)
node.key?('virtualization') && node['virtualization']['system'] == 'vmware'
end
#
# Determine if the current node is running under openvz.
#
# @param [Chef::Node] node
#
# @return [Boolean]
# true if the machine is currently running under openvz, false
# otherwise
#
def openvz?(node)
node.key?('virtualization') && node['virtualization']['system'] == 'openvz'
end
def virtual?(node)
openvz?(node) || vmware?(node) || virtualbox?(node) || parallels?(node) || lxc?(node) || kvm?(node)
end
def physical?(node)
!virtual?(node)
end
end
module DSL
# @see Chef::Sugar::Virtualization#kvm?
def kvm?
Chef::Sugar::Virtualization.kvm?(node)
end
# @see Chef::Sugar::Virtualization#lxc?
def lxc?
Chef::Sugar::Virtualization.lxc?(node)
end
# @see Chef::Sugar::Virtualization#parallels?
def parallels?
Chef::Sugar::Virtualization.parallels?(node)
end
# @see Chef::Sugar::Virtualization#virtualbox?
def virtualbox?
Chef::Sugar::Virtualization.virtualbox?(node)
end
# @see Chef::Sugar::Virtualization#vmware?
def vmware?
Chef::Sugar::Virtualization.vmware?(node)
end
# @see Chef::Sugar::Virtualization#openvz?
def openvz?
Chef::Sugar::Virtualization.openvz?(node)
end
# @see Chef::Sugar::Virtualization#virtual?
def virtual?
Chef::Sugar::Virtualization.virtual?(node)
end
# @see Chef::Sugar::Virtualization#physical?
def physical?
Chef::Sugar::Virtualization.physical?(node)
end
end
end
end

View File

@@ -1 +0,0 @@
require "chef/sugar"

View File

@@ -1,38 +0,0 @@
{
"name": "chef-sugar",
"description": "Installs chef-sugar. Please see the chef-sugar Ruby gem for more information.",
"long_description": "Chef Sugar is a Gem & Chef Recipe that includes series of helpful syntactic\nsugars on top of the Chef core and other resources to make a cleaner, more lean\nrecipe DSL, enforce DRY principles, and make writing Chef recipes an awesome and\nfun experience!\n\nFor the most up-to-date information and documentation, please visit the [Chef\nSugar project page on GitHub](https://github.com/chef/chef-sugar).\n",
"maintainer": "Chef Software, Inc",
"maintainer_email": "cookbooks@chef.io",
"license": "Apache-2.0",
"platforms": {
"any": ">= 0.0.0"
},
"dependencies": {
},
"providing": {
},
"recipes": {
},
"version": "5.1.12",
"source_url": "https://github.com/chef/chef-sugar",
"issues_url": "https://github.com/chef/chef-sugar/issues",
"privacy": false,
"chef_versions": [
[
">= 13.0"
]
],
"ohai_versions": [
],
"gems": [
[
"chef-sugar"
]
],
"eager_load_libraries": true
}

View File

@@ -1,22 +0,0 @@
name 'chef-sugar'
maintainer 'Chef Software, Inc'
maintainer_email 'cookbooks@chef.io'
license 'Apache-2.0'
description 'Installs chef-sugar. Please see the chef-sugar Ruby gem for more information.'
long_description <<-EOH
Chef Sugar is a Gem & Chef Recipe that includes series of helpful syntactic
sugars on top of the Chef core and other resources to make a cleaner, more lean
recipe DSL, enforce DRY principles, and make writing Chef recipes an awesome and
fun experience!
For the most up-to-date information and documentation, please visit the [Chef
Sugar project page on GitHub](https://github.com/chef/chef-sugar).
EOH
version '5.1.12'
supports 'any'
issues_url 'https://github.com/chef/chef-sugar/issues'
source_url 'https://github.com/chef/chef-sugar'
chef_version '>= 13.0'
gem 'chef-sugar'

View File

@@ -1,20 +0,0 @@
#
# Cookbook Name:: chef-sugar
# Recipe:: default
#
# Copyright 2013-2015, Seth Vargo <sethvargo@gmail.com>
#
# 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.
#
Chef::Log.warn('chef-sugar::default no longer needs to be included in your runlist. Instead simply depend on the chef-sugar cookbook and the gem will be installed and loaded automatically.')

View File

@@ -1,28 +0,0 @@
require 'rspec'
require 'chefspec'
require 'chef/sugar'
require 'chef/version'
require_relative 'support/shared_examples'
RSpec.configure do |config|
# Prohibit using the should syntax
config.expect_with :rspec do |spec|
spec.syntax = :expect
end
# Focus groups
config.filter_run(focus: true)
config.run_all_when_everything_filtered = true
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
# ChefSpec configuration
config.log_level = :fatal
config.filter_run_excluding pre_chef16_only: Gem::Requirement.new(">= 16.0.257").satisfied_by?(Gem::Version.new(Chef::VERSION))
end

View File

@@ -1,20 +0,0 @@
module RSpec
shared_examples 'a chef sugar' do
it 'acts as a singleton' do
described_class.module_eval("def foo; 'result'; end")
klass = Class.new.tap { |k| k.send(:include, described_class) }
expect(described_class.foo).to eq(klass.new.foo)
end
described_class.instance_methods.each do |name|
it "defines a `#{name}` DSL method" do
expect(Chef::Sugar::DSL).to be_method_defined(name)
end
it 'has n-1 arity from the parent method' do
method = Chef::Sugar::DSL.instance_method(name)
expect(method.arity).to eq(described_class.method(name).arity - 1)
end
end
end
end

View File

@@ -1,149 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::Cloud do
it_behaves_like 'a chef sugar'
describe '#cloud?' do
it 'is true when the node is on cloud' do
node = { 'cloud' => nil }
expect(described_class.cloud?(node)).to be true
end
it 'is false when the node is not on cloud' do
node = {}
expect(described_class.cloud?(node)).to be false
end
end
describe '#ec2?' do
it 'is true when the node is on ec2' do
node = { 'ec2' => nil }
expect(described_class.ec2?(node)).to be true
end
it 'is false when the node is not on ec2' do
node = {}
expect(described_class.ec2?(node)).to be false
end
end
describe '#gce?' do
it 'is true when the node is on gce' do
node = { 'gce' => nil }
expect(described_class.gce?(node)).to be true
end
it 'is false when the node is not on gce' do
node = {}
expect(described_class.gce?(node)).to be false
end
end
describe '#rackspace?' do
it 'is true when the node is on rackspace' do
node = { 'rackspace' => nil }
expect(described_class.rackspace?(node)).to be true
end
it 'is false when the node is not on rackspace' do
node = {}
expect(described_class.rackspace?(node)).to be false
end
end
describe '#eucalyptus?' do
it 'is true when the node is on eucalyptus' do
node = { 'eucalyptus' => nil }
expect(described_class.eucalyptus?(node)).to be true
end
it 'is false when the node is not on eucalyptus' do
node = {}
expect(described_class.eucalyptus?(node)).to be false
end
end
describe '#euca?' do
it 'is true when the node is on eucalyptus' do
node = { 'eucalyptus' => nil }
expect(described_class.euca?(node)).to be true
end
it 'is false when the node is not on eucalyptus' do
node = {}
expect(described_class.euca?(node)).to be false
end
end
describe '#linode?' do
it 'is true when the node is on linode' do
node = { 'linode' => nil }
expect(described_class.linode?(node)).to be true
end
it 'is false when the node is not on linode' do
node = {}
expect(described_class.linode?(node)).to be false
end
end
describe '#openstack?' do
it 'is true when the node is on openstack' do
node = { 'openstack' => nil }
expect(described_class.openstack?(node)).to be true
end
it 'is false when the node is not on openstack' do
node = {}
expect(described_class.openstack?(node)).to be false
end
end
describe '#cloudstack?' do
it 'is true when the node is on cloudstack' do
node = { 'cloudstack' => nil }
expect(described_class.cloudstack?(node)).to be true
end
it 'is false when the node is not on cloudstack' do
node = {}
expect(described_class.cloudstack?(node)).to be false
end
end
describe '#azure?' do
it 'is true when the node is on azure' do
node = { 'azure' => nil }
expect(described_class.azure?(node)).to be true
end
it 'is false when the node is not on azure' do
node = {}
expect(described_class.azure?(node)).to be false
end
end
describe '#digitalocean?' do
it 'is true when the node is on digitalocean' do
node = { 'digital_ocean' => nil }
expect(described_class.digitalocean?(node)).to be true
end
it 'is false when the node is not on digitalocean' do
node = {}
expect(described_class.digitalocean?(node)).to be false
end
end
describe '#softlayer?' do
it 'is true when the node is on softlayer' do
node = { 'softlayer' => nil }
expect(described_class.softlayer?(node)).to be true
end
it 'is false when the node is not on softlayer' do
node = {}
expect(described_class.softlayer?(node)).to be false
end
end
end

View File

@@ -1,45 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::Constraints do
describe '#version' do
let(:version) { described_class.version('1.2.3') }
it 'returns a new version object' do
expect(version).to be_a(Chef::Sugar::Constraints::Version)
end
it 'behaves like a String' do
expect(version).to be_a(String)
end
it 'returns true with the version is satisifed' do
expect(version).to be_satisfies('~> 1.2.0')
end
it 'returns false when the version is not satisfed' do
expect(version).to_not be_satisfies('~> 2.0.0')
end
end
describe '#constraint' do
let(:constraint) { described_class.constraint('~> 1.2.0') }
it 'returns a new constraint object' do
expect(constraint).to be_a(Chef::Sugar::Constraints::Constraint)
end
it 'returns true when the constraint is satisfied' do
expect(constraint).to be_satisfied_by('1.2.3')
end
it 'returns false when the constraint is not satisfied' do
expect(constraint).to_not be_satisfied_by('2.0.0')
end
end
describe '#chef_version' do
it 'is a DSL method' do
expect(Chef::Sugar::DSL).to be_method_defined(:chef_version)
end
end
end

View File

@@ -1,10 +0,0 @@
require 'spec_helper'
require 'chef/sugar/core_extensions'
describe Array do
describe '#satisfied_by?' do
it 'includes the method' do
expect(described_class).to be_method_defined(:satisfied_by?)
end
end
end

View File

@@ -1,62 +0,0 @@
require 'spec_helper'
require 'chef/sugar/core_extensions'
describe Object do
describe '#blank?' do
it 'includes the method' do
expect(described_class).to be_method_defined(:blank?)
end
it 'returns true for nil' do
expect(nil).to be_blank
end
it 'returns true for false' do
expect(false).to be_blank
end
it 'returns true for the empty string' do
expect('').to be_blank
end
it 'returns true for the empty array' do
expect([]).to be_blank
end
it 'returns true for the empty hash' do
expect({}).to be_blank
end
it 'returns false for a non-empty string' do
expect(' ').to_not be_blank
end
it 'returns false for a non-empty string with unicode' do
expect("\u00a0").to_not be_blank
end
it 'returns false for a non-empty string with special characters' do
expect("\n\t").to_not be_blank
end
it 'returns false for any object' do
expect(Object.new).to_not be_blank
end
it 'returns false for true' do
expect(true).to_not be_blank
end
it 'returns false for a fixnum' do
expect(1).to_not be_blank
end
it 'returns false for an array with items' do
expect(['foo']).to_not be_blank
end
it 'returns false for an array with items' do
expect({'foo' => 'bar'}).to_not be_blank
end
end
end

View File

@@ -1,48 +0,0 @@
require 'spec_helper'
require 'chef/sugar/core_extensions'
describe String do
describe '#satisfies?' do
it 'includes the method' do
expect(described_class).to be_method_defined(:satisfies?)
end
end
describe '#satisfied_by?' do
it 'includes the method' do
expect(described_class).to be_method_defined(:satisfied_by?)
end
end
describe '#flush' do
context 'when given a single-line string' do
it 'strips trailing whitespace' do
string = <<-EOH
This is a string
EOH
expect(string.flush).to eq('This is a string')
end
end
context 'when given a multi-line string' do
it 'removes the leading number of whitespaces' do
string = <<-EOH
def method
"This is a string!"
end
EOH
expect(string.flush).to eq(%Q(def method\n "This is a string!"\nend))
end
it 'leaves a newline when given' do
string = <<-EOH
def method
"This is a string!"
end
EOH
expect(string.flush).to eq(%Q(def method\n "This is a string!"\nend\n))
end
end
end
end

View File

@@ -1,118 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::DataBag do
describe '#encrypted_data_bag_item' do
before { allow(Chef::EncryptedDataBagItem).to receive(:load) }
it 'loads the encrypted data bag item' do
expect(Chef::EncryptedDataBagItem).to receive(:load)
.with('accounts', 'github', 'secret_key')
described_class.encrypted_data_bag_item('accounts', 'github', 'secret_key')
end
context 'when Chef::Config is set' do
it 'loads the secret key from the Chef::Config' do
allow(Chef::Config).to receive(:[]).with(:encrypted_data_bag_secret).and_return('/data/path')
allow(File).to receive(:read).with('/data/path').and_return('B@c0n')
expect(Chef::EncryptedDataBagItem).to receive(:load)
.with('accounts', 'github', 'B@c0n')
described_class.encrypted_data_bag_item('accounts', 'github')
end
end
context 'when Chef::Config is not set and no value is given' do
it 'raises an exception' do
expect {
described_class.encrypted_data_bag_item('accounts', 'github')
}.to raise_error(Chef::Sugar::DataBag::EncryptedDataBagSecretNotGiven)
end
end
end
describe '#encrypted_data_bag_item_for_environment' do
let(:node) { double(:node, chef_environment: 'production') }
context 'when the environment exists' do
it 'loads the data from the environment' do
allow(Chef::EncryptedDataBagItem).to receive(:load).and_return(
'production' => {
'username' => 'sethvargo',
'password' => 'bacon',
}
)
expect(described_class.encrypted_data_bag_item_for_environment(node, 'accounts', 'github', 'secret_key')).to eq(
'password' => 'bacon',
'username' => 'sethvargo',
)
end
end
context 'when the environment does not exist' do
it 'loads the data from the default bucket' do
allow(Chef::EncryptedDataBagItem).to receive(:load).and_return(
'staging' => {
'username' => 'sethvargo',
'password' => 'bacon',
},
'default' => {
'username' => 'schisamo',
'password' => 'ham',
}
)
expect(described_class.encrypted_data_bag_item_for_environment(node, 'accounts', 'github', 'secret_key')).to eq(
'password' => 'ham',
'username' => 'schisamo',
)
end
end
end
describe '#data_bag_item_for_environment' do
let(:node) { double(:node, chef_environment: 'production') }
context 'when the environment exists' do
it 'loads the data from the environment' do
allow(Chef::DataBagItem).to receive(:load).and_return(
'production' => {
'username' => 'sethvargo',
'comment' => 'loves bacon',
},
'default' => {
'username' => 'schisamo',
'comment' => 'more of a ham guy',
}
)
expect(described_class.data_bag_item_for_environment(node, 'accounts', 'github')).to eq(
'comment' => 'loves bacon',
'username' => 'sethvargo',
)
end
end
context 'when the environment does not exist' do
it 'loads the data from the default bucket' do
allow(Chef::DataBagItem).to receive(:load).and_return(
'staging' => {
'username' => 'sethvargo',
'comment' => 'loves bacon',
},
'default' => {
'username' => 'schisamo',
'comment' => 'more of a ham guy',
}
)
expect(described_class.data_bag_item_for_environment(node, 'accounts', 'github')).to eq(
'comment' => 'more of a ham guy',
'username' => 'schisamo',
)
end
end
end
end

View File

@@ -1,70 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::Init do
it_behaves_like 'a chef sugar'
before(:each) do
allow(IO).to receive(:read)
.with("/proc/1/comm")
.and_return("init")
allow(File).to receive(:executable?)
.with("/sbin/initctl")
.and_return(false)
allow(File).to receive(:executable?)
.with("/sbin/runit-init")
.and_return(false)
end
describe '#systemd?' do
systemctl_path = '/bin/systemctl'
it "is true when #{systemctl_path} exists" do
allow(File).to receive(:exist?)
.with(systemctl_path)
.and_return(true)
node = {}
expect(described_class.systemd?(node)).to be true
end
it "is false when #{systemctl_path} does not exist" do
allow(File).to receive(:exist?)
.with(systemctl_path)
.and_return(false)
node = {}
expect(described_class.systemd?(node)).to be false
end
end
describe '#upstart?' do
it 'is true when /sbin/initctl is executable' do
allow(File).to receive(:executable?)
.with("/sbin/initctl")
.and_return(true)
node = {}
expect(described_class.upstart?(node)).to be true
end
it 'is false when /sbin/initctl is not executable' do
node = {}
expect(described_class.upstart?(node)).to be false
end
end
describe '#runit?' do
it 'is true when /sbin/runit-init is executable' do
allow(File).to receive(:executable?)
.with("/sbin/runit-init")
.and_return(true)
node = {}
expect(described_class.runit?(node)).to be true
end
it 'is false when /sbin/runit-init is not executable' do
node = {}
expect(described_class.runit?(node)).to be false
end
end
end

View File

@@ -1,53 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::IP do
it_behaves_like 'a chef sugar'
let(:node) { { 'ipaddress' => '1.2.3.4' } }
let(:other) { { 'ipaddress' => '5.6.7.8' } }
context 'when not on a cloud' do
it 'returns the default IP address' do
expect(described_class.best_ip_for(node, other)).to eq(other['ipaddress'])
end
end
context 'when the target is on the cloud' do
before do
other['cloud'] = {}
other['cloud']['provider'] = 'ec2'
other['cloud']['local_ipv4'] = '9.10.11.12'
other['cloud']['public_ipv4'] = '13.14.15.16'
node['cloud'] = nil
end
context 'when the current node is not on the cloud' do
it 'uses the public ipv4' do
expect(described_class.best_ip_for(node, other)).to eq('13.14.15.16')
end
end
context 'when the current node is on a different cloud' do
before do
node['cloud'] = {}
node['cloud']['provider'] = 'rackspace'
end
it 'uses the public ipv4' do
expect(described_class.best_ip_for(node, other)).to eq('13.14.15.16')
end
end
context 'when the current node is on the same cloud' do
before do
node['cloud'] = {}
node['cloud']['provider'] = 'ec2'
end
it 'uses the local ipv4' do
expect(described_class.best_ip_for(node, other)).to eq('9.10.11.12')
end
end
end
end

View File

@@ -1,16 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::Kernel do
describe '.require_chef_gem' do
it 'raises an exception when the gem is not installed' do
expect {
described_class.require_chef_gem('bacon')
}.to raise_error(Chef::Sugar::Kernel::ChefGemLoadError)
end
it 'loads the gem' do
allow(Chef::Sugar::Kernel).to receive(:require).and_return(true)
expect(described_class.require_chef_gem('bacon')).to be true
end
end
end

View File

@@ -1,172 +0,0 @@
require 'spec_helper'
describe Chef::Node do
describe '#in?' do
it 'returns true when the node is in the environment' do
allow(subject).to receive(:chef_environment).and_return('production')
expect(subject.in?('production')).to be true
expect(subject.in?(/production$/)).to be true
end
it 'returns false when the node is not in the environment' do
allow(subject).to receive(:chef_environment).and_return('staging')
expect(subject.in?('production')).to be false
expect(subject.in?(/production$/)).to be false
end
end
describe '#deep_fetch' do
let(:node) { described_class.new }
before { node.default['apache2']['config']['root'] = '/var/www' }
it 'fetches a deeply nested attribute' do
expect(node.deep_fetch('apache2', 'config', 'root')).to eq('/var/www')
end
it 'ignores symbols, strings, etc' do
expect(node.deep_fetch(:apache2, :config, :root)).to eq('/var/www')
end
it 'safely returns nil if a key does not exist' do
expect(node.deep_fetch(:apache2, :not_real, :nested, :yup)).to be_nil
end
end
describe '#deep_fetch!' do
let(:node) { described_class.new }
before { node.default['apache2']['config']['root'] = '/var/www' }
it 'fetches a deeply nested attribute' do
expect(node.deep_fetch!('apache2', 'config', 'root')).to eq('/var/www')
end
it 'ignores symbols, strings, etc' do
expect(node.deep_fetch!(:apache2, :config, :root)).to eq('/var/www')
end
it 'raises an error if a key does not exist' do
expect {
node.deep_fetch!(:apache2, :not_real)
}.to raise_error(Chef::Node::AttributeDoesNotExistError) { |e|
expect(e.message).to eq(<<-EOH.gsub(/^ {10}/, ''))
No attribute `node['apache2']['not_real']' exists on
the current node. Specifically the `not_real' attribute is not
defined. Please make sure you have spelled everything correctly.
EOH
}
end
end
describe '#namespace' do
let(:node) { described_class.new }
it 'defines the attributes' do
node.instance_eval do
namespace 'apache2' do
namespace 'config' do
root '/var/www'
end
end
end
expect(node.default).to eq({
'apache2' => {
'config' => { 'root' => '/var/www' }
}
})
end
it 'accepts multiple attributes' do
node.instance_eval do
namespace 'apache2', 'config' do
root '/var/www'
end
end
expect(node.default).to eq({
'apache2' => {
'config' => { 'root' => '/var/www' }
}
})
end
it 'accepts attribute precedence levels' do
node.instance_eval do
namespace 'apache2', precedence: normal do
namespace 'config', precedence: override do
root '/var/www'
end
end
end
expect(node.override).to eq({
'apache2' => {
'config' => { 'root' => '/var/www' }
}
})
end
it 'maintains precedence level into nested calls' do
node.instance_eval do
namespace 'apache2', precedence: override do
namespace 'config' do
root '/var/www'
end
end
end
expect(node.override).to eq({
'apache2' => {
'config' => { 'root' => '/var/www' }
}
})
end
it 'resets precedence to default in subsequent non-nested calls' do
node.instance_eval do
namespace 'apache2', precedence: override do
namespace 'config' do
root '/var/www'
end
end
namespace 'php' do
version '5.3'
end
end
expect(node.override).to eq({
'apache2' => {
'config' => { 'root' => '/var/www' }
}
})
expect(node.default).to eq({
'php' => {
'version' => '5.3'
}
})
end
it 'can access attributes within itself' do
node.instance_eval do
namespace 'apache2' do
namespace 'config' do
root '/var/www'
ssl File.join(root, 'ssl')
end
end
end
expect(node.default).to eq({
'apache2' => {
'config' => {
'root' => '/var/www',
'ssl' => '/var/www/ssl',
}
}
})
end
end
end

View File

@@ -1,174 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::Platform do
it_behaves_like 'a chef sugar'
describe '#platform_version' do
it 'returns the platform version' do
node = { 'platform_version' => '1.2.3' }
expect(described_class.platform_version(node)).to eq('1.2.3')
end
end
context 'dynamic matchers' do
describe '#ubuntu_after_lucid?' do
it 'returns true when the version is later than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.10' }
expect(described_class.ubuntu_after_lucid?(node)).to be true
end
it 'returns false when the version is 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.04' }
expect(described_class.ubuntu_after_lucid?(node)).to be false
end
it 'returns false when the version is a patch release higher than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.04.4' }
expect(described_class.ubuntu_after_lucid?(node)).to be false
end
it 'returns false when the version is less than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '9.10' }
expect(described_class.ubuntu_after_lucid?(node)).to be false
end
end
describe '#ubuntu_after_or_at_lucid?' do
it 'returns true when the version is later than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.10' }
expect(described_class.ubuntu_after_or_at_lucid?(node)).to be true
end
it 'returns true when the version is 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.04' }
expect(described_class.ubuntu_after_or_at_lucid?(node)).to be true
end
it 'returns true when the version is a patch release higher than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.04.4' }
expect(described_class.ubuntu_after_or_at_lucid?(node)).to be true
end
it 'returns false when the version is less than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '9.10' }
expect(described_class.ubuntu_after_or_at_lucid?(node)).to be false
end
end
describe '#ubuntu_lucid?' do
it 'returns false when the version is later than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.10' }
expect(described_class.ubuntu_lucid?(node)).to be false
end
it 'returns true when the version is 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.04' }
expect(described_class.ubuntu_lucid?(node)).to be true
end
it 'returns true when the version is a patch release higher than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.04.4' }
expect(described_class.ubuntu_lucid?(node)).to be true
end
it 'returns false when the version is less than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '9.10' }
expect(described_class.ubuntu_lucid?(node)).to be false
end
end
describe '#ubuntu_before_lucid?' do
it 'returns false when the version is later than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.10' }
expect(described_class.ubuntu_before_lucid?(node)).to be false
end
it 'returns false when the version is 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.04' }
expect(described_class.ubuntu_before_lucid?(node)).to be false
end
it 'returns false when the version is a patch release higher than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.04.4' }
expect(described_class.ubuntu_before_lucid?(node)).to be false
end
it 'returns true when the version is less than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '9.10' }
expect(described_class.ubuntu_before_lucid?(node)).to be true
end
end
describe '#ubuntu_before_or_at_lucid?' do
it 'returns false when the version is later than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.10' }
expect(described_class.ubuntu_before_or_at_lucid?(node)).to be false
end
it 'returns true when the version is 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.04' }
expect(described_class.ubuntu_before_or_at_lucid?(node)).to be true
end
it 'returns true when the version is a patch release higher than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '10.04.4' }
expect(described_class.ubuntu_before_or_at_lucid?(node)).to be true
end
it 'returns true when the version is less than 10.04' do
node = { 'platform' => 'ubuntu', 'platform_version' => '9.10' }
expect(described_class.ubuntu_before_or_at_lucid?(node)).to be true
end
end
describe '#centos_final?' do
it 'returns true when the version is a subset of the major' do
node = { 'platform' => 'centos', 'platform_version' => '6.8' }
expect(described_class.centos_final?(node)).to be true
end
it 'returns false when the version is not the major' do
node = { 'platform' => 'centos', 'platform_version' => '7.4' }
expect(described_class.centos_final?(node)).to be false
end
end
describe '#debian_wheezy?' do
it 'returns true when the version is a subset of the major' do
node = { 'platform' => 'debian', 'platform_version' => '7.1' }
expect(described_class.debian_wheezy?(node)).to be true
end
it 'returns false when the version is not the major' do
node = { 'platform' => 'debian', 'platform_version' => '6.1' }
expect(described_class.debian_wheezy?(node)).to be false
end
end
describe '#debian_before_wheezy?' do
it 'returns true when the version is a less than the major' do
node = { 'platform' => 'debian', 'platform_version' => '6.5' }
expect(described_class.debian_before_wheezy?(node)).to be true
end
it 'returns false when the version is not less than the major' do
node = { 'platform' => 'debian', 'platform_version' => '8.0' }
expect(described_class.debian_before_wheezy?(node)).to be false
end
end
describe '#solaris_10?' do
it 'returns true when the version is 5.10' do
node = { 'platform' => 'solaris2', 'platform_version' => '5.10' }
expect(described_class.solaris_10?(node)).to be true
end
end
describe '#solaris_11?' do
it 'returns true when the version is 5.11' do
node = { 'platform' => 'solaris2', 'platform_version' => '5.11' }
expect(described_class.solaris_11?(node)).to be true
end
end
end
end

View File

@@ -1,39 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::Ruby do
it_behaves_like 'a chef sugar'
describe '#ruby_20?' do
it 'returns true when the ruby version is 2.0' do
node = { 'languages' => { 'ruby' => { 'version' => '2.0.0' } } }
expect(described_class.ruby_20?(node)).to be true
end
it 'returns true when the ruby version is less than 2.0' do
node = { 'languages' => { 'ruby' => { 'version' => '1.9.3' } } }
expect(described_class.ruby_20?(node)).to be false
end
it 'returns false when the ruby version is higher than 2.0' do
node = { 'languages' => { 'ruby' => { 'version' => '3.0.0' } } }
expect(described_class.ruby_20?(node)).to be false
end
end
describe '#ruby_19?' do
it 'returns true when the ruby version is 1.9' do
node = { 'languages' => { 'ruby' => { 'version' => '1.9.1' } } }
expect(described_class.ruby_19?(node)).to be true
end
it 'returns true when the ruby version is less than 1.9' do
node = { 'languages' => { 'ruby' => { 'version' => '1.8.7' } } }
expect(described_class.ruby_19?(node)).to be false
end
it 'returns false when the ruby version is higher than 1.9' do
node = { 'languages' => { 'ruby' => { 'version' => '2.0.0' } } }
expect(described_class.ruby_19?(node)).to be false
end
end
end

View File

@@ -1,19 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::RunContext do
it_behaves_like 'a chef sugar'
describe '#includes_recipe?' do
let(:node) { double(Chef::Node) }
it 'returns true when the recipe exists' do
allow(node).to receive(:recipe?).and_return(true)
expect(described_class.includes_recipe?(node, 'foo')).to be true
end
it 'returns false when the recipe does not exist' do
allow(node).to receive(:recipe?).and_return(false)
expect(described_class.includes_recipe?(node, 'bar')).to be false
end
end
end

View File

@@ -1,104 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::Shell do
describe '#which', :pre_chef16_only do
it 'returns the first executable matching the command' do
allow(File).to receive(:executable?).and_return(false)
allow(File).to receive(:executable?).with('/usr/bin/mongo').and_return(true)
expect(described_class.which('mongo')).to eq('/usr/bin/mongo')
end
it 'returns nil when no command is found' do
allow(File).to receive(:executable?).and_return(false)
expect(described_class.which('node')).to be_nil
end
context 'with an absolute path' do
it 'returns the executable if it exists' do
allow(File).to receive(:executable?).with('/usr/local/bin/bash').and_return(true)
expect(described_class.which('/usr/local/bin/bash')).to eq('/usr/local/bin/bash')
end
it 'returns nil when the file is not executable' do
allow(File).to receive(:executable?).with('/usr/local/bin/bash').and_return(false)
expect(described_class.which('/usr/local/bin/bash')).to be_nil
end
end
end
describe '#dev_null' do
it 'returns NUL on Windows' do
node = { 'platform_family' => 'windows' }
expect(described_class.dev_null(node)).to eq('NUL')
end
it 'returns /dev/null on Linux' do
node = { 'platform_family' => 'debian' }
expect(described_class.dev_null(node)).to eq('/dev/null')
end
end
describe '#installed?' do
it 'returns true if the given binary exists' do
allow(described_class).to receive(:which).and_return(nil)
allow(described_class).to receive(:which).with('mongo').and_return(true)
expect(described_class.installed?('mongo')).to be true
end
it 'returns false if the given binary does not exist' do
allow(described_class).to receive(:which).with('node').and_return(nil)
expect(described_class.installed?('node')).to be false
end
end
describe '#installed_at_version?' do
it 'returns true if the command is installed at the correct version' do
allow(described_class).to receive(:which).and_return(true)
allow(described_class).to receive(:version_for).and_return('1.2.3')
expect(described_class.installed_at_version?('mongo', '1.2.3')).to be true
end
it 'returns true if the command is installed at the correct version and has additional output' do
allow(described_class).to receive(:which).and_return(true)
allow(described_class).to receive(:version_for).and_return('Mongo DB version 1.2.3. Some other text.')
expect(described_class.installed_at_version?('mongo', '1.2.3')).to be true
end
it 'returns true if the command is installed at the correct version with a regex' do
allow(described_class).to receive(:which).and_return(true)
allow(described_class).to receive(:version_for).and_return('1.2.3')
expect(described_class.installed_at_version?('mongo', /1\.2/)).to be true
end
it 'returns false if the command is installed at the wrong version' do
allow(described_class).to receive(:which).and_return(true)
allow(described_class).to receive(:version_for).and_return('1.2.3')
expect(described_class.installed_at_version?('mongo', '4.5.6')).to be false
end
it 'returns false if #version_for is nil' do
allow(described_class).to receive(:which).and_return(true)
allow(described_class).to receive(:version_for).and_return(nil)
expect(described_class.installed_at_version?('mongo', '4.5.6')).to be false
end
it 'returns false if the command is not installed' do
allow(described_class).to receive(:which).and_return(nil)
expect(described_class.installed_at_version?('mongo', '1.0.0')).to be false
end
end
describe '#version_for' do
let(:shell_out) { double('shell_out', run_command: nil, error!: nil, stdout: '1.2.3', stderr: 'Oh no!') }
before { allow(Mixlib::ShellOut).to receive(:new).and_return(shell_out) }
it 'runs the thing in shellout' do
expect(Mixlib::ShellOut).to receive(:new).with('mongo --version')
described_class.version_for('mongo')
end
it 'returns the combined stdout and stderr' do
expect(described_class.version_for('mongo')).to eq("1.2.3\nOh no!")
end
end
end

View File

@@ -1,37 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::Vagrant do
it_behaves_like 'a chef sugar'
describe '#vagrant?' do
it 'returns true when the machine is on vagrant' do
node = { 'vagrant' => {} }
expect(described_class.vagrant?(node)).to be true
end
it 'returns true when the domain is vagrantup.com' do
node = { 'domain' => 'bacon.vagrantup.com' }
expect(described_class.vagrant?(node)).to be true
end
it 'returns false when the domain is nil' do
node = { 'domain' => nil }
expect(described_class.vagrant?(node)).to be false
end
it 'returns false when the domain is not vagrantup.com' do
node = { 'domain' => 'sethvargo.com' }
expect(described_class.vagrant?(node)).to be false
end
it 'returns true when the vagrant user exists on the system' do
node = { 'etc' => { 'passwd' => { 'vagrant' => {} } } }
expect(described_class.vagrant?(node)).to be true
end
it 'returns false when the machine is not on vagrant' do
node = {}
expect(described_class.vagrant?(node)).to be false
end
end
end

View File

@@ -1,135 +0,0 @@
require 'spec_helper'
describe Chef::Sugar::Virtualization do
it_behaves_like 'a chef sugar'
describe '#kvm?' do
it 'returns true when the machine is under kvm' do
node = { 'virtualization' => { 'system' => 'kvm' } }
expect(described_class.kvm?(node)).to be true
end
it 'returns false when the virtual machine is not under kvm' do
node = { 'virtualization' => { 'system' => 'vbox' } }
expect(described_class.kvm?(node)).to be false
end
it 'returns false when the machine is not virtual' do
node = {}
expect(described_class.kvm?(node)).to be false
end
end
describe '#lxc?' do
it 'returns true when the machine is a linux contianer' do
node = { 'virtualization' => { 'system' => 'lxc' } }
expect(described_class.lxc?(node)).to be true
end
it 'returns false when the virtual machine is not lxc' do
node = { 'virtualization' => { 'system' => 'vbox' } }
expect(described_class.lxc?(node)).to be false
end
it 'returns false when the machine is not virtual' do
node = {}
expect(described_class.lxc?(node)).to be false
end
end
describe '#parallels?' do
it 'returns true when the machine is under parallels' do
node = { 'virtualization' => { 'system' => 'parallels' } }
expect(described_class.parallels?(node)).to be true
end
it 'returns false when the virtual machine is not under parallels' do
node = { 'virtualization' => { 'system' => 'kvm' } }
expect(described_class.parallels?(node)).to be false
end
it 'returns false when the machine is not virtual' do
node = {}
expect(described_class.parallels?(node)).to be false
end
end
describe '#virtualbox?' do
it 'returns true when the machine is under virtualbox' do
node = { 'virtualization' => { 'system' => 'vbox' } }
expect(described_class.virtualbox?(node)).to be true
end
it 'returns false when the virtual machine is not under virtualbox' do
node = { 'virtualization' => { 'system' => 'kvm' } }
expect(described_class.virtualbox?(node)).to be false
end
it 'returns false when the machine is not virtual' do
node = {}
expect(described_class.virtualbox?(node)).to be false
end
end
describe '#vmware?' do
it 'returns true when the machine is under vmware' do
node = { 'virtualization' => { 'system' => 'vmware' } }
expect(described_class.vmware?(node)).to be true
end
it 'returns false when the virtual machine is not under vmware' do
node = { 'virtualization' => { 'system' => 'vbox' } }
expect(described_class.vmware?(node)).to be false
end
it 'returns false when the machine is not virtual' do
node = {}
expect(described_class.vmware?(node)).to be false
end
end
describe '#openvz?' do
it 'returns true when the machine is under openvz' do
node = { 'virtualization' => { 'system' => 'openvz' } }
expect(described_class.openvz?(node)).to be true
end
it 'returns false when the virtual machine is not under openvz' do
node = { 'virtualization' => { 'system' => 'kvm' } }
expect(described_class.openvz?(node)).to be false
end
it 'returns false when the machine is not virtual' do
node = {}
expect(described_class.openvz?(node)).to be false
end
end
describe '#virtual?' do
it 'returns true when the machine is under a supported virtualization provider' do
%w(openvz vmware vbox lxc kvm).each do |host|
node = { 'virtualization' => { 'system' => host } }
expect(described_class.virtual?(node)).to be true
end
end
it 'returns false when the machine is not virtual' do
node = {}
expect(described_class.virtual?(node)).to be false
end
end
describe '#physical?' do
it 'returns false when the machine is under a supported virtualization provider' do
%w(openvz vmware vbox lxc kvm).each do |host|
node = { 'virtualization' => { 'system' => host } }
expect(described_class.physical?(node)).to be false
end
end
it 'returns true when the machine is not virtual' do
node = {}
expect(described_class.physical?(node)).to be true
end
end
end

View File

@@ -1,9 +0,0 @@
require 'spec_helper'
describe 'chef-sugar::default' do
let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04').converge(described_recipe) }
it 'converges successfully' do
expect { :chef_run }.to_not raise_error
end
end

View File

@@ -1,53 +0,0 @@
# compat_resource Cookbook CHANGELOG
This file is used to list changes made in each version of the compat_resource cookbook.
## 12.19.0 (2017-04-17)
- Suppress warning already initialized constant
- Backport yum/apt changes from 12.19
## 12.16.2 (2016-11-09)
- Sync chef-client changes from Chef 12.16.42
## 12.16.1 (2016-10-20)
- add delayed_action helper
## 12.16.0 (2016-10-19)
- Sync chef-client changes from Chef 12.16.14
## 12.14.7 (2016-09-26)
- Update to 12.14.89 Chef
- Fix autoload by applying fix from #106
## 12.14.6 (2016-09-20)
- Update backported codebase to Chef 12.14.77 which brings in yum_repository updates and why-run enabled by default in custom resources
## 12.14.5 (2016-09-19)
- Prevent spamming messages in Chefspec runs for cookbooks that depend on compat_resource
## 12.14.4 (2016-09-19)
- Fix delayed notifications cloning
## 12.14.3 (2016-09-12)
- Fix subscribes notifications
## 12.14.2 (2016-09-09)
- Improve documentation
- keep ChefCompat::Resource defined even if we don't load
## 12.14.1 (2016-09-07)
- add yum_repository resource from Chef 12.14
- Update the minimum chef version in the metadata to 12.1
- Added maintainers files
- suppress constant redef warnings when running chefspec

View File

@@ -1,2 +0,0 @@
Please refer to
https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/CONTRIBUTING.MD

View File

@@ -1,16 +0,0 @@
<!-- This is a generated file. Please do not edit directly -->
# Maintainers
This file lists how this cookbook project is maintained. When making changes to the system, this file tells you who needs to review your patch - you need a review from an existing maintainer for the cookbook to provide a :+1: on your pull request. Additionally, you need to not receive a veto from a Lieutenant or the Project Lead.
Check out [How Cookbooks are Maintained](https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/CONTRIBUTING.MD) for details on the process and how to become a maintainer or the project lead.
# Project Maintainer
* [Lamont Granquist](https://github.com/lamont-granquist)
# Maintainers
* [Jennifer Davis](https://github.com/sigje)
* [Tim Smith](https://github.com/tas50)
* [Thom May](https://github.com/thommay)
* [Lamont Granquist](https://github.com/lamont-granquist)

View File

@@ -1,60 +0,0 @@
# compat_resource cookbook
[![Build Status](https://travis-ci.org/chef-cookbooks/compat_resource.svg?branch=master)](https://travis-ci.org/chef-cookbooks/compat_resource) [![Cookbook Version](https://img.shields.io/cookbook/v/compat_resource.svg)](https://supermarket.chef.io/cookbooks/compat_resource)
This cookbook backports functionality introduced in the latest chef-client releases to any chef-client from 12.1 onwards. This includes [Custom Resource](https://docs.chef.io/custom_resources.html) functionality, notification improvements, as well as new resources added to core chef. It allows for the usage of these new resources in cookbooks without requiring the very latest Chef client release.
## Backported functionality
- [Custom Resources](https://docs.chef.io/custom_resources.html)
- [apt_repository](https://docs.chef.io/resource_apt_repository.html)
- [apt_update](https://docs.chef.io/resource_apt_update.html)
- [systemd_unit](https://docs.chef.io/resource_systemd_unit.html)
- [yum_repository](https://docs.chef.io/resource_yum_repository.html)
- [:before notifications](https://docs.chef.io/resources.html#timers)
## Requirements
### Platforms
- All platforms supported by Chef
### Chef
- Chef 12.1+
### Cookbooks
- none
## Usage
To use this cookbook, put `depends 'compat_resource'` in the metadata.rb of your cookbook. Once this is done, you can use all the new custom resource features to define resources. It Just Works.
## Custom Resources?
Curious about how to use custom resources?
- Docs: <https://docs.chef.io/custom_resources.html>
- Slides: <https://docs.chef.io/decks/custom_resources.html>
## License & Authors
- Author:: Lamont Granquist ([lamont@chef.io](mailto:lamont@chef.io))
- Author:: John Keiser ([jkeiser@chef.io](mailto:jkeiser@chef.io))
```text
Copyright:: 2015-2016 Chef Software, Inc.
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.
```

View File

@@ -1,29 +0,0 @@
module ChefCompat
module CopiedFromChef
def self.extend_chef_module(chef_module, target)
target.instance_eval do
include chef_module
@chef_module = chef_module
def self.method_missing(name, *args, &block)
@chef_module.send(name, *args, &block)
end
def self.const_missing(name)
@chef_module.const_get(name)
end
end
end
# This patch to CopiedFromChef's ActionClass is necessary for the include to work
require 'chef/resource'
class Chef < ::Chef
class Resource < ::Chef::Resource
module ActionClass
def self.use_inline_resources
end
def self.include_resource_dsl(include_resource_dsl)
end
end
end
end
end
end

View File

@@ -1,47 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/constants'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: John Keiser <jkeiser@chef.io>
# Copyright:: Copyright 2015-2016, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# 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.
class Chef < (defined?(::Chef) ? ::Chef : Object)
NOT_PASSED = Object.new
def NOT_PASSED.to_s
"NOT_PASSED"
end
def NOT_PASSED.inspect
to_s
end
NOT_PASSED.freeze
end
end
end
end

View File

@@ -1,40 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/delayed_evaluator'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: John Keiser <jkeiser@chef.io>
# Copyright:: Copyright 2015-2016, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# 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.
class Chef < (defined?(::Chef) ? ::Chef : Object)
class DelayedEvaluator < (defined?(::Chef::DelayedEvaluator) ? ::Chef::DelayedEvaluator : Proc)
end
end
end
end
end

View File

@@ -1,73 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/dsl/core'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#--
# Author:: Adam Jacob (<adam@chef.io>)
# Author:: Christopher Walters (<cw@chef.io>)
# Copyright:: Copyright 2008-2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/dsl/declare_resource"
require "chef_compat/copied_from_chef/chef/dsl/universal"
require "chef_compat/copied_from_chef/chef/mixin/notifying_block"
require "chef_compat/copied_from_chef/chef/mixin/lazy_module_include"
class Chef < (defined?(::Chef) ? ::Chef : Object)
module DSL
CopiedFromChef.extend_chef_module(::Chef::DSL, self) if defined?(::Chef::DSL)
# Part of a family of DSL mixins.
#
# Chef::DSL::Recipe mixes into Recipes and LWRP Providers.
# - this does not target core chef resources and providers.
# - this is restricted to recipe/resource/provider context where a resource collection exists.
# - cookbook authors should typically include modules into here.
#
# Chef::DSL::Core mixes into Recipes, LWRP Providers and Core Providers
# - this adds cores providers on top of the Recipe DSL.
# - this is restricted to recipe/resource/provider context where a resource collection exists.
# - core chef authors should typically include modules into here.
#
# Chef::DSL::Universal mixes into Recipes, LWRP Resources+Providers, Core Resources+Providers, and Attributes files.
# - this adds resources and attributes files.
# - do not add helpers which manipulate the resource collection.
# - this is for general-purpose stuff that is useful nearly everywhere.
# - it also pollutes the namespace of nearly every context, watch out.
#
module Core
CopiedFromChef.extend_chef_module(::Chef::DSL::Core, self) if defined?(::Chef::DSL::Core)
include Chef::DSL::Universal
include Chef::DSL::DeclareResource
include Chef::Mixin::NotifyingBlock
extend Chef::Mixin::LazyModuleInclude
end
end
end
end
end
end

View File

@@ -1,315 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/dsl/declare_resource'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#--
# Author:: Adam Jacob (<adam@chef.io>)
# Author:: Christopher Walters
# Copyright:: Copyright 2008-2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
class Chef < (defined?(::Chef) ? ::Chef : Object)
module DSL
CopiedFromChef.extend_chef_module(::Chef::DSL, self) if defined?(::Chef::DSL)
module DeclareResource
CopiedFromChef.extend_chef_module(::Chef::DSL::DeclareResource, self) if defined?(::Chef::DSL::DeclareResource)
# Helper for switching run_contexts. Allows for using :parent or :root in place of
# passing the run_context. Executes the block in the run_context. Returns the return
# value of the passed block.
#
# @param rc [Chef::RunContext,Symbol] Either :root, :parent or a Chef::RunContext
#
# @return return value of the block
#
# @example
# # creates/returns a 'service[foo]' resource in the root run_context
# resource = with_run_context(:root)
# edit_resource(:service, "foo") do
# action :nothing
# end
# end
#
def with_run_context(rc)
raise ArgumentError, "with_run_context is useless without a block" unless block_given?
old_run_context = @run_context
@run_context =
case rc
when Chef::RunContext
rc
when :root
run_context.root_run_context
when :parent
run_context.parent_run_context
else
raise ArgumentError, "bad argument to run_context helper, must be :root, :parent, or a Chef::RunContext"
end
yield
ensure
@run_context = old_run_context
end
# Lookup a resource in the resource collection by name and delete it. This
# will raise Chef::Exceptions::ResourceNotFound if the resource is not found.
#
# @param type [Symbol] The type of resource (e.g. `:file` or `:package`)
# @param name [String] The name of the resource (e.g. '/x/y.txt' or 'apache2')
# @param run_context [Chef::RunContext] the run_context of the resource collection to operate on
#
# @return [Chef::Resource] The resource
#
# @example
# delete_resource!(:template, '/x/y.txy')
#
def delete_resource!(type, name, run_context: self.run_context)
run_context.resource_collection.delete("#{type}[#{name}]").tap do |resource|
# Purge any pending notifications too. This will not raise an exception
# if there are no notifications.
if resource
run_context.before_notification_collection.delete(resource.declared_key)
run_context.immediate_notification_collection.delete(resource.declared_key)
run_context.delayed_notification_collection.delete(resource.declared_key)
end
end
end
# Lookup a resource in the resource collection by name and delete it. Returns
# nil if the resource is not found and should not fail.
#
# @param type [Symbol] The type of resource (e.g. `:file` or `:package`)
# @param name [String] The name of the resource (e.g. '/x/y.txt' or 'apache2')
# @param run_context [Chef::RunContext] the run_context of the resource collection to operate on
#
# @return [Chef::Resource] The resource
#
# @example
# delete_resource(:template, '/x/y.txy')
#
def delete_resource(type, name, run_context: self.run_context)
delete_resource!(type, name, run_context: run_context)
rescue Chef::Exceptions::ResourceNotFound
nil
end
# Lookup a resource in the resource collection by name and edit the resource. If the resource is not
# found this will raise Chef::Exceptions::ResourceNotFound. This is the correct API to use for
# "chef_rewind" functionality.
#
# @param type [Symbol] The type of resource (e.g. `:file` or `:package`)
# @param name [String] The name of the resource (e.g. '/x/y.txt' or 'apache2')
# @param run_context [Chef::RunContext] the run_context of the resource collection to operate on
# @param resource_attrs_block A block that lets you set attributes of the
# resource (it is instance_eval'd on the resource instance).
#
# @return [Chef::Resource] The updated resource
#
# @example
# edit_resource!(:template, '/x/y.txy') do
# cookbook_name: cookbook_name
# end
#
def edit_resource!(type, name, created_at = nil, run_context: self.run_context, &resource_attrs_block)
resource = find_resource!(type, name, run_context: run_context)
if resource_attrs_block
if defined?(new_resource)
resource.instance_exec(new_resource, &resource_attrs_block)
else
resource.instance_exec(&resource_attrs_block)
end
end
resource
end
# Lookup a resource in the resource collection by name. If it exists,
# return it. If it does not exist, create it. This is a useful function
# for accumulator patterns. In CRUD terminology this is an "upsert" operation and is
# used to assert that the resource must exist with the specified properties.
#
# @param type [Symbol] The type of resource (e.g. `:file` or `:package`)
# @param name [String] The name of the resource (e.g. '/x/y.txt' or 'apache2')
# @param created_at [String] The caller of the resource. Use `caller[0]`
# to get the caller of your function. Defaults to the caller of this
# function.
# @param run_context [Chef::RunContext] the run_context of the resource collection to operate on
# @param resource_attrs_block A block that lets you set attributes of the
# resource (it is instance_eval'd on the resource instance).
#
# @return [Chef::Resource] The updated or created resource
#
# @example
# resource = edit_resource(:template, '/x/y.txy') do
# source "y.txy.erb"
# variables {}
# end
# resource.variables.merge!({ home: "/home/klowns" })
#
def edit_resource(type, name, created_at = nil, run_context: self.run_context, &resource_attrs_block)
edit_resource!(type, name, created_at, run_context: run_context, &resource_attrs_block)
rescue Chef::Exceptions::ResourceNotFound
declare_resource(type, name, created_at, run_context: run_context, &resource_attrs_block)
end
# Lookup a resource in the resource collection by name. If the resource is not
# found this will raise Chef::Exceptions::ResourceNotFound. This API is identical to the
# resources() call and while it is a synonym it is not intended to deprecate that call.
#
# @param type [Symbol] The type of resource (e.g. `:file` or `:package`)
# @param name [String] The name of the resource (e.g. '/x/y.txt' or 'apache2')
# @param run_context [Chef::RunContext] the run_context of the resource collection to operate on
#
# @return [Chef::Resource] The updated resource
#
# @example
# resource = find_resource!(:template, '/x/y.txy')
#
def find_resource!(type, name, run_context: self.run_context)
raise ArgumentError, "find_resource! does not take a block" if block_given?
run_context.resource_collection.find(type => name)
end
# Lookup a resource in the resource collection by name. If the resource is not found
# the will be no exception raised and the call will return nil. If a block is given and
# no resource is found it will create the resource using the block, if the resource is
# found then the block will not be applied. The block version is similar to create_if_missing
#
# @param type [Symbol] The type of resource (e.g. `:file` or `:package`)
# @param name [String] The name of the resource (e.g. '/x/y.txt' or 'apache2')
# @param run_context [Chef::RunContext] the run_context of the resource collection to operate on
#
# @return [Chef::Resource] The updated resource
#
# @example
# if ( find_resource(:template, '/x/y.txy') )
# # do something
# else
# # don't worry about the error
# end
#
# @example
# # this API can be used to return a resource from an outer run context, and will only create
# # an action :nothing service if one does not already exist.
# resource = with_run_context(:root) do
# find_resource(:service, 'whatever') do
# action :nothing
# end
# end
#
def find_resource(type, name, created_at: nil, run_context: self.run_context, &resource_attrs_block)
find_resource!(type, name, run_context: run_context)
rescue Chef::Exceptions::ResourceNotFound
if resource_attrs_block
declare_resource(type, name, created_at, run_context: run_context, &resource_attrs_block)
end # returns nil otherwise
end
# Instantiates a resource (via #build_resource), then adds it to the
# resource collection. Note that resource classes are looked up directly,
# so this will create the resource you intended even if the method name
# corresponding to that resource has been overridden.
#
# @param type [Symbol] The type of resource (e.g. `:file` or `:package`)
# @param name [String] The name of the resource (e.g. '/x/y.txt' or 'apache2')
# @param created_at [String] The caller of the resource. Use `caller[0]`
# to get the caller of your function. Defaults to the caller of this
# function.
# @param run_context [Chef::RunContext] the run_context of the resource collection to operate on
# @param resource_attrs_block A block that lets you set attributes of the
# resource (it is instance_eval'd on the resource instance).
#
# @return [Chef::Resource] The new resource.
#
# @example
# declare_resource(:file, '/x/y.txy', caller[0]) do
# action :delete
# end
# # Equivalent to
# file '/x/y.txt' do
# action :delete
# end
#
def declare_resource(type, name, created_at = nil, run_context: self.run_context, create_if_missing: false, &resource_attrs_block)
created_at ||= caller[0]
if create_if_missing
Chef::Log.deprecation "build_resource with a create_if_missing flag is deprecated, use edit_resource instead"
# midly goofy since we call edit_resource only to re-call ourselves, but that's why its deprecated...
return edit_resource(type, name, created_at, run_context: run_context, &resource_attrs_block)
end
resource = build_resource(type, name, created_at, &resource_attrs_block)
run_context.resource_collection.insert(resource, resource_type: type, instance_name: name)
resource
end
# Instantiate a resource of the given +type+ with the given +name+ and
# attributes as given in the +resource_attrs_block+.
#
# The resource is NOT added to the resource collection.
#
# @param type [Symbol] The type of resource (e.g. `:file` or `:package`)
# @param name [String] The name of the resource (e.g. '/x/y.txt' or 'apache2')
# @param created_at [String] The caller of the resource. Use `caller[0]`
# to get the caller of your function. Defaults to the caller of this
# function.
# @param run_context [Chef::RunContext] the run_context of the resource collection to operate on
# @param resource_attrs_block A block that lets you set attributes of the
# resource (it is instance_eval'd on the resource instance).
#
# @return [Chef::Resource] The new resource.
#
# @example
# build_resource(:file, '/x/y.txy', caller[0]) do
# action :delete
# end
#
def build_resource(type, name, created_at = nil, run_context: self.run_context, &resource_attrs_block)
created_at ||= caller[0]
# this needs to be lazy in order to avoid circular dependencies since ResourceBuilder
# will requires the entire provider+resolver universe
require "chef_compat/copied_from_chef/chef/resource_builder" unless defined?(Chef::ResourceBuilder)
Chef::ResourceBuilder.new(
type: type,
name: name,
created_at: created_at,
params: @params,
run_context: run_context,
cookbook_name: cookbook_name,
recipe_name: recipe_name,
enclosing_provider: self.is_a?(Chef::Provider) ? self : nil
).build(&resource_attrs_block)
end
end
end
end
end
end
end

View File

@@ -1,292 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/dsl/platform_introspection'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Adam Jacob (<adam@chef.io>)
# Copyright:: Copyright 2008-2016, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
class Chef < (defined?(::Chef) ? ::Chef : Object)
module DSL
CopiedFromChef.extend_chef_module(::Chef::DSL, self) if defined?(::Chef::DSL)
# == Chef::DSL::PlatformIntrospection
# Provides the DSL for platform-dependent switch logic, such as
# #value_for_platform.
module PlatformIntrospection
CopiedFromChef.extend_chef_module(::Chef::DSL::PlatformIntrospection, self) if defined?(::Chef::DSL::PlatformIntrospection)
# Implementation class for determining platform dependent values
class PlatformDependentValue < (defined?(::Chef::DSL::PlatformIntrospection::PlatformDependentValue) ? ::Chef::DSL::PlatformIntrospection::PlatformDependentValue : Object)
# Create a platform dependent value object.
# === Arguments
# platform_hash (Hash) a hash of the same structure as Chef::Platform,
# like this:
# {
# :debian => {:default => 'the value for all debian'}
# [:centos, :redhat, :fedora] => {:default => "value for all EL variants"}
# :ubuntu => { :default => "default for ubuntu", '10.04' => "value for 10.04 only"},
# :default => "the default when nothing else matches"
# }
# * platforms can be specified as Symbols or Strings
# * multiple platforms can be grouped by using an Array as the key
# * values for platforms need to be Hashes of the form:
# {platform_version => value_for_that_version}
# * the exception to the above is the default value, which is given as
# :default => default_value
def initialize(platform_hash)
super if defined?(::Chef::DSL::PlatformIntrospection::PlatformDependentValue)
@values = {}
platform_hash.each { |platforms, value| set(platforms, value) }
end
def value_for_node(node)
platform, version = node[:platform].to_s, node[:platform_version].to_s
# Check if we match a version constraint via Chef::VersionConstraint::Platform and Chef::Version::Platform
matched_value = match_versions(node)
if @values.key?(platform) && @values[platform].key?(version)
@values[platform][version]
elsif matched_value
matched_value
elsif @values.key?(platform) && @values[platform].key?("default")
@values[platform]["default"]
elsif @values.key?("default")
@values["default"]
else
nil
end
end
private
def match_versions(node)
begin
platform, version = node[:platform].to_s, node[:platform_version].to_s
return nil unless @values.key?(platform)
node_version = Chef::Version::Platform.new(version)
key_matches = []
keys = @values[platform].keys
keys.each do |k|
begin
if Chef::VersionConstraint::Platform.new(k).include?(node_version)
key_matches << k
end
rescue Chef::Exceptions::InvalidVersionConstraint => e
Chef::Log.debug "Caught InvalidVersionConstraint. This means that a key in value_for_platform cannot be interpreted as a Chef::VersionConstraint::Platform."
Chef::Log.debug(e)
end
end
return @values[platform][version] if key_matches.include?(version)
case key_matches.length
when 0
return nil
when 1
return @values[platform][key_matches.first]
else
raise "Multiple matches detected for #{platform} with values #{@values}. The matches are: #{key_matches}"
end
rescue Chef::Exceptions::InvalidCookbookVersion => e
# Lets not break because someone passes a weird string like 'default' :)
Chef::Log.debug(e)
Chef::Log.debug "InvalidCookbookVersion exceptions are common and expected here: the generic constraint matcher attempted to match something which is not a constraint. Moving on to next version or constraint"
return nil
rescue Chef::Exceptions::InvalidPlatformVersion => e
Chef::Log.debug "Caught InvalidPlatformVersion, this means that Chef::Version::Platform does not know how to turn #{node_version} into an x.y.z format"
Chef::Log.debug(e)
return nil
end
end
def set(platforms, value)
if platforms.to_s == "default"
@values["default"] = value
else
assert_valid_platform_values!(platforms, value)
Array(platforms).each { |platform| @values[platform.to_s] = normalize_keys(value) }
value
end
end
def normalize_keys(hash)
hash.inject({}) do |h, key_value|
keys, value = *key_value
Array(keys).each do |key|
h[key.to_s] = value
end
h
end
end
def assert_valid_platform_values!(platforms, value)
unless value.kind_of?(Hash)
msg = "platform dependent values must be specified in the format :platform => {:version => value} "
msg << "you gave a value #{value.inspect} for platform(s) #{platforms}"
raise ArgumentError, msg
end
end
end
# Given a hash similar to the one we use for Platforms, select a value from the hash. Supports
# per platform defaults, along with a single base default. Arrays may be passed as hash keys and
# will be expanded.
#
# === Parameters
# platform_hash:: A platform-style hash.
#
# === Returns
# value:: Whatever the most specific value of the hash is.
def value_for_platform(platform_hash)
PlatformDependentValue.new(platform_hash).value_for_node(node)
end
# Given a list of platforms, returns true if the current recipe is being run on a node with
# that platform, false otherwise.
#
# === Parameters
# args:: A list of platforms. Each platform can be in string or symbol format.
#
# === Returns
# true:: If the current platform is in the list
# false:: If the current platform is not in the list
def platform?(*args)
has_platform = false
args.flatten.each do |platform|
has_platform = true if platform.to_s == node[:platform]
end
has_platform
end
# Implementation class for determining platform family dependent values
class PlatformFamilyDependentValue < (defined?(::Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue) ? ::Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue : Object)
# Create a platform family dependent value object.
# === Arguments
# platform_family_hash (Hash) a map of platform families to values.
# like this:
# {
# :rhel => "value for all EL variants"
# :fedora => "value for fedora variants fedora and amazon" ,
# [:fedora, :rhel] => "value for all known redhat variants"
# :debian => "value for debian variants including debian, ubuntu, mint" ,
# :default => "the default when nothing else matches"
# }
# * platform families can be specified as Symbols or Strings
# * multiple platform families can be grouped by using an Array as the key
# * values for platform families can be any object, with no restrictions. Some examples:
# - [:stop, :start]
# - "mysql-devel"
# - { :key => "value" }
def initialize(platform_family_hash)
super if defined?(::Chef::DSL::PlatformIntrospection::PlatformFamilyDependentValue)
@values = {}
@values["default"] = nil
platform_family_hash.each { |platform_families, value| set(platform_families, value) }
end
def value_for_node(node)
if node.key?(:platform_family)
platform_family = node[:platform_family].to_s
if @values.key?(platform_family)
@values[platform_family]
else
@values["default"]
end
else
@values["default"]
end
end
private
def set(platform_family, value)
if platform_family.to_s == "default"
@values["default"] = value
else
Array(platform_family).each { |family| @values[family.to_s] = value }
value
end
end
end
# Given a hash mapping platform families to values, select a value from the hash. Supports a single
# base default if platform family is not in the map. Arrays may be passed as hash keys and will be
# expanded
#
# === Parameters
# platform_family_hash:: A hash in the form { platform_family_name => value }
#
# === Returns
# value:: Whatever the most specific value of the hash is.
def value_for_platform_family(platform_family_hash)
PlatformFamilyDependentValue.new(platform_family_hash).value_for_node(node)
end
# Given a list of platform families, returns true if the current recipe is being run on a
# node within that platform family, false otherwise.
#
# === Parameters
# args:: A list of platform families. Each platform family can be in string or symbol format.
#
# === Returns
# true:: if the current node platform family is in the list.
# false:: if the current node platform family is not in the list.
def platform_family?(*args)
args.flatten.any? do |platform_family|
platform_family.to_s == node[:platform_family]
end
end
# Shamelessly stolen from https://github.com/sethvargo/chef-sugar/blob/master/lib/chef/sugar/docker.rb
# Given a node object, returns whether the node is a docker container.
#
# === Parameters
# node:: [Chef::Node] The node to check.
#
# === Returns
# true:: if the current node is a docker container
# false:: if the current node is not a docker container
def docker?(node = run_context.nil? ? nil : run_context.node)
# Using "File.exist?('/.dockerinit') || File.exist?('/.dockerenv')" makes Travis sad,
# and that makes us sad too.
node && node[:virtualization] && node[:virtualization][:systems] &&
node[:virtualization][:systems][:docker] && node[:virtualization][:systems][:docker] == "guest"
end
end
end
end
# **DEPRECATED**
# This used to be part of chef/mixin/language. Load the file to activate the deprecation code.
end
end
end

View File

@@ -1,37 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/dsl/recipe'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
require "chef_compat/copied_from_chef/chef/dsl/core"
require "chef_compat/copied_from_chef/chef/mixin/lazy_module_include"
class Chef < (defined?(::Chef) ? ::Chef : Object)
module DSL
CopiedFromChef.extend_chef_module(::Chef::DSL, self) if defined?(::Chef::DSL)
module Recipe
CopiedFromChef.extend_chef_module(::Chef::DSL::Recipe, self) if defined?(::Chef::DSL::Recipe)
include Chef::DSL::Core
extend Chef::Mixin::LazyModuleInclude
module FullDSL
CopiedFromChef.extend_chef_module(::Chef::DSL::Recipe::FullDSL, self) if defined?(::Chef::DSL::Recipe::FullDSL)
include Chef::DSL::Recipe
extend Chef::Mixin::LazyModuleInclude
end
end
end
end
require "chef_compat/copied_from_chef/chef/resource"
end
end
end

View File

@@ -1,70 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/dsl/universal'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#--
# Author:: Adam Jacob (<adam@chef.io>)
# Author:: Christopher Walters (<cw@chef.io>)
# Copyright:: Copyright 2008-2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/dsl/platform_introspection"
require "chef_compat/copied_from_chef/chef/mixin/powershell_out"
class Chef < (defined?(::Chef) ? ::Chef : Object)
module DSL
CopiedFromChef.extend_chef_module(::Chef::DSL, self) if defined?(::Chef::DSL)
# Part of a family of DSL mixins.
#
# Chef::DSL::Recipe mixes into Recipes and LWRP Providers.
# - this does not target core chef resources and providers.
# - this is restricted to recipe/resource/provider context where a resource collection exists.
# - cookbook authors should typically include modules into here.
#
# Chef::DSL::Core mixes into Recipes, LWRP Providers and Core Providers
# - this adds cores providers on top of the Recipe DSL.
# - this is restricted to recipe/resource/provider context where a resource collection exists.
# - core chef authors should typically include modules into here.
#
# Chef::DSL::Universal mixes into Recipes, LWRP Resources+Providers, Core Resources+Providers, and Attributes files.
# - this adds resources and attributes files.
# - do not add helpers which manipulate the resource collection.
# - this is for general-purpose stuff that is useful nearly everywhere.
# - it also pollutes the namespace of nearly every context, watch out.
#
module Universal
CopiedFromChef.extend_chef_module(::Chef::DSL::Universal, self) if defined?(::Chef::DSL::Universal)
include Chef::DSL::PlatformIntrospection
include Chef::Mixin::PowershellOut
include Chef::Mixin::ShellOut
end
end
end
end
end
end

View File

@@ -1,98 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/mixin/lazy_module_include'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Copyright:: Copyright 2011-2016, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
class Chef < (defined?(::Chef) ? ::Chef : Object)
module Mixin
CopiedFromChef.extend_chef_module(::Chef::Mixin, self) if defined?(::Chef::Mixin)
# If you have:
#
# module A
# extend LazyModuleInclude
# end
#
# module B
# include A
# end
#
# module C
# include B
# end
#
# module Monkeypatches
# def monkey
# puts "monkey!"
# end
# end
#
# A.send(:include, Monkeypatches)
#
# Then B and C and any classes that they're included in will also get the #monkey method patched into them.
#
module LazyModuleInclude
CopiedFromChef.extend_chef_module(::Chef::Mixin::LazyModuleInclude, self) if defined?(::Chef::Mixin::LazyModuleInclude)
# Most of the magick is in this hook which creates a closure over the parent class and then builds an
# "infector" module which infects all descendants and which is responsible for updating the list of
# descendants in the parent class.
def included(klass)
super
parent_klass = self
infector = Module.new do
define_method(:included) do |subklass|
super(subklass)
subklass.extend(infector)
parent_klass.descendants.push(subklass)
end
end
klass.extend(infector)
parent_klass.descendants.push(klass)
end
def descendants
@descendants ||= []
end
def include(*classes)
super
classes.each do |klass|
descendants.each do |descendant|
descendant.send(:include, klass)
end
end
end
end
end
end
end
end
end

View File

@@ -1,74 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/mixin/notifying_block'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#--
# Author:: Lamont Granquist <lamont@chef.io>
# Copyright:: Copyright 2010-2016, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# 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.
class Chef < (defined?(::Chef) ? ::Chef : Object)
module Mixin
CopiedFromChef.extend_chef_module(::Chef::Mixin, self) if defined?(::Chef::Mixin)
module NotifyingBlock
CopiedFromChef.extend_chef_module(::Chef::Mixin::NotifyingBlock, self) if defined?(::Chef::Mixin::NotifyingBlock)
def notifying_block(&block)
begin
subcontext = subcontext_block(&block)
Chef::Runner.new(subcontext).converge
ensure
# recipes don't have a new_resource
if respond_to?(:new_resource)
if subcontext && subcontext.resource_collection.any?(&:updated?)
new_resource.updated_by_last_action(true)
end
end
end
end
def subcontext_block(parent_context = nil, &block)
parent_context ||= @run_context
sub_run_context = parent_context.create_child
begin
outer_run_context = @run_context
@run_context = sub_run_context
instance_eval(&block)
ensure
@run_context = outer_run_context
end
sub_run_context
end
end
end
end
end
end
end

View File

@@ -1,510 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/mixin/params_validate'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Adam Jacob (<adam@chef.io>)
# Copyright:: Copyright 2008-2016, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/constants"
require "chef_compat/copied_from_chef/chef/property"
require "chef_compat/copied_from_chef/chef/delayed_evaluator"
class Chef < (defined?(::Chef) ? ::Chef : Object)
module Mixin
CopiedFromChef.extend_chef_module(::Chef::Mixin, self) if defined?(::Chef::Mixin)
module ParamsValidate
CopiedFromChef.extend_chef_module(::Chef::Mixin::ParamsValidate, self) if defined?(::Chef::Mixin::ParamsValidate)
# Takes a hash of options, along with a map to validate them. Returns the original
# options hash, plus any changes that might have been made (through things like setting
# default values in the validation map)
#
# For example:
#
# validate({ :one => "neat" }, { :one => { :kind_of => String }})
#
# Would raise an exception if the value of :one above is not a kind_of? string. Valid
# map options are:
#
# @param opts [Hash<Symbol,Object>] Validation opts.
# @option opts [Object,Array] :is An object, or list of
# objects, that must match the value using Ruby's `===` operator
# (`opts[:is].any? { |v| v === value }`). (See #_pv_is.)
# @option opts [Object,Array] :equal_to An object, or list
# of objects, that must be equal to the value using Ruby's `==`
# operator (`opts[:is].any? { |v| v == value }`) (See #_pv_equal_to.)
# @option opts [Regexp,Array<Regexp>] :regex An object, or
# list of objects, that must match the value with `regex.match(value)`.
# (See #_pv_regex)
# @option opts [Class,Array<Class>] :kind_of A class, or
# list of classes, that the value must be an instance of. (See
# #_pv_kind_of.)
# @option opts [Hash<String,Proc>] :callbacks A hash of
# messages -> procs, all of which match the value. The proc must
# return a truthy or falsey value (true means it matches). (See
# #_pv_callbacks.)
# @option opts [Symbol,Array<Symbol>] :respond_to A method
# name, or list of method names, the value must respond to. (See
# #_pv_respond_to.)
# @option opts [Symbol,Array<Symbol>] :cannot_be A property,
# or a list of properties, that the value cannot have (such as `:nil` or
# `:empty`). The method with a questionmark at the end is called on the
# value (e.g. `value.empty?`). If the value does not have this method,
# it is considered valid (i.e. if you don't respond to `empty?` we
# assume you are not empty). (See #_pv_cannot_be.)
# @option opts [Proc] :coerce A proc which will be called to
# transform the user input to canonical form. The value is passed in,
# and the transformed value returned as output. Lazy values will *not*
# be passed to this method until after they are evaluated. Called in the
# context of the resource (meaning you can access other properties).
# (See #_pv_coerce.) (See #_pv_coerce.)
# @option opts [Boolean] :required `true` if this property
# must be present and not `nil`; `false` otherwise. This is checked
# after the resource is fully initialized. (See #_pv_required.)
# @option opts [Boolean] :name_property `true` if this
# property defaults to the same value as `name`. Equivalent to
# `default: lazy { name }`, except that #property_is_set? will
# return `true` if the property is set *or* if `name` is set. (See
# #_pv_name_property.)
# @option opts [Boolean] :name_attribute Same as `name_property`.
# @option opts [Object] :default The value this property
# will return if the user does not set one. If this is `lazy`, it will
# be run in the context of the instance (and able to access other
# properties). (See #_pv_default.)
#
def validate(opts, map)
map = map.validation_options if map.is_a?(Property)
#--
# validate works by taking the keys in the validation map, assuming it's a hash, and
# looking for _pv_:symbol as methods. Assuming it find them, it calls the right
# one.
#++
raise ArgumentError, "Options must be a hash" unless opts.kind_of?(Hash)
raise ArgumentError, "Validation Map must be a hash" unless map.kind_of?(Hash)
map.each do |key, validation|
unless key.kind_of?(Symbol) || key.kind_of?(String)
raise ArgumentError, "Validation map keys must be symbols or strings!"
end
case validation
when true
_pv_required(opts, key)
when false
true
when Hash
validation.each do |check, carg|
check_method = "_pv_#{check}"
if self.respond_to?(check_method, true)
self.send(check_method, opts, key, carg)
else
raise ArgumentError, "Validation map has unknown check: #{check}"
end
end
end
end
opts
end
def lazy(&block)
DelayedEvaluator.new(&block)
end
def set_or_return(symbol, value, validation)
property = SetOrReturnProperty.new(name: symbol, **validation)
property.call(self, value)
end
private
def explicitly_allows_nil?(key, validation)
validation.has_key?(:is) && _pv_is({ key => nil }, key, validation[:is], raise_error: false)
end
# Return the value of a parameter, or nil if it doesn't exist.
def _pv_opts_lookup(opts, key)
if opts.has_key?(key.to_s)
opts[key.to_s]
elsif opts.has_key?(key.to_sym)
opts[key.to_sym]
else
nil
end
end
# Raise an exception if the parameter is not found.
def _pv_required(opts, key, is_required = true, explicitly_allows_nil = false)
if is_required
return true if opts.has_key?(key.to_s) && (explicitly_allows_nil || !opts[key.to_s].nil?)
return true if opts.has_key?(key.to_sym) && (explicitly_allows_nil || !opts[key.to_sym].nil?)
raise Exceptions::ValidationFailed, "Required argument #{key.inspect} is missing!"
end
true
end
#
# List of things values must be equal to.
#
# Uses Ruby's `==` to evaluate (equal_to == value). At least one must
# match for the value to be valid.
#
# `nil` passes this validation automatically.
#
# @return [Array,nil] List of things values must be equal to, or nil if
# equal_to is unspecified.
#
def _pv_equal_to(opts, key, to_be)
value = _pv_opts_lookup(opts, key)
unless value.nil?
to_be = Array(to_be)
to_be.each do |tb|
return true if value == tb
end
raise Exceptions::ValidationFailed, "Option #{key} must be equal to one of: #{to_be.join(", ")}! You passed #{value.inspect}."
end
end
#
# List of things values must be instances of.
#
# Uses value.kind_of?(kind_of) to evaluate. At least one must match for
# the value to be valid.
#
# `nil` automatically passes this validation.
#
def _pv_kind_of(opts, key, to_be)
value = _pv_opts_lookup(opts, key)
unless value.nil?
to_be = Array(to_be)
to_be.each do |tb|
return true if value.kind_of?(tb)
end
raise Exceptions::ValidationFailed, "Option #{key} must be a kind of #{to_be}! You passed #{value.inspect}."
end
end
#
# List of method names values must respond to.
#
# Uses value.respond_to?(respond_to) to evaluate. At least one must match
# for the value to be valid.
#
def _pv_respond_to(opts, key, method_name_list)
value = _pv_opts_lookup(opts, key)
unless value.nil?
Array(method_name_list).each do |method_name|
unless value.respond_to?(method_name)
raise Exceptions::ValidationFailed, "Option #{key} must have a #{method_name} method!"
end
end
end
end
#
# List of things that must not be true about the value.
#
# Calls `value.<thing>?` All responses must be false for the value to be
# valid.
# Values which do not respond to <thing>? are considered valid (because if
# a value doesn't respond to `:readable?`, then it probably isn't
# readable.)
#
# @example
# ```ruby
# property :x, cannot_be: [ :nil, :empty ]
# x [ 1, 2 ] #=> valid
# x 1 #=> valid
# x [] #=> invalid
# x nil #=> invalid
# ```
#
def _pv_cannot_be(opts, key, predicate_method_base_name)
value = _pv_opts_lookup(opts, key)
if !value.nil?
Array(predicate_method_base_name).each do |method_name|
predicate_method = :"#{method_name}?"
if value.respond_to?(predicate_method)
if value.send(predicate_method)
raise Exceptions::ValidationFailed, "Option #{key} cannot be #{predicate_method_base_name}"
end
end
end
end
end
#
# The default value for a property.
#
# When the property is not assigned, this will be used.
#
# If this is a lazy value, it will either be passed the resource as a value,
# or if the lazy proc does not take parameters, it will be run in the
# context of the instance with instance_eval.
#
# @example
# ```ruby
# property :x, default: 10
# ```
#
# @example
# ```ruby
# property :x
# property :y, default: lazy { x+2 }
# ```
#
# @example
# ```ruby
# property :x
# property :y, default: lazy { |r| r.x+2 }
# ```
#
def _pv_default(opts, key, default_value)
value = _pv_opts_lookup(opts, key)
if value.nil?
default_value = default_value.freeze if !default_value.is_a?(DelayedEvaluator)
opts[key] = default_value
end
end
#
# List of regexes values that must match.
#
# Uses regex.match() to evaluate. At least one must match for the value to
# be valid.
#
# `nil` passes regex validation automatically.
#
# @example
# ```ruby
# property :x, regex: [ /abc/, /xyz/ ]
# ```
#
def _pv_regex(opts, key, regex)
value = _pv_opts_lookup(opts, key)
if !value.nil?
Array(regex).flatten.each do |r|
return true if r.match(value.to_s)
end
raise Exceptions::ValidationFailed, "Option #{key}'s value #{value} does not match regular expression #{regex.inspect}"
end
end
#
# List of procs we pass the value to.
#
# All procs must return true for the value to be valid. If any procs do
# not return true, the key will be used for the message: `"Property x's
# value :y <message>"`.
#
# @example
# ```ruby
# property :x, callbacks: { "is bigger than 10" => proc { |v| v <= 10 }, "is not awesome" => proc { |v| !v.awesome }}
# ```
#
def _pv_callbacks(opts, key, callbacks)
raise ArgumentError, "Callback list must be a hash!" unless callbacks.kind_of?(Hash)
value = _pv_opts_lookup(opts, key)
if !value.nil?
callbacks.each do |message, zeproc|
unless zeproc.call(value)
raise Exceptions::ValidationFailed, "Option #{key}'s value #{value} #{message}!"
end
end
end
end
#
# Allows a parameter to default to the value of the resource name.
#
# @example
# ```ruby
# property :x, name_property: true
# ```
#
def _pv_name_property(opts, key, is_name_property = true)
if is_name_property
if opts[key].nil?
raise CannotValidateStaticallyError, "name_property cannot be evaluated without a resource." if self == Chef::Mixin::ParamsValidate
opts[key] = self.instance_variable_get(:"@name")
end
end
end
alias :_pv_name_attribute :_pv_name_property
#
# List of valid things values can be.
#
# Uses Ruby's `===` to evaluate (is === value). At least one must match
# for the value to be valid.
#
# If a proc is passed, it is instance_eval'd in the resource, passed the
# value, and must return a truthy or falsey value.
#
# @example Class
# ```ruby
# property :x, String
# x 'valid' #=> valid
# x 1 #=> invalid
# x nil #=> invalid
#
# @example Value
# ```ruby
# property :x, [ :a, :b, :c, nil ]
# x :a #=> valid
# x nil #=> valid
# ```
#
# @example Regex
# ```ruby
# property :x, /bar/
# x 'foobar' #=> valid
# x 'foo' #=> invalid
# x nil #=> invalid
# ```
#
# @example Proc
# ```ruby
# property :x, proc { |x| x > y }
# property :y, default: 2
# x 3 #=> valid
# x 1 #=> invalid
# ```
#
# @example Property
# ```ruby
# type = Property.new(is: String)
# property :x, type
# x 'foo' #=> valid
# x 1 #=> invalid
# x nil #=> invalid
# ```
#
# @example RSpec Matcher
# ```ruby
# include RSpec::Matchers
# property :x, a_string_matching /bar/
# x 'foobar' #=> valid
# x 'foo' #=> invalid
# x nil #=> invalid
# ```
#
def _pv_is(opts, key, to_be, raise_error: true)
return true if !opts.has_key?(key.to_s) && !opts.has_key?(key.to_sym)
value = _pv_opts_lookup(opts, key)
to_be = [ to_be ].flatten(1)
errors = []
passed = to_be.any? do |tb|
case tb
when Proc
raise CannotValidateStaticallyError, "is: proc { } must be evaluated once for each resource" if self == Chef::Mixin::ParamsValidate
instance_exec(value, &tb)
when Property
begin
validate(opts, { key => tb.validation_options })
true
rescue Exceptions::ValidationFailed
# re-raise immediately if there is only one "is" so we get a better stack
raise if to_be.size == 1
errors << $!
false
end
else
tb === value
end
end
if passed
true
else
message = "Property #{key} must be one of: #{to_be.map { |v| v.inspect }.join(", ")}! You passed #{value.inspect}."
unless errors.empty?
message << " Errors:\n#{errors.map { |m| "- #{m}" }.join("\n")}"
end
raise Exceptions::ValidationFailed, message
end
end
#
# Method to mess with a value before it is validated and stored.
#
# Allows you to transform values into a canonical form that is easy to
# work with.
#
# This is passed the value to transform, and is run in the context of the
# instance (so it has access to other resource properties). It must return
# the value that will be stored in the instance.
#
# @example
# ```ruby
# property :x, Integer, coerce: { |v| v.to_i }
# ```
#
def _pv_coerce(opts, key, coercer)
if opts.has_key?(key.to_s)
raise CannotValidateStaticallyError, "coerce must be evaluated for each resource." if self == Chef::Mixin::ParamsValidate
opts[key.to_s] = instance_exec(opts[key], &coercer)
elsif opts.has_key?(key.to_sym)
raise CannotValidateStaticallyError, "coerce must be evaluated for each resource." if self == Chef::Mixin::ParamsValidate
opts[key.to_sym] = instance_exec(opts[key], &coercer)
end
end
# We allow Chef::Mixin::ParamsValidate.validate(), but we will raise an
# error if you try to do anything requiring there to be an actual resource.
# This way, you can statically validate things if you have constant validation
# (which is the norm).
extend self
# Used by #set_or_return to avoid emitting a deprecation warning for
# "value nil" and to keep default stickiness working exactly the same
# @api private
class SetOrReturnProperty < (defined?(::Chef::Mixin::ParamsValidate::SetOrReturnProperty) ? ::Chef::Mixin::ParamsValidate::SetOrReturnProperty : Chef::Property)
def get(resource, nil_set: false)
value = super
# All values are sticky, frozen or not
if !is_set?(resource)
set_value(resource, value)
end
value
end
def call(resource, value = NOT_PASSED)
# setting to nil does a get
if value.nil? && !explicitly_accepts_nil?(resource)
get(resource, nil_set: true)
else
super
end
end
end
end
end
end
end
end
end

View File

@@ -1,117 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/mixin/powershell_out'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#--
# Copyright:: Copyright 2015-2016, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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.
class Chef < (defined?(::Chef) ? ::Chef : Object)
module Mixin
CopiedFromChef.extend_chef_module(::Chef::Mixin, self) if defined?(::Chef::Mixin)
module PowershellOut
CopiedFromChef.extend_chef_module(::Chef::Mixin::PowershellOut, self) if defined?(::Chef::Mixin::PowershellOut)
include Chef::Mixin::ShellOut
include Chef::Mixin::WindowsArchitectureHelper
# Run a command under powershell with the same API as shell_out. The
# options hash is extended to take an "architecture" flag which
# can be set to :i386 or :x86_64 to force the windows architecture.
#
# @param script [String] script to run
# @param options [Hash] options hash
# @return [Mixlib::Shellout] mixlib-shellout object
def powershell_out(*command_args)
script = command_args.first
options = command_args.last.is_a?(Hash) ? command_args.last : nil
run_command_with_os_architecture(script, options)
end
# Run a command under powershell with the same API as shell_out!
# (raises exceptions on errors)
#
# @param script [String] script to run
# @param options [Hash] options hash
# @return [Mixlib::Shellout] mixlib-shellout object
def powershell_out!(*command_args)
cmd = powershell_out(*command_args)
cmd.error!
cmd
end
private
# Helper function to run shell_out and wrap it with the correct
# flags to possibly disable WOW64 redirection (which we often need
# because chef-client runs as a 32-bit app on 64-bit windows).
#
# @param script [String] script to run
# @param options [Hash] options hash
# @return [Mixlib::Shellout] mixlib-shellout object
def run_command_with_os_architecture(script, options)
options ||= {}
options = options.dup
arch = options.delete(:architecture)
with_os_architecture(nil, architecture: arch) do
shell_out(
build_powershell_command(script),
options
)
end
end
# Helper to build a powershell command around the script to run.
#
# @param script [String] script to run
# @retrurn [String] powershell command to execute
def build_powershell_command(script)
flags = [
# Hides the copyright banner at startup.
"-NoLogo",
# Does not present an interactive prompt to the user.
"-NonInteractive",
# Does not load the Windows PowerShell profile.
"-NoProfile",
# always set the ExecutionPolicy flag
# see http://technet.microsoft.com/en-us/library/ee176961.aspx
"-ExecutionPolicy Unrestricted",
# Powershell will hang if STDIN is redirected
# http://connect.microsoft.com/PowerShell/feedback/details/572313/powershell-exe-can-hang-if-stdin-is-redirected
"-InputFormat None",
]
"powershell.exe #{flags.join(' ')} -Command \"#{script.gsub('"', '\"')}\""
end
end
end
end
end
end
end

View File

@@ -1,328 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/mixin/properties'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
require "chef_compat/copied_from_chef/chef/delayed_evaluator"
require "chef_compat/copied_from_chef/chef/mixin/params_validate"
require "chef_compat/copied_from_chef/chef/property"
class Chef < (defined?(::Chef) ? ::Chef : Object)
module Mixin
CopiedFromChef.extend_chef_module(::Chef::Mixin, self) if defined?(::Chef::Mixin)
module Properties
CopiedFromChef.extend_chef_module(::Chef::Mixin::Properties, self) if defined?(::Chef::Mixin::Properties)
module ClassMethods
CopiedFromChef.extend_chef_module(::Chef::Mixin::Properties::ClassMethods, self) if defined?(::Chef::Mixin::Properties::ClassMethods)
#
# The list of properties defined on this resource.
#
# Everything defined with `property` is in this list.
#
# @param include_superclass [Boolean] `true` to include properties defined
# on superclasses; `false` or `nil` to return the list of properties
# directly on this class.
#
# @return [Hash<Symbol,Property>] The list of property names and types.
#
def properties(include_superclass = true)
if include_superclass
result = {}
ancestors.reverse_each { |c| result.merge!(c.properties(false)) if c.respond_to?(:properties) }
result
else
@properties ||= {}
end
end
#
# Create a property on this resource class.
#
# If a superclass has this property, or if this property has already been
# defined by this resource, this will *override* the previous value.
#
# @param name [Symbol] The name of the property.
# @param type [Object,Array<Object>] The type(s) of this property.
# If present, this is prepended to the `is` validation option.
# @param options [Hash<Symbol,Object>] Validation options.
# @option options [Object,Array] :is An object, or list of
# objects, that must match the value using Ruby's `===` operator
# (`options[:is].any? { |v| v === value }`).
# @option options [Object,Array] :equal_to An object, or list
# of objects, that must be equal to the value using Ruby's `==`
# operator (`options[:is].any? { |v| v == value }`)
# @option options [Regexp,Array<Regexp>] :regex An object, or
# list of objects, that must match the value with `regex.match(value)`.
# @option options [Class,Array<Class>] :kind_of A class, or
# list of classes, that the value must be an instance of.
# @option options [Hash<String,Proc>] :callbacks A hash of
# messages -> procs, all of which match the value. The proc must
# return a truthy or falsey value (true means it matches).
# @option options [Symbol,Array<Symbol>] :respond_to A method
# name, or list of method names, the value must respond to.
# @option options [Symbol,Array<Symbol>] :cannot_be A property,
# or a list of properties, that the value cannot have (such as `:nil` or
# `:empty`). The method with a questionmark at the end is called on the
# value (e.g. `value.empty?`). If the value does not have this method,
# it is considered valid (i.e. if you don't respond to `empty?` we
# assume you are not empty).
# @option options [Proc] :coerce A proc which will be called to
# transform the user input to canonical form. The value is passed in,
# and the transformed value returned as output. Lazy values will *not*
# be passed to this method until after they are evaluated. Called in the
# context of the resource (meaning you can access other properties).
# @option options [Boolean] :required `true` if this property
# must be present; `false` otherwise. This is checked after the resource
# is fully initialized.
# @option options [Boolean] :name_property `true` if this
# property defaults to the same value as `name`. Equivalent to
# `default: lazy { name }`, except that #property_is_set? will
# return `true` if the property is set *or* if `name` is set.
# @option options [Boolean] :name_attribute Same as `name_property`.
# @option options [Object] :default The value this property
# will return if the user does not set one. If this is `lazy`, it will
# be run in the context of the instance (and able to access other
# properties).
# @option options [Boolean] :desired_state `true` if this property is
# part of desired state. Defaults to `true`.
# @option options [Boolean] :identity `true` if this property
# is part of object identity. Defaults to `false`.
# @option options [Boolean] :sensitive `true` if this property could
# contain sensitive information and whose value should be redacted
# in any resource reporting / auditing output. Defaults to `false`.
#
# @example Bare property
# property :x
#
# @example With just a type
# property :x, String
#
# @example With just options
# property :x, default: 'hi'
#
# @example With type and options
# property :x, String, default: 'hi'
#
def property(name, type = NOT_PASSED, **options)
name = name.to_sym
options = options.inject({}) { |memo, (key, value)| memo[key.to_sym] = value; memo }
options[:instance_variable_name] = :"@#{name}" if !options.has_key?(:instance_variable_name)
options[:name] = name
options[:declared_in] = self
if type == NOT_PASSED
# If a type is not passed, the property derives from the
# superclass property (if any)
if properties.has_key?(name)
property = properties[name].derive(**options)
else
property = property_type(**options)
end
# If a Property is specified, derive a new one from that.
elsif type.is_a?(Property) || (type.is_a?(Class) && type <= Property)
property = type.derive(**options)
# If a primitive type was passed, combine it with "is"
else
if options[:is]
options[:is] = ([ type ] + [ options[:is] ]).flatten(1)
else
options[:is] = type
end
property = property_type(**options)
end
local_properties = properties(false)
local_properties[name] = property
property.emit_dsl
end
#
# Create a reusable property type that can be used in multiple properties
# in different resources.
#
# @param options [Hash<Symbol,Object>] Validation options. see #property for
# the list of options.
#
# @example
# property_type(default: 'hi')
#
def property_type(**options)
Property.derive(**options)
end
#
# Create a lazy value for assignment to a default value.
#
# @param block The block to run when the value is retrieved.
#
# @return [Chef::DelayedEvaluator] The lazy value
#
def lazy(&block)
DelayedEvaluator.new(&block)
end
#
# Get or set the list of desired state properties for this resource.
#
# State properties are properties that describe the desired state
# of the system, such as file permissions or ownership.
# In general, state properties are properties 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, properties that are not
# "state properties" 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.
#
# This method is unnecessary when declaring properties with `property`;
# properties are added to state_properties by default, and can be turned off
# with `desired_state: false`.
#
# ```ruby
# property :x # part of desired state
# property :y, desired_state: false # not part of desired state
# ```
#
# @param names [Array<Symbol>] A list of property names to set as desired
# state.
#
# @return [Array<Property>] All properties in desired state.
#
def state_properties(*names)
if !names.empty?
names = names.map { |name| name.to_sym }.uniq
local_properties = properties(false)
# Add new properties to the list.
names.each do |name|
property = properties[name]
if !property
self.property name, instance_variable_name: false, desired_state: true
elsif !property.desired_state?
self.property name, desired_state: true
end
end
# If state_attrs *excludes* something which is currently desired state,
# mark it as desired_state: false.
local_properties.each do |name, property|
if property.desired_state? && !names.include?(name)
self.property name, desired_state: false
end
end
end
properties.values.select { |property| property.desired_state? }
end
#
# Set the identity of this resource to a particular set of properties.
#
# This drives #identity, which returns data that uniquely refers to a given
# resource on the given node (in such a way that it can be correlated
# across Chef runs).
#
# This method is unnecessary when declaring properties with `property`;
# properties can be added to identity during declaration with
# `identity: true`.
#
# ```ruby
# property :x, identity: true # part of identity
# property :y # not part of identity
# ```
#
# If no properties are marked as identity, "name" is considered the identity.
#
# @param names [Array<Symbol>] A list of property names to set as the identity.
#
# @return [Array<Property>] All identity properties.
#
def identity_properties(*names)
if !names.empty?
names = names.map { |name| name.to_sym }
# Add or change properties that are not part of the identity.
names.each do |name|
property = properties[name]
if !property
self.property name, instance_variable_name: false, identity: true
elsif !property.identity?
self.property name, identity: true
end
end
# If identity_properties *excludes* something which is currently part of
# the identity, mark it as identity: false.
properties.each do |name, property|
if property.identity? && !names.include?(name)
self.property name, identity: false
end
end
end
result = properties.values.select { |property| property.identity? }
result = [ properties[:name] ] if result.empty?
result
end
def included(other)
other.extend ClassMethods
end
end
def self.included(other)
other.extend ClassMethods
end
include Chef::Mixin::ParamsValidate
#
# Whether this property has been set (or whether it has a default that has
# been retrieved).
#
# @param name [Symbol] The name of the property.
# @return [Boolean] `true` if the property has been set.
#
def property_is_set?(name)
property = self.class.properties[name.to_sym]
raise ArgumentError, "Property #{name} is not defined in class #{self}" if !property
property.is_set?(self)
end
#
# Clear this property as if it had never been set. It will thereafter return
# the default.
# been retrieved).
#
# @param name [Symbol] The name of the property.
#
def reset_property(name)
property = self.class.properties[name.to_sym]
raise ArgumentError, "Property #{name} is not defined in class #{self}" if !property
property.reset(self)
end
end
end
end
end
end
end

View File

@@ -1,713 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/property'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: John Keiser <jkeiser@chef.io>
# Copyright:: Copyright 2015-2016, John Keiser.
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/delayed_evaluator"
class Chef < (defined?(::Chef) ? ::Chef : Object)
#
# Type and validation information for a property on a resource.
#
# A property named "x" manipulates the "@x" instance variable on a
# resource. The *presence* of the variable (`instance_variable_defined?(@x)`)
# tells whether the variable is defined; it may have any actual value,
# constrained only by validation.
#
# Properties may have validation, defaults, and coercion, and have full
# support for lazy values.
#
# @see Chef::Resource.property
# @see Chef::DelayedEvaluator
#
class Property < (defined?(::Chef::Property) ? ::Chef::Property : Object)
#
# Create a reusable property type that can be used in multiple properties
# in different resources.
#
# @param options [Hash<Symbol,Object>] Validation options. See Chef::Resource.property for
# the list of options.
#
# @example
# Property.derive(default: 'hi')
#
def self.derive(**options)
new(**options)
end
#
# Create a new property.
#
# @param options [Hash<Symbol,Object>] Property options, including
# control options here, as well as validation options (see
# Chef::Mixin::ParamsValidate#validate for a description of validation
# options).
# @option options [Symbol] :name The name of this property.
# @option options [Class] :declared_in The class this property comes from.
# @option options [Symbol] :instance_variable_name The instance variable
# tied to this property. Must include a leading `@`. Defaults to `@<name>`.
# `nil` means the property is opaque and not tied to a specific instance
# variable.
# @option options [Boolean] :desired_state `true` if this property is part of desired
# state. Defaults to `true`.
# @option options [Boolean] :identity `true` if this property is part of object
# identity. Defaults to `false`.
# @option options [Boolean] :name_property `true` if this
# property defaults to the same value as `name`. Equivalent to
# `default: lazy { name }`, except that #property_is_set? will
# return `true` if the property is set *or* if `name` is set.
# @option options [Boolean] :nillable `true` opt-in to Chef-13 style behavior where
# attempting to set a nil value will really set a nil value instead of issuing
# a warning and operating like a getter
# @option options [Object] :default The value this property
# will return if the user does not set one. If this is `lazy`, it will
# be run in the context of the instance (and able to access other
# properties) and cached. If not, the value will be frozen with Object#freeze
# to prevent users from modifying it in an instance.
# @option options [Proc] :coerce A proc which will be called to
# transform the user input to canonical form. The value is passed in,
# and the transformed value returned as output. Lazy values will *not*
# be passed to this method until after they are evaluated. Called in the
# context of the resource (meaning you can access other properties).
# @option options [Boolean] :required `true` if this property
# must be present; `false` otherwise. This is checked after the resource
# is fully initialized.
#
def initialize(**options)
super if defined?(::Chef::Property)
options = options.inject({}) { |memo, (key, value)| memo[key.to_sym] = value; memo }
@options = options
options[:name] = options[:name].to_sym if options[:name]
options[:instance_variable_name] = options[:instance_variable_name].to_sym if options[:instance_variable_name]
# Replace name_attribute with name_property
if options.has_key?(:name_attribute)
# If we have both name_attribute and name_property and they differ, raise an error
if options.has_key?(:name_property)
raise ArgumentError, "Cannot specify both name_property and name_attribute together on property #{self}."
end
# replace name_property with name_attribute in place
options = Hash[options.map { |k, v| k == :name_attribute ? [ :name_property, v ] : [ k, v ] }]
@options = options
end
# Only pick the first of :default, :name_property and :name_attribute if
# more than one is specified.
if options.has_key?(:default) && options[:name_property]
if options[:default].nil? || options.keys.index(:name_property) < options.keys.index(:default)
options.delete(:default)
preferred_default = :name_property
else
options.delete(:name_property)
preferred_default = :default
end
Chef.log_deprecation("Cannot specify both default and name_property together on property #{self}. Only one (#{preferred_default}) will be obeyed. In Chef 13, this will become an error. Please remove one or the other from the property.")
end
# Validate the default early, so the user gets a good error message, and
# cache it so we don't do it again if so
begin
# If we can validate it all the way to output, do it.
@stored_default = input_to_stored_value(nil, default, is_default: true)
rescue Chef::Exceptions::CannotValidateStaticallyError
# If the validation is not static (i.e. has procs), we will have to
# coerce and validate the default each time we run
end
end
def to_s
"#{name || "<property type>"}#{declared_in ? " of resource #{declared_in.resource_name}" : ""}"
end
#
# The name of this property.
#
# @return [String]
#
def name
options[:name]
end
#
# The class this property was defined in.
#
# @return [Class]
#
def declared_in
options[:declared_in]
end
#
# The instance variable associated with this property.
#
# Defaults to `@<name>`
#
# @return [Symbol]
#
def instance_variable_name
if options.has_key?(:instance_variable_name)
options[:instance_variable_name]
elsif name
:"@#{name}"
end
end
#
# The raw default value for this resource.
#
# Does not coerce or validate the default. Does not evaluate lazy values.
#
# Defaults to `lazy { name }` if name_property is true; otherwise defaults to
# `nil`
#
def default
return options[:default] if options.has_key?(:default)
return Chef::DelayedEvaluator.new { name } if name_property?
nil
end
#
# Whether this is part of the resource's natural identity or not.
#
# @return [Boolean]
#
def identity?
options[:identity]
end
#
# Whether this is part of desired state or not.
#
# Defaults to true.
#
# @return [Boolean]
#
def desired_state?
return true if !options.has_key?(:desired_state)
options[:desired_state]
end
#
# Whether this is name_property or not.
#
# @return [Boolean]
#
def name_property?
options[:name_property]
end
#
# Whether this property has a default value.
#
# @return [Boolean]
#
def has_default?
options.has_key?(:default) || name_property?
end
#
# Whether this property is required or not.
#
# @return [Boolean]
#
def required?
options[:required]
end
#
# Whether this property is sensitive or not.
#
# Defaults to false.
#
# @return [Boolean]
#
def sensitive?
options.fetch(:sensitive, false)
end
#
# Validation options. (See Chef::Mixin::ParamsValidate#validate.)
#
# @return [Hash<Symbol,Object>]
#
def validation_options
@validation_options ||= options.reject do |k, v|
[:declared_in, :name, :instance_variable_name, :desired_state, :identity, :default, :name_property, :coerce, :required, :nillable, :sensitive].include?(k)
end
end
#
# Handle the property being called.
#
# The base implementation does the property get-or-set:
#
# ```ruby
# resource.myprop # get
# resource.myprop value # set
# ```
#
# Subclasses may implement this with any arguments they want, as long as
# the corresponding DSL calls it correctly.
#
# @param resource [Chef::Resource] The resource to get the property from.
# @param value The value to set (or NOT_PASSED if it is a get).
#
# @return The current value of the property. If it is a `set`, lazy values
# will be returned without running, validating or coercing. If it is a
# `get`, the non-lazy, coerced, validated value will always be returned.
#
def call(resource, value = NOT_PASSED)
if value == NOT_PASSED
return get(resource)
end
if value.nil? && !nillable?
# In Chef 12, value(nil) does a *get* instead of a set, so we
# warn if the value would have been changed. In Chef 13, it will be
# equivalent to value = nil.
result = get(resource, nil_set: true)
# Warn about this becoming a set in Chef 13.
begin
input_to_stored_value(resource, value)
# If nil is valid, and it would change the value, warn that this will change to a set.
if !result.nil?
Chef.log_deprecation("An attempt was made to change #{name} from #{result.inspect} to nil by calling #{name}(nil). In Chef 12, this does a get rather than a set. In Chef 13, this will change to set the value to nil.")
end
rescue Chef::Exceptions::DeprecatedFeatureError
raise
rescue
# If nil is invalid, warn that this will become an error.
Chef.log_deprecation("nil is an invalid value for #{self}. In Chef 13, this warning will change to an error. Error: #{$!}")
end
result
else
# Anything else, such as myprop(value) is a set
set(resource, value)
end
end
#
# Get the property value from the resource, handling lazy values,
# defaults, and validation.
#
# - If the property's value is lazy, it is evaluated, coerced and validated.
# - If the property has no value, and is required, raises ValidationFailed.
# - If the property has no value, but has a lazy default, it is evaluated,
# coerced and validated. If the evaluated value is frozen, the resulting
# - If the property has no value, but has a default, the default value
# will be returned and frozen. If the default value is lazy, it will be
# evaluated, coerced and validated, and the result stored in the property.
# - If the property has no value, but is name_property, `resource.name`
# is retrieved, coerced, validated and stored in the property.
# - Otherwise, `nil` is returned.
#
# @param resource [Chef::Resource] The resource to get the property from.
#
# @return The value of the property.
#
# @raise Chef::Exceptions::ValidationFailed If the value is invalid for
# this property, or if the value is required and not set.
#
def get(resource, nil_set: false)
# If it's set, return it (and evaluate any lazy values)
if is_set?(resource)
value = get_value(resource)
value = stored_value_to_output(resource, value)
else
# We are getting the default value.
# If the user does something like this:
#
# ```
# class MyResource < Chef::Resource
# property :content
# action :create do
# file '/x.txt' do
# content content
# end
# end
# end
# ```
#
# It won't do what they expect. This checks whether you try to *read*
# `content` while we are compiling the resource.
if !nil_set &&
resource.respond_to?(:resource_initializing) &&
resource.resource_initializing &&
resource.respond_to?(:enclosing_provider) &&
resource.enclosing_provider &&
resource.enclosing_provider.new_resource &&
resource.enclosing_provider.new_resource.respond_to?(name)
Chef::Log.warn("#{Chef::Log.caller_location}: property #{name} is declared in both #{resource} and #{resource.enclosing_provider}. Use new_resource.#{name} instead. At #{Chef::Log.caller_location}")
end
if has_default?
# If we were able to cache the stored_default, grab it.
if defined?(@stored_default)
value = @stored_default
else
# Otherwise, we have to validate it now.
value = input_to_stored_value(resource, default, is_default: true)
end
value = stored_value_to_output(resource, value, is_default: true)
# If the value is mutable (non-frozen), we set it on the instance
# so that people can mutate it. (All constant default values are
# frozen.)
if !value.frozen? && !value.nil?
set_value(resource, value)
end
value
elsif required?
raise Chef::Exceptions::ValidationFailed, "#{name} is required"
end
end
end
#
# Set the value of this property in the given resource.
#
# Non-lazy values are coerced and validated before being set. Coercion
# and validation of lazy values is delayed until they are first retrieved.
#
# @param resource [Chef::Resource] The resource to set this property in.
# @param value The value to set.
#
# @return The value that was set, after coercion (if lazy, still returns
# the lazy value)
#
# @raise Chef::Exceptions::ValidationFailed If the value is invalid for
# this property.
#
def set(resource, value)
set_value(resource, input_to_stored_value(resource, value))
end
#
# Find out whether this property has been set.
#
# This will be true if:
# - The user explicitly set the value
# - The property has a default, and the value was retrieved.
#
# From this point of view, it is worth looking at this as "what does the
# user think this value should be." In order words, if the user grabbed
# the value, even if it was a default, they probably based calculations on
# it. If they based calculations on it and the value changes, the rest of
# the world gets inconsistent.
#
# @param resource [Chef::Resource] The resource to get the property from.
#
# @return [Boolean]
#
def is_set?(resource)
value_is_set?(resource)
end
#
# Reset the value of this property so that is_set? will return false and the
# default will be returned in the future.
#
# @param resource [Chef::Resource] The resource to get the property from.
#
def reset(resource)
reset_value(resource)
end
#
# Coerce an input value into canonical form for the property.
#
# After coercion, the value is suitable for storage in the resource.
# You must validate values after coercion, however.
#
# Does no special handling for lazy values.
#
# @param resource [Chef::Resource] The resource we're coercing against
# (to provide context for the coerce).
# @param value The value to coerce.
#
# @return The coerced value.
#
# @raise Chef::Exceptions::ValidationFailed If the value is invalid for
# this property.
#
def coerce(resource, value)
if options.has_key?(:coerce)
# If we have no default value, `nil` is never coerced or validated
unless !has_default? && value.nil?
value = exec_in_resource(resource, options[:coerce], value)
end
end
value
end
#
# Validate a value.
#
# Calls Chef::Mixin::ParamsValidate#validate with #validation_options as
# options.
#
# @param resource [Chef::Resource] The resource we're validating against
# (to provide context for the validate).
# @param value The value to validate.
#
# @raise Chef::Exceptions::ValidationFailed If the value is invalid for
# this property.
#
def validate(resource, value)
# If we have no default value, `nil` is never coerced or validated
unless value.nil? && !has_default?
if resource
resource.validate({ name => value }, { name => validation_options })
else
name = self.name || :property_type
Chef::Mixin::ParamsValidate.validate({ name => value }, { name => validation_options })
end
end
end
#
# Derive a new Property that is just like this one, except with some added or
# changed options.
#
# @param options [Hash<Symbol,Object>] List of options that would be passed
# to #initialize.
#
# @return [Property] The new property type.
#
def derive(**modified_options)
# Since name_property, name_attribute and default override each other,
# if you specify one of them in modified_options it overrides anything in
# the original options.
options = self.options
if modified_options.has_key?(:name_property) ||
modified_options.has_key?(:name_attribute) ||
modified_options.has_key?(:default)
options = options.reject { |k, v| k == :name_attribute || k == :name_property || k == :default }
end
self.class.new(options.merge(modified_options))
end
#
# Emit the DSL for this property into the resource class (`declared_in`).
#
# Creates a getter and setter for the property.
#
def emit_dsl
# We don't create the getter/setter if it's a custom property; we will
# be using the existing getter/setter to manipulate it instead.
return if !instance_variable_name
# We prefer this form because the property name won't show up in the
# stack trace if you use `define_method`.
declared_in.class_eval <<-EOM, __FILE__, __LINE__ + 1
def #{name}(value=NOT_PASSED)
raise "Property `#{name}` of `\#{self}` was incorrectly passed a block. Possible property-resource collision. To call a resource named `#{name}` either rename the property or else use `declare_resource(:#{name}, ...)`" if block_given?
self.class.properties[#{name.inspect}].call(self, value)
end
def #{name}=(value)
raise "Property `#{name}` of `\#{self}` was incorrectly passed a block. Possible property-resource collision. To call a resource named `#{name}` either rename the property or else use `declare_resource(:#{name}, ...)`" if block_given?
self.class.properties[#{name.inspect}].set(self, value)
end
EOM
rescue SyntaxError
# If the name is not a valid ruby name, we use define_method.
declared_in.define_method(name) do |value = NOT_PASSED, &block|
raise "Property `#{name}` of `#{self}` was incorrectly passed a block! Possible property-resource collision. To call a resource named `#{name}` either rename the property or else use `declare_resource(:#{name}, ...)`" if block
self.class.properties[name].call(self, value)
end
declared_in.define_method("#{name}=") do |value, &block|
raise "Property `#{name}` of `#{self}` was incorrectly passed a block! Possible property-resource collision. To call a resource named `#{name}` either rename the property or else use `declare_resource(:#{name}, ...)`" if block
self.class.properties[name].set(self, value)
end
end
#
# The options this Property will use for get/set behavior and validation.
#
# @see #initialize for a list of valid options.
#
attr_reader :options
#
# Find out whether this type accepts nil explicitly.
#
# A type accepts nil explicitly if "is" allows nil, it validates as nil, *and* is not simply
# an empty type.
#
# A type is presumed to accept nil if it does coercion (which must handle nil).
#
# These examples accept nil explicitly:
# ```ruby
# property :a, [ String, nil ]
# property :a, [ String, NilClass ]
# property :a, [ String, proc { |v| v.nil? } ]
# ```
#
# This does not (because the "is" doesn't exist or doesn't have nil):
#
# ```ruby
# property :x, String
# ```
#
# These do not, even though nil would validate fine (because they do not
# have "is"):
#
# ```ruby
# property :a
# property :a, equal_to: [ 1, 2, 3, nil ]
# property :a, kind_of: [ String, NilClass ]
# property :a, respond_to: [ ]
# property :a, callbacks: { "a" => proc { |v| v.nil? } }
# ```
#
# @param resource [Chef::Resource] The resource we're coercing against
# (to provide context for the coerce).
#
# @return [Boolean] Whether this value explicitly accepts nil.
#
# @api private
def explicitly_accepts_nil?(resource)
options.has_key?(:coerce) ||
(options.has_key?(:is) && resource.send(:_pv_is, { name => nil }, name, options[:is], raise_error: false))
end
# @api private
def get_value(resource)
if instance_variable_name
resource.instance_variable_get(instance_variable_name)
else
resource.send(name)
end
end
# @api private
def set_value(resource, value)
if instance_variable_name
resource.instance_variable_set(instance_variable_name, value)
else
resource.send(name, value)
end
end
# @api private
def value_is_set?(resource)
if instance_variable_name
resource.instance_variable_defined?(instance_variable_name)
else
true
end
end
# @api private
def reset_value(resource)
if instance_variable_name
if value_is_set?(resource)
resource.remove_instance_variable(instance_variable_name)
end
else
raise ArgumentError, "Property #{name} has no instance variable defined and cannot be reset"
end
end
private
def exec_in_resource(resource, proc, *args)
if resource
if proc.arity > args.size
value = proc.call(resource, *args)
else
value = resource.instance_exec(*args, &proc)
end
else
# If we don't have a resource yet, we can't exec in resource!
raise Chef::Exceptions::CannotValidateStaticallyError, "Cannot validate or coerce without a resource"
end
end
def input_to_stored_value(resource, value, is_default: false)
unless value.is_a?(DelayedEvaluator)
value = coerce_and_validate(resource, value, is_default: is_default)
end
value
end
def stored_value_to_output(resource, value, is_default: false)
# Crack open lazy values before giving the result to the user
if value.is_a?(DelayedEvaluator)
value = exec_in_resource(resource, value)
value = coerce_and_validate(resource, value, is_default: is_default)
end
value
end
# Coerces and validates the value. If the value is a default, it will warn
# the user that invalid defaults are bad mmkay, and return it as if it were
# valid.
def coerce_and_validate(resource, value, is_default: false)
result = coerce(resource, value)
begin
# If the input is from a default, we need to emit an invalid default warning on validate.
validate(resource, result)
rescue Chef::Exceptions::CannotValidateStaticallyError
# This one gets re-raised
raise
rescue
# Anything else is just an invalid default: in those cases, we just
# warn and return the (possibly coerced) value to the user.
if is_default
if value.nil?
Chef.log_deprecation("Default value nil is invalid for property #{self}. Possible fixes: 1. Remove 'default: nil' if nil means 'undefined'. 2. Set a valid default value if there is a reasonable one. 3. Allow nil as a valid value of your property (for example, 'property #{name.inspect}, [ String, nil ], default: nil'). Error: #{$!}")
else
Chef.log_deprecation("Default value #{value.inspect} is invalid for property #{self}. In Chef 13 this will become an error: #{$!}.")
end
else
raise
end
end
result
end
def nillable?
!!options[:nillable]
end
end
end
end
end
end

View File

@@ -1,164 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/provider'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
require "chef_compat/copied_from_chef/chef/dsl/core"
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Provider < (defined?(::Chef::Provider) ? ::Chef::Provider : Object)
include Chef::DSL::Core
attr_accessor :action
def initialize(new_resource, run_context)
super if defined?(::Chef::Provider)
@new_resource = new_resource
@action = action
@current_resource = nil
@run_context = run_context
@converge_actions = nil
@recipe_name = nil
@cookbook_name = nil
self.class.include_resource_dsl_module(new_resource)
end
def converge_if_changed(*properties, &converge_block)
if !converge_block
raise ArgumentError, "converge_if_changed must be passed a block!"
end
properties = new_resource.class.state_properties.map { |p| p.name } if properties.empty?
properties = properties.map { |p| p.to_sym }
if current_resource
# Collect the list of modified properties
specified_properties = properties.select { |property| new_resource.property_is_set?(property) }
modified = specified_properties.select { |p| new_resource.send(p) != current_resource.send(p) }
if modified.empty?
properties_str = if sensitive
specified_properties.join(", ")
else
specified_properties.map { |p| "#{p}=#{new_resource.send(p).inspect}" }.join(", ")
end
Chef::Log.debug("Skipping update of #{new_resource}: has not changed any of the specified properties #{properties_str}.")
return false
end
# Print the pretty green text and run the block
property_size = modified.map { |p| p.size }.max
modified.map! do |p|
properties_str = if sensitive
"(suppressed sensitive property)"
else
"#{new_resource.send(p).inspect} (was #{current_resource.send(p).inspect})"
end
" set #{p.to_s.ljust(property_size)} to #{properties_str}"
end
converge_by([ "update #{current_resource.identity}" ] + modified, &converge_block)
else
# The resource doesn't exist. Mark that we are *creating* this, and
# write down any properties we are setting.
property_size = properties.map { |p| p.size }.max
created = properties.map do |property|
default = " (default value)" unless new_resource.property_is_set?(property)
properties_str = if sensitive
"(suppressed sensitive property)"
else
new_resource.send(property).inspect
end
" set #{property.to_s.ljust(property_size)} to #{properties_str}#{default}"
end
converge_by([ "create #{new_resource.identity}" ] + created, &converge_block)
end
true
end
def self.include_resource_dsl(include_resource_dsl)
@include_resource_dsl = include_resource_dsl
end
def self.include_resource_dsl_module(resource)
if @include_resource_dsl && !defined?(@included_resource_dsl_module)
provider_class = self
@included_resource_dsl_module = Module.new do
extend Forwardable
define_singleton_method(:to_s) { "forwarder module for #{provider_class}" }
define_singleton_method(:inspect) { to_s }
# Add a delegator for each explicit property that will get the *current* value
# of the property by default instead of the *actual* value.
resource.class.properties.each do |name, property|
class_eval(<<-EOM, __FILE__, __LINE__)
def #{name}(*args, &block)
# If no arguments were passed, we process "get" by defaulting
# the value to current_resource, not new_resource. This helps
# avoid issues where resources accidentally overwrite perfectly
# valid stuff with default values.
if args.empty? && !block
if !new_resource.property_is_set?(__method__) && current_resource
return current_resource.public_send(__method__)
end
end
new_resource.public_send(__method__, *args, &block)
end
EOM
end
dsl_methods =
resource.class.public_instance_methods +
resource.class.protected_instance_methods -
provider_class.instance_methods -
resource.class.properties.keys
def_delegators(:new_resource, *dsl_methods)
end
include @included_resource_dsl_module
end
end
def self.use_inline_resources
extend InlineResources::ClassMethods
include InlineResources
end
module InlineResources
CopiedFromChef.extend_chef_module(::Chef::Provider::InlineResources, self) if defined?(::Chef::Provider::InlineResources)
def compile_and_converge_action(&block)
old_run_context = run_context
@run_context = run_context.create_child
return_value = instance_eval(&block)
Chef::Runner.new(run_context).converge
return_value
ensure
if run_context.resource_collection.any? { |r| r.updated? }
new_resource.updated_by_last_action(true)
end
@run_context = old_run_context
end
module ClassMethods
CopiedFromChef.extend_chef_module(::Chef::Provider::InlineResources::ClassMethods, self) if defined?(::Chef::Provider::InlineResources::ClassMethods)
def action(name, &block)
# We need the block directly in a method so that `super` works
define_method("compile_action_#{name}", &block)
# We try hard to use `def` because define_method doesn't show the method name in the stack.
begin
class_eval <<-EOM
def action_#{name}
compile_and_converge_action { compile_action_#{name} }
end
EOM
rescue SyntaxError
define_method("action_#{name}") { send("compile_action_#{name}") }
end
end
end
end
protected
end
end
end
end
end

View File

@@ -1,269 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/provider/apt_repository'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Thom May (<thom@chef.io>)
# Copyright:: Copyright (c) 2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/resource"
require "chef_compat/copied_from_chef/chef/dsl/declare_resource"
require "chef_compat/copied_from_chef/chef/provider/noop"
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Provider < (defined?(::Chef::Provider) ? ::Chef::Provider : Object)
class AptRepository < (defined?(::Chef::Provider::AptRepository) ? ::Chef::Provider::AptRepository : Chef::Provider)
use_inline_resources
include Chef::Mixin::ShellOut
extend Chef::Mixin::Which
provides :apt_repository do
which("apt-get")
end
def whyrun_supported?
true
end
def load_current_resource
end
action :add do
unless new_resource.key.nil?
if is_key_id?(new_resource.key) && !has_cookbook_file?(new_resource.key)
install_key_from_keyserver
else
install_key_from_uri
end
end
declare_resource(:execute, "apt-cache gencaches") do
ignore_failure true
action :nothing
end
declare_resource(:apt_update, new_resource.name) do
ignore_failure true
action :nothing
end
components = if is_ppa_url?(new_resource.uri) && new_resource.components.empty?
"main"
else
new_resource.components
end
repo = build_repo(
new_resource.uri,
new_resource.distribution,
components,
new_resource.trusted,
new_resource.arch,
new_resource.deb_src
)
declare_resource(:file, "/etc/apt/sources.list.d/#{new_resource.name}.list") do
owner "root"
group "root"
mode "0644"
content repo
sensitive new_resource.sensitive
action :create
notifies :run, "execute[apt-cache gencaches]", :immediately
notifies :update, "apt_update[#{new_resource.name}]", :immediately if new_resource.cache_rebuild
end
end
action :remove do
if ::File.exist?("/etc/apt/sources.list.d/#{new_resource.name}.list")
converge_by "Removing #{new_resource.name} repository from /etc/apt/sources.list.d/" do
declare_resource(:file, "/etc/apt/sources.list.d/#{new_resource.name}.list") do
sensitive new_resource.sensitive
action :delete
notifies :update, "apt_update[#{new_resource.name}]", :immediately if new_resource.cache_rebuild
end
declare_resource(:apt_update, new_resource.name) do
ignore_failure true
action :nothing
end
end
end
end
def is_key_id?(id)
id = id[2..-1] if id.start_with?("0x")
id =~ /^\h+$/ && [8, 16, 40].include?(id.length)
end
def extract_fingerprints_from_cmd(cmd)
so = shell_out(cmd)
so.run_command
so.stdout.split(/\n/).map do |t|
if z = t.match(/^ +Key fingerprint = ([0-9A-F ]+)/)
z[1].split.join
end
end.compact
end
def key_is_valid?(cmd, key)
valid = true
so = shell_out(cmd)
so.run_command
so.stdout.split(/\n/).map do |t|
if t =~ %r{^\/#{key}.*\[expired: .*\]$}
Chef::Log.debug "Found expired key: #{t}"
valid = false
break
end
end
Chef::Log.debug "key #{key} #{valid ? "is valid" : "is not valid"}"
valid
end
def cookbook_name
new_resource.cookbook || new_resource.cookbook_name
end
def has_cookbook_file?(fn)
run_context.has_cookbook_file_in_cookbook?(cookbook_name, fn)
end
def no_new_keys?(file)
installed_keys = extract_fingerprints_from_cmd("apt-key finger")
proposed_keys = extract_fingerprints_from_cmd("gpg --with-fingerprint #{file}")
(installed_keys & proposed_keys).sort == proposed_keys.sort
end
def install_key_from_uri
key_name = new_resource.key.gsub(/[^0-9A-Za-z\-]/, "_")
cached_keyfile = ::File.join(Chef::Config[:file_cache_path], key_name)
type = if new_resource.key.start_with?("http")
:remote_file
elsif has_cookbook_file?(new_resource.key)
:cookbook_file
else
raise Chef::Exceptions::FileNotFound, "Cannot locate key file"
end
declare_resource(type, cached_keyfile) do
source new_resource.key
mode "0644"
sensitive new_resource.sensitive
action :create
end
raise "The key #{cached_keyfile} is invalid and cannot be used to verify an apt repository." unless key_is_valid?("gpg #{cached_keyfile}", "")
declare_resource(:execute, "apt-key add #{cached_keyfile}") do
sensitive new_resource.sensitive
action :run
not_if do
no_new_keys?(cached_keyfile)
end
notifies :run, "execute[apt-cache gencaches]", :immediately
end
end
def install_key_from_keyserver(key = new_resource.key, keyserver = new_resource.keyserver)
cmd = "apt-key adv --recv"
cmd << " --keyserver-options http-proxy=#{new_resource.key_proxy}" if new_resource.key_proxy
cmd << " --keyserver "
cmd << if keyserver.start_with?("hkp://")
keyserver
else
"hkp://#{keyserver}:80"
end
cmd << " #{key}"
declare_resource(:execute, "install-key #{key}") do
command cmd
sensitive new_resource.sensitive
not_if do
present = extract_fingerprints_from_cmd("apt-key finger").any? do |fp|
fp.end_with? key.upcase
end
present && key_is_valid?("apt-key list", key.upcase)
end
notifies :run, "execute[apt-cache gencaches]", :immediately
end
raise "The key #{key} is invalid and cannot be used to verify an apt repository." unless key_is_valid?("apt-key list", key.upcase)
end
def install_ppa_key(owner, repo)
url = "https://launchpad.net/api/1.0/~#{owner}/+archive/#{repo}"
key_id = Chef::HTTP::Simple.new(url).get("signing_key_fingerprint").delete('"')
install_key_from_keyserver(key_id, "keyserver.ubuntu.com")
rescue Net::HTTPServerException => e
raise "Could not access Launchpad ppa API: #{e.message}"
end
def is_ppa_url?(url)
url.start_with?("ppa:")
end
def make_ppa_url(ppa)
return unless is_ppa_url?(ppa)
owner, repo = ppa[4..-1].split("/")
repo ||= "ppa"
install_ppa_key(owner, repo)
"http://ppa.launchpad.net/#{owner}/#{repo}/ubuntu"
end
def build_repo(uri, distribution, components, trusted, arch, add_src = false)
uri = make_ppa_url(uri) if is_ppa_url?(uri)
uri = '"' + uri + '"' unless uri.start_with?("'", '"')
components = Array(components).join(" ")
options = []
options << "arch=#{arch}" if arch
options << "trusted=yes" if trusted
optstr = unless options.empty?
"[" + options.join(" ") + "]"
end
info = [ optstr, uri, distribution, components ].compact.join(" ")
repo = "deb #{info}\n"
repo << "deb-src #{info}\n" if add_src
repo
end
end
end
end
Chef::Provider::Noop.provides :apt_repository
end
end
end

View File

@@ -1,105 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/provider/apt_update'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Thom May (<thom@chef.io>)
# Copyright:: Copyright (c) 2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/provider"
require "chef_compat/copied_from_chef/chef/provider/noop"
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Provider < (defined?(::Chef::Provider) ? ::Chef::Provider : Object)
class AptUpdate < (defined?(::Chef::Provider::AptUpdate) ? ::Chef::Provider::AptUpdate : Chef::Provider)
use_inline_resources
extend Chef::Mixin::Which
provides :apt_update do
which("apt-get")
end
APT_CONF_DIR = "/etc/apt/apt.conf.d"
STAMP_DIR = "/var/lib/apt/periodic"
def whyrun_supported?
true
end
def load_current_resource
end
action :periodic do
if !apt_up_to_date?
converge_by "update new lists of packages" do
do_update
end
end
end
action :update do
converge_by "force update new lists of packages" do
do_update
end
end
private
# Determines whether we need to run `apt-get update`
#
# @return [Boolean]
def apt_up_to_date?
::File.exist?("#{STAMP_DIR}/update-success-stamp") &&
::File.mtime("#{STAMP_DIR}/update-success-stamp") > Time.now - new_resource.frequency
end
def do_update
[STAMP_DIR, APT_CONF_DIR].each do |d|
declare_resource(:directory, d) do
recursive true
end
end
declare_resource(:file, "#{APT_CONF_DIR}/15update-stamp") do
content "APT::Update::Post-Invoke-Success {\"touch #{STAMP_DIR}/update-success-stamp 2>/dev/null || true\";};\n"
action :create_if_missing
end
declare_resource(:execute, "apt-get -q update")
end
end
end
end
Chef::Provider::Noop.provides :apt_update
end
end
end

View File

@@ -1,56 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/provider/noop'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Thom May (<thom@chef.io>)
# Copyright:: Copyright (c) 2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Provider < (defined?(::Chef::Provider) ? ::Chef::Provider : Object)
class Noop < (defined?(::Chef::Provider::Noop) ? ::Chef::Provider::Noop : Chef::Provider)
def load_current_resource; end
def respond_to_missing?(method_sym, include_private = false)
method_sym.to_s.start_with?("action_") || super
end
def method_missing(method_sym, *arguments, &block)
if method_sym.to_s =~ /^action_/
Chef::Log.debug("NoOp-ing for #{method_sym}")
else
super
end
end
end
end
end
end
end
end

View File

@@ -1,132 +0,0 @@
# This file was generated by Chef
# Do NOT modify this file by hand.
[<%= @config.repositoryid %>]
name=<%= @config.description %>
<% if @config.baseurl %>
baseurl=<%= case @config.baseurl
when Array
@config.baseurl.join("\n")
else
@config.baseurl
end %>
<% end -%>
<% if @config.cost %>
cost=<%= @config.cost %>
<% end %>
<% if @config.enabled %>
enabled=1
<% else %>
enabled=0
<% end %>
<% if @config.enablegroups %>
enablegroups=1
<% end %>
<% if @config.exclude %>
exclude=<%= @config.exclude %>
<% end %>
<% if @config.failovermethod %>
failovermethod=<%= @config.failovermethod %>
<% end %>
<% if @config.fastestmirror_enabled %>
fastestmirror_enabled=1
<% else %>
fastestmirror_enabled=0
<% end %>
<% if @config.gpgcheck %>
gpgcheck=1
<% else %>
gpgcheck=0
<% end %>
<% if @config.gpgkey %>
gpgkey=<%= case @config.gpgkey
when Array
@config.gpgkey.join("\n ")
else
@config.gpgkey
end %>
<% end -%>
<% if @config.http_caching %>
http_caching=<%= @config.http_caching %>
<% end %>
<% if @config.include_config %>
include=<%= @config.include_config %>
<% end %>
<% if @config.includepkgs %>
includepkgs=<%= @config.includepkgs %>
<% end %>
<% if @config.keepalive %>
keepalive=1
<% end %>
<% if @config.metadata_expire %>
metadata_expire=<%= @config.metadata_expire %>
<% end %>
<% if @config.mirrorlist %>
mirrorlist=<%= @config.mirrorlist %>
<% end %>
<% if @config.mirror_expire %>
mirror_expire=<%= @config.mirror_expire %>
<% end %>
<% if @config.mirrorlist_expire %>
mirrorlist_expire=<%= @config.mirrorlist_expire %>
<% end %>
<% if @config.priority %>
priority=<%= @config.priority %>
<% end %>
<% if @config.proxy %>
proxy=<%= @config.proxy %>
<% end %>
<% if @config.proxy_username %>
proxy_username=<%= @config.proxy_username %>
<% end %>
<% if @config.proxy_password %>
proxy_password=<%= @config.proxy_password %>
<% end %>
<% if @config.username %>
username=<%= @config.username %>
<% end %>
<% if @config.password %>
password=<%= @config.password %>
<% end %>
<% if @config.repo_gpgcheck %>
repo_gpgcheck=1
<% end %>
<% if @config.max_retries %>
retries=<%= @config.max_retries %>
<% end %>
<% if @config.report_instanceid %>
report_instanceid=<%= @config.report_instanceid %>
<% end %>
<% if @config.skip_if_unavailable %>
skip_if_unavailable=1
<% end %>
<% if @config.sslcacert %>
sslcacert=<%= @config.sslcacert %>
<% end %>
<% if @config.sslclientcert %>
sslclientcert=<%= @config.sslclientcert %>
<% end %>
<% if @config.sslclientkey %>
sslclientkey=<%= @config.sslclientkey %>
<% end %>
<% unless @config.sslverify.nil? %>
sslverify=<%= ( @config.sslverify ) ? 'true' : 'false' %>
<% end %>
<% if @config.timeout %>
timeout=<%= @config.timeout %>
<% end %>
<% if @config.options -%>
<% @config.options.each do |key, value| -%>
<%= key %>=<%=
case value
when Array
value.join("\n ")
when TrueClass
'1'
when FalseClass
'0'
else
value
end %>
<% end -%>
<% end -%>

View File

@@ -1,253 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/provider/systemd_unit'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Nathan Williams (<nath.e.will@gmail.com>)
# Copyright:: Copyright 2016, Nathan Williams
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/provider"
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Provider < (defined?(::Chef::Provider) ? ::Chef::Provider : Object)
class SystemdUnit < (defined?(::Chef::Provider::SystemdUnit) ? ::Chef::Provider::SystemdUnit : Chef::Provider)
include Chef::Mixin::Which
include Chef::Mixin::ShellOut
provides :systemd_unit, os: "linux"
def load_current_resource
@current_resource = Chef::Resource::SystemdUnit.new(new_resource.name)
current_resource.content(::File.read(unit_path)) if ::File.exist?(unit_path)
current_resource.user(new_resource.user)
current_resource.enabled(enabled?)
current_resource.active(active?)
current_resource.masked(masked?)
current_resource.static(static?)
current_resource.triggers_reload(new_resource.triggers_reload)
current_resource
end
def define_resource_requirements
super
requirements.assert(:create) do |a|
a.assertion { IniParse.parse(new_resource.to_ini) }
a.failure_message "Unit content is not valid INI text"
end
end
def action_create
if current_resource.content != new_resource.to_ini
converge_by("creating unit: #{new_resource.name}") do
manage_unit_file(:create)
daemon_reload if new_resource.triggers_reload
end
end
end
def action_delete
if ::File.exist?(unit_path)
converge_by("deleting unit: #{new_resource.name}") do
manage_unit_file(:delete)
daemon_reload if new_resource.triggers_reload
end
end
end
def action_enable
if current_resource.static
Chef::Log.debug("#{new_resource.name} is a static unit, enabling is a NOP.")
end
unless current_resource.enabled || current_resource.static
converge_by("enabling unit: #{new_resource.name}") do
systemctl_execute!(:enable, new_resource.name)
end
end
end
def action_disable
if current_resource.static
Chef::Log.debug("#{new_resource.name} is a static unit, disabling is a NOP.")
end
if current_resource.enabled && !current_resource.static
converge_by("disabling unit: #{new_resource.name}") do
systemctl_execute!(:disable, new_resource.name)
end
end
end
def action_mask
unless current_resource.masked
converge_by("masking unit: #{new_resource.name}") do
systemctl_execute!(:mask, new_resource.name)
end
end
end
def action_unmask
if current_resource.masked
converge_by("unmasking unit: #{new_resource.name}") do
systemctl_execute!(:unmask, new_resource.name)
end
end
end
def action_start
unless current_resource.active
converge_by("starting unit: #{new_resource.name}") do
systemctl_execute!(:start, new_resource.name)
end
end
end
def action_stop
if current_resource.active
converge_by("stopping unit: #{new_resource.name}") do
systemctl_execute!(:stop, new_resource.name)
end
end
end
def action_restart
converge_by("restarting unit: #{new_resource.name}") do
systemctl_execute!(:restart, new_resource.name)
end
end
def action_reload
if current_resource.active
converge_by("reloading unit: #{new_resource.name}") do
systemctl_execute!(:reload, new_resource.name)
end
else
Chef::Log.debug("#{new_resource.name} is not active, skipping reload.")
end
end
def action_try_restart
converge_by("try-restarting unit: #{new_resource.name}") do
systemctl_execute!("try-restart", new_resource.name)
end
end
def action_reload_or_restart
converge_by("reload-or-restarting unit: #{new_resource.name}") do
systemctl_execute!("reload-or-restart", new_resource.name)
end
end
def action_reload_or_try_restart
converge_by("reload-or-try-restarting unit: #{new_resource.name}") do
systemctl_execute!("reload-or-try-restart", new_resource.name)
end
end
def active?
systemctl_execute("is-active", new_resource.name).exitstatus == 0
end
def enabled?
systemctl_execute("is-enabled", new_resource.name).exitstatus == 0
end
def masked?
systemctl_execute(:status, new_resource.name).stdout.include?("masked")
end
def static?
systemctl_execute("is-enabled", new_resource.name).stdout.include?("static")
end
private
def unit_path
if new_resource.user
"/etc/systemd/user/#{new_resource.name}"
else
"/etc/systemd/system/#{new_resource.name}"
end
end
def manage_unit_file(action = :nothing)
Chef::Resource::File.new(unit_path, run_context).tap do |f|
f.owner "root"
f.group "root"
f.mode "0644"
f.content new_resource.to_ini
end.run_action(action)
end
def daemon_reload
shell_out_with_systems_locale!("#{systemctl_path} daemon-reload")
end
def systemctl_execute!(action, unit)
shell_out_with_systems_locale!("#{systemctl_cmd} #{action} #{unit}", systemctl_opts)
end
def systemctl_execute(action, unit)
shell_out("#{systemctl_cmd} #{action} #{unit}", systemctl_opts)
end
def systemctl_cmd
@systemctl_cmd ||= "#{systemctl_path} #{systemctl_args}"
end
def systemctl_path
@systemctl_path ||= which("systemctl")
end
def systemctl_args
@systemctl_args ||= new_resource.user ? "--user" : "--system"
end
def systemctl_opts
@systemctl_opts ||=
if new_resource.user
{
:user => new_resource.user,
:environment => {
"DBUS_SESSION_BUS_ADDRESS" => "unix:path=/run/user/#{node['etc']['passwd'][new_resource.user]['uid']}/bus",
},
}
else
{}
end
end
end
end
end
end
end
end

View File

@@ -1,136 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/provider/yum_repository'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Thom May (<thom@chef.io>)
# Copyright:: Copyright (c) 2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/resource"
require "chef_compat/copied_from_chef/chef/dsl/declare_resource"
require "chef_compat/copied_from_chef/chef/provider/noop"
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Provider < (defined?(::Chef::Provider) ? ::Chef::Provider : Object)
class YumRepository < (defined?(::Chef::Provider::YumRepository) ? ::Chef::Provider::YumRepository : Chef::Provider)
use_inline_resources
extend Chef::Mixin::Which
provides :yum_repository do
which "yum"
end
def whyrun_supported?; true; end
def load_current_resource; end
action :create do
declare_resource(:template, "/etc/yum.repos.d/#{new_resource.repositoryid}.repo") do
if template_available?(new_resource.source)
source new_resource.source
else
source ::File.expand_path("../support/yum_repo.erb", __FILE__)
local true
end
sensitive new_resource.sensitive
variables(config: new_resource)
mode new_resource.mode
if new_resource.make_cache
notifies :run, "execute[yum clean metadata #{new_resource.repositoryid}]", :immediately if new_resource.clean_metadata || new_resource.clean_headers
notifies :run, "execute[yum-makecache-#{new_resource.repositoryid}]", :immediately
notifies :create, "ruby_block[yum-cache-reload-#{new_resource.repositoryid}]", :immediately
end
end
declare_resource(:execute, "yum clean metadata #{new_resource.repositoryid}") do
command "yum clean metadata --disablerepo=* --enablerepo=#{new_resource.repositoryid}"
action :nothing
end
# get the metadata for this repo only
declare_resource(:execute, "yum-makecache-#{new_resource.repositoryid}") do
command "yum -q -y makecache --disablerepo=* --enablerepo=#{new_resource.repositoryid}"
action :nothing
only_if { new_resource.enabled }
end
# reload internal Chef yum cache
declare_resource(:ruby_block, "yum-cache-reload-#{new_resource.repositoryid}") do
block { Chef::Provider::Package::Yum::YumCache.instance.reload }
action :nothing
end
end
action :delete do
# clean the repo cache first
declare_resource(:execute, "yum clean all #{new_resource.repositoryid}") do
command "yum clean all --disablerepo=* --enablerepo=#{new_resource.repositoryid}"
only_if "yum repolist all | grep -P '^#{new_resource.repositoryid}([ \t]|$)'"
end
declare_resource(:file, "/etc/yum.repos.d/#{new_resource.repositoryid}.repo") do
action :delete
notifies :create, "ruby_block[yum-cache-reload-#{new_resource.repositoryid}]", :immediately
end
declare_resource(:ruby_block, "yum-cache-reload-#{new_resource.repositoryid}") do
block { Chef::Provider::Package::Yum::YumCache.instance.reload }
action :nothing
end
end
action :makecache do
declare_resource(:execute, "yum-makecache-#{new_resource.repositoryid}") do
command "yum -q -y makecache --disablerepo=* --enablerepo=#{new_resource.repositoryid}"
action :run
only_if { new_resource.enabled }
end
declare_resource(:ruby_block, "yum-cache-reload-#{new_resource.repositoryid}") do
block { Chef::Provider::Package::Yum::YumCache.instance.reload }
action :run
end
end
alias_method :action_add, :action_create
alias_method :action_remove, :action_delete
def template_available?(path)
!path.nil? && run_context.has_template_in_cookbook?(new_resource.cookbook_name, path)
end
end
end
end
Chef::Provider::Noop.provides :yum_repository
end
end
end

View File

@@ -1,214 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/resource'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
require "chef_compat/copied_from_chef/chef/resource/action_class"
require "chef_compat/copied_from_chef/chef/provider"
require "chef_compat/copied_from_chef/chef/mixin/properties"
require "chef_compat/copied_from_chef/chef/dsl/universal"
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Resource < (defined?(::Chef::Resource) ? ::Chef::Resource : Object)
include Chef::Mixin::Properties
property :name, String, coerce: proc { |v| v.is_a?(Array) ? v.join(", ") : v.to_s }, desired_state: false
def initialize(name, run_context = nil)
super if defined?(::Chef::Resource)
name(name) unless name.nil?
@run_context = run_context
@noop = nil
@before = nil
@params = Hash.new
@provider = nil
@allowed_actions = self.class.allowed_actions.to_a
@action = self.class.default_action
@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
def action(arg = nil)
if arg
arg = Array(arg).map(&:to_sym)
arg.each do |action|
validate(
{ action: action },
{ action: { kind_of: Symbol, equal_to: allowed_actions } }
)
end
@action = arg
else
@action
end
end
alias_method :action=, :action
class UnresolvedSubscribes < (defined?(::Chef::Resource::UnresolvedSubscribes) ? ::Chef::Resource::UnresolvedSubscribes : self)
alias_method :to_s, :name
alias_method :declared_key, :name
end
def state_for_resource_reporter
state = {}
state_properties = self.class.state_properties
state_properties.each do |property|
if property.identity? || property.is_set?(self)
state[property.name] = property.sensitive? ? "*sensitive value suppressed*" : send(property.name)
end
end
state
end
alias_method :state, :state_for_resource_reporter
def identity
result = {}
identity_properties = self.class.identity_properties
identity_properties.each do |property|
result[property.name] = send(property.name)
end
return result.values.first if identity_properties.size == 1
result
end
attr_reader :resource_initializing
def resource_initializing=(value)
if value
@resource_initializing = true
else
remove_instance_variable(:@resource_initializing)
end
end
def to_hash
# Grab all current state, then any other ivars (backcompat)
result = {}
self.class.state_properties.each do |p|
result[p.name] = p.get(self)
end
safe_ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS
safe_ivars.each do |iv|
key = iv.to_s.sub(/^@/, "").to_sym
next if result.has_key?(key)
result[key] = instance_variable_get(iv)
end
result
end
def self.identity_property(name = nil)
result = identity_properties(*Array(name))
if result.size > 1
raise Chef::Exceptions::MultipleIdentityError, "identity_property cannot be called on an object with more than one identity property (#{result.map { |r| r.name }.join(", ")})."
end
result.first
end
attr_accessor :allowed_actions
def allowed_actions(value = NOT_PASSED)
if value != NOT_PASSED
self.allowed_actions = value
end
@allowed_actions
end
def resource_name
@resource_name || self.class.resource_name
end
def self.use_automatic_resource_name
automatic_name = convert_to_snake_case(self.name.split("::")[-1])
resource_name automatic_name
end
def self.allowed_actions(*actions)
@allowed_actions ||=
if superclass.respond_to?(:allowed_actions)
superclass.allowed_actions.dup
else
[ :nothing ]
end
@allowed_actions |= actions.flatten
end
def self.allowed_actions=(value)
@allowed_actions = value.uniq
end
def self.default_action(action_name = NOT_PASSED)
unless action_name.equal?(NOT_PASSED)
@default_action = Array(action_name).map(&:to_sym)
self.allowed_actions |= @default_action
end
if @default_action
@default_action
elsif superclass.respond_to?(:default_action)
superclass.default_action
else
[:nothing]
end
end
def self.default_action=(action_name)
default_action action_name
end
def self.action(action, &recipe_block)
action = action.to_sym
declare_action_class
action_class.action(action, &recipe_block)
self.allowed_actions += [ action ]
default_action action if Array(default_action) == [:nothing]
end
def self.load_current_value(&load_block)
define_method(:load_current_value!, &load_block)
end
def current_value_does_not_exist!
raise Chef::Exceptions::CurrentValueDoesNotExist
end
def self.action_class(&block)
return @action_class if @action_class && !block
# If the superclass needed one, then we need one as well.
if block || (superclass.respond_to?(:action_class) && superclass.action_class)
@action_class = declare_action_class(&block)
end
@action_class
end
def self.declare_action_class(&block)
@action_class ||= begin
if superclass.respond_to?(:action_class)
base_provider = superclass.action_class
end
base_provider ||= Chef::Provider
resource_class = self
Class.new(base_provider) do
include ActionClass
self.resource_class = resource_class
end
end
@action_class.class_eval(&block) if block
@action_class
end
FORBIDDEN_IVARS = [:@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]
class << self
end
@@sorted_descendants = nil
module DeprecatedLWRPClass
CopiedFromChef.extend_chef_module(::Chef::Resource::DeprecatedLWRPClass, self) if defined?(::Chef::Resource::DeprecatedLWRPClass)
end
end
end
end
end
end

View File

@@ -1,114 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/resource/action_class'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: John Keiser (<jkeiser@chef.io)
# Copyright:: Copyright 2015-2016, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/dsl/recipe"
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Resource < (defined?(::Chef::Resource) ? ::Chef::Resource : Object)
module ActionClass
CopiedFromChef.extend_chef_module(::Chef::Resource::ActionClass, self) if defined?(::Chef::Resource::ActionClass)
include Chef::DSL::Recipe
def to_s
"#{new_resource || "<no resource>"} action #{action ? action.inspect : "<no action>"}"
end
def whyrun_supported?
true
end
#
# If load_current_value! is defined on the resource, use that.
#
def load_current_resource
if new_resource.respond_to?(:load_current_value!)
# dup the resource and then reset desired-state properties.
current_resource = new_resource.dup
# We clear desired state in the copy, because it is supposed to be actual state.
# We keep identity properties and non-desired-state, which are assumed to be
# "control" values like `recurse: true`
current_resource.class.properties.each do |name, property|
if property.desired_state? && !property.identity? && !property.name_property?
property.reset(current_resource)
end
end
# Call the actual load_current_value! method. If it raises
# CurrentValueDoesNotExist, set current_resource to `nil`.
begin
# If the user specifies load_current_value do |desired_resource|, we
# pass in the desired resource as well as the current one.
if current_resource.method(:load_current_value!).arity > 0
current_resource.load_current_value!(new_resource)
else
current_resource.load_current_value!
end
rescue Chef::Exceptions::CurrentValueDoesNotExist
current_resource = nil
end
end
@current_resource = current_resource
end
def self.included(other)
other.extend(ClassMethods)
other.use_inline_resources
other.include_resource_dsl true
end
module ClassMethods
CopiedFromChef.extend_chef_module(::Chef::Resource::ActionClass::ClassMethods, self) if defined?(::Chef::Resource::ActionClass::ClassMethods)
#
# The Chef::Resource class this ActionClass was declared against.
#
# @return [Class] The Chef::Resource class this ActionClass was declared against.
#
attr_accessor :resource_class
def to_s
"#{resource_class} action provider"
end
def inspect
to_s
end
end
end
end
end
end
end
end

View File

@@ -1,65 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/resource/apt_repository'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Thom May (<thom@chef.io>)
# Copyright:: Copyright (c) 2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/resource"
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Resource < (defined?(::Chef::Resource) ? ::Chef::Resource : Object)
class AptRepository < (defined?(::Chef::Resource::AptRepository) ? ::Chef::Resource::AptRepository : Chef::Resource)
resource_name :apt_repository
provides :apt_repository
property :repo_name, String, name_property: true
property :uri, String
property :distribution, [ String, nil, false ], default: lazy { node["lsb"]["codename"] }, nillable: true, coerce: proc { |x| x ? x : nil }
property :components, Array, default: []
property :arch, [String, nil, false], default: nil, nillable: true, coerce: proc { |x| x ? x : nil }
property :trusted, [TrueClass, FalseClass], default: false
# whether or not to add the repository as a source repo, too
property :deb_src, [TrueClass, FalseClass], default: false
property :keyserver, [String, nil, false], default: "keyserver.ubuntu.com", nillable: true, coerce: proc { |x| x ? x : nil }
property :key, [String, nil, false], default: nil, nillable: true, coerce: proc { |x| x ? x : nil }
property :key_proxy, [String, nil, false], default: nil, nillable: true, coerce: proc { |x| x ? x : nil }
property :cookbook, [String, nil, false], default: nil, desired_state: false, nillable: true, coerce: proc { |x| x ? x : nil }
property :cache_rebuild, [TrueClass, FalseClass], default: true, desired_state: false
default_action :add
allowed_actions :add, :remove
end
end
end
end
end
end

View File

@@ -1,52 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/resource/apt_update'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Thom May (<thom@chef.io>)
# Copyright:: Copyright (c) 2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/resource"
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Resource < (defined?(::Chef::Resource) ? ::Chef::Resource : Object)
class AptUpdate < (defined?(::Chef::Resource::AptUpdate) ? ::Chef::Resource::AptUpdate : Chef::Resource)
resource_name :apt_update
provides :apt_update
property :frequency, Integer, default: 86_400
default_action :periodic
allowed_actions :update, :periodic
end
end
end
end
end
end

View File

@@ -1,81 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/resource/systemd_unit'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Nathan Williams (<nath.e.will@gmail.com>)
# Copyright:: Copyright 2016, Nathan Williams
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/resource"
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Resource < (defined?(::Chef::Resource) ? ::Chef::Resource : Object)
class SystemdUnit < (defined?(::Chef::Resource::SystemdUnit) ? ::Chef::Resource::SystemdUnit : Chef::Resource)
resource_name :systemd_unit
default_action :nothing
allowed_actions :create, :delete,
:enable, :disable,
:mask, :unmask,
:start, :stop,
:restart, :reload,
:try_restart, :reload_or_restart,
:reload_or_try_restart
property :enabled, [TrueClass, FalseClass]
property :active, [TrueClass, FalseClass]
property :masked, [TrueClass, FalseClass]
property :static, [TrueClass, FalseClass]
property :user, String, desired_state: false
property :content, [String, Hash]
property :triggers_reload, [TrueClass, FalseClass],
default: true, desired_state: false
def to_ini
case content
when Hash
IniParse.gen do |doc|
content.each_pair do |sect, opts|
doc.section(sect) do |section|
opts.each_pair do |opt, val|
section.option(opt, val)
end
end
end
end.to_s
else
content.to_s
end
end
end
end
end
end
end
end

View File

@@ -1,97 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/resource/yum_repository'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Thom May (<thom@chef.io>)
# Copyright:: Copyright (c) 2016 Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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 "chef_compat/copied_from_chef/chef/resource"
class Chef < (defined?(::Chef) ? ::Chef : Object)
class Resource < (defined?(::Chef::Resource) ? ::Chef::Resource : Object)
class YumRepository < (defined?(::Chef::Resource::YumRepository) ? ::Chef::Resource::YumRepository : Chef::Resource)
resource_name :yum_repository
provides :yum_repository
# http://linux.die.net/man/5/yum.conf
property :baseurl, [String, Array], regex: /.*/
property :cost, String, regex: /^\d+$/
property :clean_headers, [TrueClass, FalseClass], default: false # deprecated
property :clean_metadata, [TrueClass, FalseClass], default: true
property :description, String, regex: /.*/, default: "Yum Repository"
property :enabled, [TrueClass, FalseClass], default: true
property :enablegroups, [TrueClass, FalseClass]
property :exclude, String, regex: /.*/
property :failovermethod, String, equal_to: %w{priority roundrobin}
property :fastestmirror_enabled, [TrueClass, FalseClass]
property :gpgcheck, [TrueClass, FalseClass], default: true
property :gpgkey, [String, Array], regex: /.*/
property :http_caching, String, equal_to: %w{packages all none}
property :include_config, String, regex: /.*/
property :includepkgs, String, regex: /.*/
property :keepalive, [TrueClass, FalseClass]
property :make_cache, [TrueClass, FalseClass], default: true
property :max_retries, [String, Integer]
property :metadata_expire, String, regex: [/^\d+$/, /^\d+[mhd]$/, /never/]
property :mirrorexpire, String, regex: /.*/
property :mirrorlist, String, regex: /.*/
property :mirror_expire, String, regex: [/^\d+$/, /^\d+[mhd]$/]
property :mirrorlist_expire, String, regex: [/^\d+$/, /^\d+[mhd]$/]
property :mode, default: "0644"
property :priority, String, regex: /^(\d?[0-9]|[0-9][0-9])$/
property :proxy, String, regex: /.*/
property :proxy_username, String, regex: /.*/
property :proxy_password, String, regex: /.*/
property :username, String, regex: /.*/
property :password, String, regex: /.*/
property :repo_gpgcheck, [TrueClass, FalseClass]
property :report_instanceid, [TrueClass, FalseClass]
property :repositoryid, String, regex: /.*/, name_property: true
property :skip_if_unavailable, [TrueClass, FalseClass]
property :source, String, regex: /.*/
property :sslcacert, String, regex: /.*/
property :sslclientcert, String, regex: /.*/
property :sslclientkey, String, regex: /.*/
property :sslverify, [TrueClass, FalseClass]
property :timeout, String, regex: /^\d+$/
property :options, Hash
default_action :create
allowed_actions :create, :remove, :makecache, :add, :delete
# provide compatibility with the yum cookbook < 3.0 properties
alias_method :url, :baseurl
alias_method :keyurl, :gpgkey
end
end
end
end
end
end

View File

@@ -1,174 +0,0 @@
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!
#
# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE
#
begin
require 'chef/resource_builder'
rescue LoadError; end
require 'chef_compat/copied_from_chef'
class Chef
module ::ChefCompat
module CopiedFromChef
#
# Author:: Lamont Granquist (<lamont@chef.io>)
# Copyright:: Copyright 2015-2016, Chef Software, Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
# NOTE: this was extracted from the Recipe DSL mixin, relevant specs are in spec/unit/recipe_spec.rb
class Chef < (defined?(::Chef) ? ::Chef : Object)
class ResourceBuilder < (defined?(::Chef::ResourceBuilder) ? ::Chef::ResourceBuilder : Object)
attr_reader :type
attr_reader :name
attr_reader :created_at
attr_reader :params
attr_reader :run_context
attr_reader :cookbook_name
attr_reader :recipe_name
attr_reader :enclosing_provider
attr_reader :resource
# FIXME (ruby-2.1 syntax): most of these are mandatory
def initialize(type: nil, name: nil, created_at: nil, params: nil, run_context: nil, cookbook_name: nil, recipe_name: nil, enclosing_provider: nil)
super if defined?(::Chef::ResourceBuilder)
@type = type
@name = name
@created_at = created_at
@params = params
@run_context = run_context
@cookbook_name = cookbook_name
@recipe_name = recipe_name
@enclosing_provider = enclosing_provider
end
def build(&block)
raise ArgumentError, "You must supply a name when declaring a #{type} resource" if name.nil?
@resource = resource_class.new(name, run_context)
if resource.resource_name.nil?
raise Chef::Exceptions::InvalidResourceSpecification, "#{resource}.resource_name is `nil`! Did you forget to put `provides :blah` or `resource_name :blah` in your resource class?"
end
resource.source_line = created_at
resource.declared_type = type
# If we have a resource like this one, we want to steal its state
# This behavior is very counter-intuitive and should be removed.
# See CHEF-3694, https://tickets.opscode.com/browse/CHEF-3694
# Moved to this location to resolve CHEF-5052, https://tickets.opscode.com/browse/CHEF-5052
if prior_resource
resource.load_from(prior_resource)
end
resource.cookbook_name = cookbook_name
resource.recipe_name = recipe_name
# Determine whether this resource is being created in the context of an enclosing Provider
resource.enclosing_provider = enclosing_provider
# XXX: this is required for definition params inside of the scope of a
# subresource to work correctly.
resource.params = params
# Evaluate resource attribute DSL
if block_given?
resource.resource_initializing = true
begin
resource.instance_eval(&block)
ensure
resource.resource_initializing = false
end
end
# emit a cloned resource warning if it is warranted
if prior_resource
if is_trivial_resource?(prior_resource) && identicalish_resources?(prior_resource, resource)
emit_harmless_cloning_debug
else
emit_cloned_resource_warning
end
end
# Run optional resource hook
resource.after_created
resource
end
private
def resource_class
# Checks the new platform => short_name => resource mapping initially
# then fall back to the older approach (Chef::Resource.const_get) for
# backward compatibility
@resource_class ||= Chef::Resource.resource_for_node(type, run_context.node)
end
def is_trivial_resource?(resource)
trivial_resource = resource_class.new(name, run_context)
# force un-lazy the name property on the created trivial resource
name_property = resource_class.properties.find { |sym, p| p.name_property? }
trivial_resource.send(name_property[0]) unless name_property.nil?
identicalish_resources?(trivial_resource, resource)
end
# this is an equality test specific to checking for 3694 cloning warnings
def identicalish_resources?(first, second)
skipped_ivars = [ :@source_line, :@cookbook_name, :@recipe_name, :@params, :@elapsed_time, :@declared_type ]
checked_ivars = ( first.instance_variables | second.instance_variables ) - skipped_ivars
non_matching_ivars = checked_ivars.reject do |iv|
if iv == :@action && ( [first.instance_variable_get(iv)].flatten == [:nothing] || [second.instance_variable_get(iv)].flatten == [:nothing] )
# :nothing action on either side of the comparison always matches
true
else
first.instance_variable_get(iv) == second.instance_variable_get(iv)
end
end
Chef::Log.debug("ivars which did not match with the prior resource: #{non_matching_ivars}")
non_matching_ivars.empty?
end
def emit_cloned_resource_warning
message = "Cloning resource attributes for #{resource} from prior resource (CHEF-3694)"
message << "\nPrevious #{prior_resource}: #{prior_resource.source_line}" if prior_resource.source_line
message << "\nCurrent #{resource}: #{resource.source_line}" if resource.source_line
Chef.log_deprecation(message)
end
def emit_harmless_cloning_debug
Chef::Log.debug("Harmless resource cloning from #{prior_resource}:#{prior_resource.source_line} to #{resource}:#{resource.source_line}")
end
def prior_resource
@prior_resource ||=
begin
key = "#{type}[#{name}]"
run_context.resource_collection.lookup_local(key)
rescue Chef::Exceptions::ResourceNotFound
nil
end
end
end
end
require "chef_compat/copied_from_chef/chef/resource"
end
end
end

View File

@@ -1,8 +0,0 @@
require 'chef_compat/monkeypatches'
require 'chef_compat/copied_from_chef/chef/mixin/properties'
module ChefCompat
module Mixin
Properties = ChefCompat::CopiedFromChef::Chef::Mixin::Properties
end
end

View File

@@ -1,41 +0,0 @@
class Chef
class RunContext
class ChildRunContext < RunContext
# magic that lets us re-parse the ChildRunContext without erroring due to
# cheffish and chef-provisioning hooks having been loaded (on old versions of
# chef-client without the lazy hooks for those gems)
@__skip_method_checking = true
end
end
end
# fix to quiet constant redefined warnings
if defined?(Chef::RunContext::ChildRunContext::CHILD_STATE)
Chef::RunContext::ChildRunContext.send(:remove_const, :CHILD_STATE)
end
require 'chef_compat/monkeypatches/chef'
require 'chef_compat/monkeypatches/chef/exceptions'
require 'chef_compat/monkeypatches/chef/log'
require 'chef_compat/monkeypatches/chef/node'
require 'chef_compat/monkeypatches/chef/mixin/params_validate'
require 'chef_compat/monkeypatches/chef/property'
require 'chef_compat/monkeypatches/chef/provider'
require 'chef_compat/monkeypatches/chef/recipe' # copied from chef
require 'chef_compat/monkeypatches/chef/recipe_hook'
require 'chef_compat/monkeypatches/chef/resource'
require 'chef_compat/monkeypatches/chef/resource_builder'
require 'chef_compat/monkeypatches/chef/resource/lwrp_base'
require 'chef_compat/monkeypatches/chef/resource_collection'
require 'chef_compat/monkeypatches/chef/resource_collection/resource_list'
require 'chef_compat/monkeypatches/chef/resource_collection/resource_set'
require 'chef_compat/monkeypatches/chef/run_context' # copied from chef
require 'chef_compat/monkeypatches/chef/runner' # copied from chef
# fix for Chef::RunContext instance that has already been created
ObjectSpace.each_object(Chef::RunContext) do |run_context|
run_context.node.run_context = run_context
run_context.instance_variable_set(:@loaded_recipes_hash, {})
run_context.instance_variable_set(:@loaded_attributes_hash, {})
run_context.initialize_child_state
end

View File

@@ -1,33 +0,0 @@
class Chef
NOT_PASSED = Object.new if !defined?(NOT_PASSED)
# Earlier versions of Chef didn't have this message
module ChefCompatDeprecation
def log_deprecation(message, location=nil)
if !location
# Pick the first caller that is *not* part of the Chef or ChefCompat gem,
# that's the thing the user wrote.
chef_compat_gem_path = File.expand_path("../../..", __FILE__)
chef_gem_path = File.expand_path("../..",::Chef::Resource.instance_method(:initialize).source_location[0])
caller(0..10).each do |c|
if !c.start_with?(chef_gem_path) && !c.start_with?(chef_compat_gem_path)
location = c
break
end
end
end
begin
super
# Bleagh. `super_method` doesn't exist on older rubies and I haven't
# figured out a way to check for its existence otherwise.
rescue NoMethodError
Chef::Log.warn(message)
end
end
end
class<<self
prepend ChefCompatDeprecation
end
end

View File

@@ -1,10 +0,0 @@
require 'chef/exceptions'
class Chef
class Exceptions
# Used in Resource::ActionClass#load_current_resource to denote that
# the resource doesn't actually exist (for example, the file does not exist)
class CurrentValueDoesNotExist < RuntimeError; end unless defined?(CurrentValueDoesNotExist)
class CannotValidateStaticallyError < RuntimeError; end unless defined?(CannotValidateStaticallyError)
end
end

Some files were not shown because too many files have changed in this diff Show More