diff --git a/.README.md.un~ b/.README.md.un~ new file mode 100644 index 00000000..4c5d90e8 Binary files /dev/null and b/.README.md.un~ differ diff --git a/README.md b/README.md index 7d963d76..634eec20 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ # chef-third-party -This repository is maintaining all third party cookbooks used by binary.com. +This repository is maintaining all the third party cookbooks used by binary.com. Most of these cookbooks are slightly modified in order to suite binary.com needs. diff --git a/README.md~ b/README.md~ new file mode 100644 index 00000000..7d963d76 --- /dev/null +++ b/README.md~ @@ -0,0 +1,4 @@ +# chef-third-party + +This repository is maintaining all third party cookbooks used by binary.com. +Most of these cookbooks are slightly modified in order to suite binary.com needs. diff --git a/cookbooks/apt/.delivery/project.toml b/cookbooks/apt/.delivery/project.toml new file mode 100644 index 00000000..6d5e3617 --- /dev/null +++ b/cookbooks/apt/.delivery/project.toml @@ -0,0 +1 @@ +remote_file = "https://raw.githubusercontent.com/chef-cookbooks/community_cookbook_tools/master/delivery/project.toml" diff --git a/cookbooks/apt/.github/CODEOWNERS b/cookbooks/apt/.github/CODEOWNERS new file mode 100644 index 00000000..075caf0a --- /dev/null +++ b/cookbooks/apt/.github/CODEOWNERS @@ -0,0 +1 @@ +* @chef-cookbooks/cookbook_engineering_team diff --git a/cookbooks/apt/.github/ISSUE_TEMPLATE.md b/cookbooks/apt/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..651e753a --- /dev/null +++ b/cookbooks/apt/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,20 @@ +### Cookbook version +[Version of the cookbook where you are encountering the issue] + +### Chef-client version +[Version of chef-client in your environment] + +### Platform Details +[Operating system distribution and release version. Cloud provider if running in the cloud] + +### Scenario: +[What you are trying to achieve and you can't?] + +### Steps to Reproduce: +[If you are filing an issue what are the things we need to do in order to repro your problem? How are you using this cookbook or any resources it includes?] + +### Expected Result: +[What are you expecting to happen as the consequence of above reproduction steps?] + +### Actual Result: +[What actually happens after the reproduction steps? Include the error output or a link to a gist if possible.] diff --git a/cookbooks/apt/.github/PULL_REQUEST_TEMPLATE.md b/cookbooks/apt/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..b8c6d9f9 --- /dev/null +++ b/cookbooks/apt/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,14 @@ +### Description + +[Describe what this change achieves] + +### Issues Resolved + +[List any existing issues this PR resolves] + +### Check List + +- [ ] All tests pass. See +- [ ] New functionality includes testing. +- [ ] New functionality has been documented in the README if applicable +- [ ] All commits have been signed for the Developer Certificate of Origin. See diff --git a/cookbooks/apt/.gitignore b/cookbooks/apt/.gitignore new file mode 100644 index 00000000..7ef01fce --- /dev/null +++ b/cookbooks/apt/.gitignore @@ -0,0 +1,49 @@ +*.rbc +.config +coverage +InstalledFiles +lib/bundler/man +pkg +rdoc +spec/reports +test/tmp +test/version_tmp +tmp +*_Store +*~ +*# +.#* +\#*# +.*.sw[a-z] +*.un~ +*.tmp +*.bk +*.bkup + +# ruby/bundler files +.ruby-version +.ruby-gemset +.rvmrc +Gemfile.lock +.bundle +*.gem + +# YARD artifacts +.yardoc +_yardoc +doc/ +.idea + +# chef stuff +Berksfile.lock +.kitchen +.kitchen.local.yml +vendor/ +.coverage/ +.zero-knife.rb +Policyfile.lock.json + +# vagrant stuff +.vagrant/ +.vagrant.d/ +.kitchen/ diff --git a/cookbooks/apt/.travis.yml b/cookbooks/apt/.travis.yml new file mode 100644 index 00000000..48611c99 --- /dev/null +++ b/cookbooks/apt/.travis.yml @@ -0,0 +1,57 @@ +sudo: required +dist: trusty + +addons: + apt: + sources: + - chef-current-trusty + packages: + - chefdk + +# Don't `bundle install` which takes about 1.5 mins +install: echo "skip bundle install" + +branches: + only: + - master + +services: docker + +env: + matrix: + - INSTANCE=default-centos-7 + - INSTANCE=default-debian-8 + - INSTANCE=default-debian-9 + - INSTANCE=default-ubuntu-1404 + - INSTANCE=default-ubuntu-1604 + - INSTANCE=default-ubuntu-1804 + - INSTANCE=cacher-debian-8 + - INSTANCE=cacher-debian-9 + - INSTANCE=cacher-ubuntu-1604 + - INSTANCE=cacher-ubuntu-1404 + - INSTANCE=compile-time-ubuntu-1404 + - INSTANCE=compile-time-ubuntu-1604 + - INSTANCE=compile-time-ubuntu-1804 + - INSTANCE=compile-time-debian-8 + - INSTANCE=compile-time-debian-9 + - INSTANCE=resources-ubuntu-1404 + - INSTANCE=resources-ubuntu-1604 + - INSTANCE=resources-ubuntu-1804 + - INSTANCE=resources-debian-8 + - INSTANCE=resources-debian-9 + - INSTANCE=unattended-upgrades-ubuntu-1404 + +before_script: + - sudo iptables -L DOCKER || ( echo "DOCKER iptables chain missing" ; sudo iptables -N DOCKER ) + - eval "$(chef shell-init bash)" + - chef --version + - cookstyle --version + - foodcritic --version + +script: KITCHEN_LOCAL_YAML=kitchen.dokken.yml kitchen verify ${INSTANCE} + +matrix: + include: + - script: + - chef exec delivery local all + env: UNIT_AND_LINT=1 diff --git a/cookbooks/apt/Berksfile b/cookbooks/apt/Berksfile new file mode 100644 index 00000000..c91084f1 --- /dev/null +++ b/cookbooks/apt/Berksfile @@ -0,0 +1,7 @@ +source 'https://supermarket.chef.io' + +metadata + +group :integration do + cookbook 'test', path: './test/fixtures/cookbooks/test' +end diff --git a/cookbooks/apt/CHANGELOG.md b/cookbooks/apt/CHANGELOG.md index 6fa49a63..d2cf320b 100644 --- a/cookbooks/apt/CHANGELOG.md +++ b/cookbooks/apt/CHANGELOG.md @@ -2,9 +2,85 @@ This file is used to list changes made in each version of the apt cookbook. +## 7.1.1 (2018-10-11) + +- Allow to customize sender email for unattended-upgrades + +## 7.1.0 (2018-09-05) + +- Add the installation of dirmngr and gnupg to the apt default cookbook to support secure repositories +- Added support for the unattended-upgrade SyslogEnable configuration feature +- Added support for the unattended-upgrade SyslogFacility configuration feature + +## 7.0.0 (2018-04-06) + +### Breaking Change + +- This cookbook no longer includes apt_preference as that resource was moved into Chef Client 13.3. The cookbook now also requires Chef 13.3 or later. If you require support for an older release of Chef you will need to pin to a 6.X release. + +## 6.1.4 (2017-08-31) + +- Restores ignore_failure true on compile time update. +- name_property vs name_attribute in the resource + +## 6.1.3 (2017-07-19) + +- Fixed typo in readme +- Fixed config namespace in the 10dpkg-options file + +## 6.1.2 (2017-06-20) + +- restore backwards compatability by respecting node['apt']['periodic_update_min_delay'] + +## 6.1.1 (2017-06-20) + +- Remove action_class.class_eval usage that caused failures +- Remove wrong warning logs generated by apt_preference +- Fix wrong warning log in cacher-client recipe + +## 6.1.0 (2017-04-11) + +- Test with local delivery and not Rake +- Use proper value type for bsd-mailx package only_if/not_if block +- Update apache2 license string +- Convert apt_preference to a custom resource + +## 6.0.1 (2017-02-27) + +- Update cookbook description +- Testing updates for Chef 13 and fixes to the cacher recipe + +## 6.0.0 (2017-02-08) + +### Breaking changes + +- apt_update and apt_repository resources have been removed from the cookbook. These resources were both added to the chef-client itself. Due to this we now require Chef 12.9 or later, which has both of these resources built in. If you require compatibility with older chef-client releases you will need to pin to the 5.X release. + +### Other changes + +- apt_preference resource now properly required a pin_priority, which prevents us from writing out bad preference files that must be manually removed + +## 5.1.0 (2017-02-01) + +- Convert integration tests to inspec +- Add management of the /etc/apt/apt.conf.d/10dpkg-options file with new attributes. This allows tuning of how dpkg will handle package prompts during package installation. Note that Chef 12.19+ will automatically suppress package prompts + +## 5.0.1 (2016-12-22) + +- Avoid CHEF-3694 in apt_preferences resource +- Cookstyle fixes + +## 5.0.0 (2016-10-14) + +- Remove search logic from the cacher client cookbook and rework attribute structure. See the attributes file and readme for new structure. Determining what servers to cache against is better handled in a wrapper cookbook where you can define the exact search syntax yourself +- Corrected readme examples for the cacher client setup +- Depend on the latest compat_resource +- Define matchers for ChefSpec +- Testing updates to better test the various recipes and providers in the cookbook on Travis + ## 4.0.2 (2016-08-13) -- The cookbook requires Chef 12.1+ not 12.0. Update docs +- The cookbook requires Chef 12.1+ not 12.0\. Update docs - Test on Chef 12.1 to ensure compatibility - Restore compatibility with Chef < 12.4 diff --git a/cookbooks/apt/Gemfile b/cookbooks/apt/Gemfile index 4fe68dd7..c1dbddd8 100644 --- a/cookbooks/apt/Gemfile +++ b/cookbooks/apt/Gemfile @@ -1,6 +1,9 @@ +# This gemfile provides additional gems for testing and releasing this cookbook +# It is meant to be installed on top of ChefDK which provides the majority +# of the necessary gems for testing this cookbook +# +# Run 'chef exec bundle install' to install these dependencies + source 'https://rubygems.org' -gem 'tomlrb' -gem 'rake' -gem 'stove' gem 'community_cookbook_releaser' diff --git a/cookbooks/apt/MAINTAINERS.md b/cookbooks/apt/MAINTAINERS.md deleted file mode 100644 index 00eed8d7..00000000 --- a/cookbooks/apt/MAINTAINERS.md +++ /dev/null @@ -1,18 +0,0 @@ - - -# 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 simple majority of maintainers -for the relevant subsystems 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 -* [Tim Smith](https://github.com/tas50) - -# Maintainers -* [Jennifer Davis](https://github.com/sigje) -* [Tim Smith](https://github.com/tas50) -* [Thom May](https://github.com/thommay) diff --git a/cookbooks/apt/MAINTAINERS.toml b/cookbooks/apt/MAINTAINERS.toml deleted file mode 100644 index d3787664..00000000 --- a/cookbooks/apt/MAINTAINERS.toml +++ /dev/null @@ -1,41 +0,0 @@ -# -# This file is structured to be consumed by both humans and computers. -# It is a TOML document containing Markdown -# -[Preamble] - title = "Maintainers" - text = """ -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 simple majority of maintainers -for the relevant subsystems 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. -""" - -[Org] - [Org.Components] - [Org.Components.Core] - title = "Project Maintainer" - - lieutenant = 'tas50' - - maintainers = [ - 'sigje', - 'tas50', - 'thommay' - ] - -[people] - [people.sigje] - name = "Jennifer Davis" - github = "sigje" - - [people.tas50] - name = "Tim Smith" - github = "tas50" - - [people.thommay] - name = "Thom May" - github = "thommay" diff --git a/cookbooks/apt/README.md b/cookbooks/apt/README.md index b6c146dc..cf333662 100644 --- a/cookbooks/apt/README.md +++ b/cookbooks/apt/README.md @@ -1,87 +1,125 @@ # apt Cookbook + [![Build Status](https://img.shields.io/travis/chef-cookbooks/apt.svg)][travis] [![Cookbook Version](https://img.shields.io/cookbook/v/apt.svg)][cookbook] -This cookbook includes recipes to execute apt-get update to ensure the local APT package cache is up to date. There are recipes for managing the apt-cacher-ng caching proxy and proxy clients. It also includes a LWRP for managing APT repositories in /etc/apt/sources.list.d as well as an LWRP for pinning packages via /etc/apt/preferences.d. +This cookbook includes recipes to execute apt-get update to ensure the local APT package cache is up to date. There are recipes for managing the apt-cacher-ng caching proxy and proxy clients. It also includes a custom resource for pinning packages via /etc/apt/preferences.d. ## Requirements + ### Platforms + - Ubuntu 12.04+ - Debian 7+ May work with or without modification on other Debian derivatives. ### Chef -- Chef 12.1+ + +- Chef 13.3+ ### Cookbooks + - None ## Recipes + ### default + This recipe manually updates the timestamp file used to only run `apt-get update` if the cache is more than one day old. This recipe should appear first in the run list of Debian or Ubuntu nodes to ensure that the package cache is up to date before managing any `package` resources with Chef. This recipe also sets up a local cache directory for preseeding packages. -**Including the default recipe on a node that does not support apt (such as Windows) results in a noop.** +**Including the default recipe on a node that does not support apt (such as Windows or RHEL) results in a noop.** ### cacher-client -Configures the node to use the `apt-cacher-ng` server as a client. + +Configures the node to use a `apt-cacher-ng` server to cache apt requests. Configuration of the server to use is located in `default['apt']['cacher_client']['cacher_server']` which is a hash containing `host`, `port`, `proxy_ssl`, and `bypass` keys. Example: + +```json +{ + "apt": { + "cacher_client": { + "cacher_server": { + "host": "cache_server.mycorp.dmz", + "port": 1234, + "proxy_ssl": true, + "cache_bypass": { + "download.oracle.com": "http" + } + } + } + } +} +``` #### Bypassing the cache + Occasionally you may come across repositories that do not play nicely when the node is using an `apt-cacher-ng` server. You can configure `cacher-client` to bypass the server and connect directly to the repository with the `cache_bypass` attribute. -To do this, you need to override the `cache_bypass` attribute with an array of repositories, with each array key as the repository URL and value as the protocol to use: +To do this, you need to override the `cache_bypass` attribute with an hash of repositories, with each key as the repository URL and value as the protocol to use: ```json { "apt": { - "cache_bypass": { - "URL": "PROTOCOL" + "cacher_client": { + "cacher_server": { + "cache_bypass": { + "URL": "PROTOCOL" + } + } } } } ``` -For example, to prevent caching and directly connect to the repository at `download.oracle.com` via http: +For example, to prevent caching and directly connect to the repository at `download.oracle.com` via http and the repo at `nginx.org` via https ```json { "apt": { - "cache_bypass": { - "download.oracle.com": "http" + "cacher_client": { + "cacher_server": { + "cache_bypass": { + "download.oracle.com": "http", + "nginx.org": "https" + } + } } } } ``` ### cacher-ng -Installs the `apt-cacher-ng` package and service so the system can provide APT caching. You can check the usage report at [http://{hostname}:3142/acng-report.html](http://{hostname}:3142/acng-report.html). + +Installs the `apt-cacher-ng` package and service so the system can provide APT caching. You can check the usage report at . If you wish to help the `cacher-ng` recipe seed itself, you must now explicitly include the `cacher-client` recipe in your run list **after** `cacher-ng` or you will block your ability to install any packages (ie. `apt-cacher-ng`). ### unattended-upgrades + Installs and configures the `unattended-upgrades` package to provide automatic package updates. This can be configured to upgrade all packages or to just install security updates by setting `['apt']['unattended_upgrades']['allowed_origins']`. To pull just security updates, set `origins_patterns` to something like `["origin=Ubuntu,archive=trusty-security"]` (for Ubuntu trusty) or `["origin=Debian,label=Debian-Security"]` (for Debian). ## Attributes + ### General + - `['apt']['compile_time_update']` - force the default recipe to run `apt-get update` at compile time. -- `['apt']['periodic_update_min_delay']` - minimum delay (in seconds) beetween two actual executions of `apt-get update` by the `execute[apt-get-update-periodic]` resource, default is '86400' (24 hours) +- `['apt']['periodic_update_min_delay']` - minimum delay (in seconds) between two actual executions of `apt-get update` by the `execute[apt-get-update-periodic]` resource, default is '86400' (24 hours) ### Caching -- `['apt']['cacher_ipaddress']` - use a cacher server (or standard proxy server) not available via search + +- `['apt']['cacher_client']['cacher_server']` - Hash containing server information used by clients for caching. See the example in the recipes section above for the full format of the hash. - `['apt']['cacher_interface']` - interface to connect to the cacher-ng service, no default. -- `['apt']['cacher_port']` - port for the cacher-ng service (either client or server), default is '3142' -- `['apt']['cacher_ssl_support']` - indicates whether the cacher supports upstream SSL servers, default is 'false' +- `['apt']['cacher_port']` - port for the cacher-ng service (used by server recipe only), default is '3142' - `['apt']['cacher_dir']` - directory used by cacher-ng service, default is '/var/cache/apt-cacher-ng' -- `['apt']['cacher-client']['restrict_environment']` - restrict your node to using the `apt-cacher-ng` server in your Environment, default is 'false' - `['apt']['compiletime']` - force the `cacher-client` recipe to run before other recipes. It forces apt to use the proxy before other recipes run. Useful if your nodes have limited access to public apt repositories. This is overridden if the `cacher-ng` recipe is in your run list. Default is 'false' -- `['apt']['cache_bypass']` - array of URLs to bypass the cache. Accepts the URL and protocol to fetch directly from the remote repository and not attempt to cache ### Unattended Upgrades + - `['apt']['unattended_upgrades']['enable']` - enables unattended upgrades, default is false - `['apt']['unattended_upgrades']['update_package_lists']` - automatically update package list (`apt-get update`) daily, default is true - `['apt']['unattended_upgrades']['allowed_origins']` - array of allowed apt origins from which to pull automatic upgrades, defaults to a guess at the system's main origin and should almost always be overridden @@ -91,166 +129,72 @@ To pull just security updates, set `origins_patterns` to something like `["origi - `['apt']['unattended_upgrades']['minimal_steps']` - Split the upgrade into the smallest possible chunks. This makes the upgrade a bit slower but it has the benefit that shutdown while a upgrade is running is possible (with a small delay). Defaults to false. - `['apt']['unattended_upgrades']['install_on_shutdown']` - Install upgrades when the machine is shuting down instead of doing it in the background while the machine is running. This will (obviously) make shutdown slower. Defaults to false. - `['apt']['unattended_upgrades']['mail']` - Send email to this address for problems or packages upgrades. Defaults to no email. +- `['apt']['unattended_upgrades']['sender']` - Send email from this address for problems or packages upgrades. Defaults to 'root'. - `['apt']['unattended_upgrades']['mail_only_on_error']` - If set, email will only be set on upgrade errors. Otherwise, an email will be sent after each upgrade. Defaults to true. - `['apt']['unattended_upgrades']['remove_unused_dependencies']` Do automatic removal of new unused dependencies after the upgrade. Defaults to false. - `['apt']['unattended_upgrades']['automatic_reboot']` - Automatically reboots _without confirmation_ if a restart is required after the upgrade. Defaults to false. - `['apt']['unattended_upgrades']['dl_limit']` - Limits the bandwidth used by apt to download packages. Value given as an integer in kb/sec. Defaults to nil (no limit). -- `['apt']['unattended_upgrades']['random_sleep]'` - Wait a random number of seconds up to this value before running daily periodic apt actions. System default is 1800 seconds (30 minutes). +- `['apt']['unattended_upgrades']['random_sleep']` - Wait a random number of seconds up to this value before running daily periodic apt actions. System default is 1800 seconds (30 minutes). +- `['apt']['unattended_upgrades']['syslog_enable']` - Enable logging to syslog. Defaults to false. +- `['apt']['unattended_upgrades']['syslog_facility']` - Specify syslog facility. Defaults to 'daemon'. ### Configuration for APT + +- `['apt']['confd']['force_confask']` - Prompt when overwriting configuration files. (default: false) +- `['apt']['confd']['force_confdef']` - Don't prompt when overwriting configuration files. (default: false) +- `['apt']['confd']['force_confmiss']` - Install removed configuration files when upgrading packages. (default: false) +- `['apt']['confd']['force_confnew']` - Overwrite configuration files when installing packages. (default: false) +- `['apt']['confd']['force_confold']` - Keep modified configuration files when installing packages. (default: false) - `['apt']['confd']['install_recommends']` - Consider recommended packages as a dependency for installing. (default: true) - `['apt']['confd']['install_suggests']` - Consider suggested packages as a dependency for installing. (default: false) ## Libraries -There is an `interface_ipaddress` method that returns the IP address for a particular host and interface, used by the `cacher-client` recipe. To enable it on the server use the `['apt']['cacher_interface']` attribute. - -## Resources/Providers -### `apt_repository` -This LWRP provides an easy way to manage additional APT repositories. Adding a new repository will notify running the `execute[apt-get-update]` resource immediately. - -#### Actions -- :add: creates a repository file and builds the repository listing (default) -- :remove: removes the repository file - -#### Attribute Parameters -- repo_name: name attribute. The name of the channel to discover -- uri: the base of the Debian distribution -- distribution: this is usually your release's codename...ie something like `karmic`, `lucid` or `maverick` -- components: package groupings... when in doubt use `main` -- arch: constrain package to a particular arch like `i386`, `amd64` or even `armhf` or `powerpc`. Defaults to nil. -- trusted: treat all packages from this repository as authenticated regardless of signature -- deb_src: whether or not to add the repository as a source repo as well - value can be `true` or `false`, default `false`. -- keyserver: the GPG keyserver where the key for the repo should be retrieved -- key: if a `keyserver` is provided, this is assumed to be the fingerprint, otherwise it can be either the URI to the GPG key for the repo, or a cookbook_file. -- key_proxy: if set, pass the specified proxy via `http-proxy=` to GPG. -- cookbook: if key should be a cookbook_file, specify a cookbook where the key is located for files/default. Defaults to nil, so it will use the cookbook where the resource is used. - -#### Examples -Add the Zenoss repo: -```ruby -apt_repository 'zenoss' do - uri 'http://dev.zenoss.org/deb' - components ['main', 'stable'] -end -``` - -Enable Ubuntu [multiverse](https://help.ubuntu.com/community/Repositories/Ubuntu) repositories: - -```ruby -apt_repository 'security-ubuntu-multiverse' do - uri 'http://security.ubuntu.com/ubuntu' - distribution 'trusty-security' - components ['multiverse'] - deb_src true -end -``` - -Add the Nginx PPA, autodetect the key and repository url: - -```ruby -apt_repository 'nginx-php' do - uri 'ppa:nginx/stable' - distribution node['lsb']['codename'] -end -``` - -Add the JuJu PPA, grab the key from the keyserver, and add source repo: +There is an `interface_ipaddress` method that returns the IP address for a particular host and interface, used by the `cacher-client` recipe. To enable it on the server use the `['apt']['cacher_interface']` attribute. -```ruby -apt_repository 'juju' do - uri 'http://ppa.launchpad.net/juju/stable/ubuntu' - components ['main'] - distribution 'trusty' - key 'C8068B11' - keyserver 'keyserver.ubuntu.com' - action :add - deb_src true -end -``` +## Usage -Add the Cloudera Repo of CDH4 packages for Ubuntu 12.04 on AMD64: +Put `recipe[apt]` first in the run list. If you have other recipes that you want to use to configure how apt behaves, like new sources, notify the execute resource to run, e.g.: ```ruby -apt_repository 'cloudera' do - uri 'http://archive.cloudera.com/cdh4/ubuntu/precise/amd64/cdh' - arch 'amd64' - distribution 'precise-cdh4' - components ['contrib'] - key 'http://archive.cloudera.com/debian/archive.key' +template '/etc/apt/sources.list.d/my_apt_sources.list' do + notifies :run, 'execute[apt-get update]', :immediately end ``` -Remove Zenoss repo: +The above will run during execution phase since it is a normal template resource, and should appear before other package resources that need the sources in the template. -```ruby -apt_repository 'zenoss' do - action :remove -end -``` +Put `recipe[apt::cacher-ng]` in the run_list for a server to provide APT caching and add `recipe[apt::cacher-client]` on the rest of the Debian-based nodes to take advantage of the caching server. -### `apt_preference` -This LWRP provides an easy way to pin packages in /etc/apt/preferences.d. Although apt-pinning is quite helpful from time to time please note that Debian does not encourage its use without thorough consideration. +If you want to cleanup unused packages, there is also the `apt-get autoclean` and `apt-get autoremove` resources provided for automated cleanup. -Further information regarding apt-pinning is available via [http://wiki.debian.org/AptPreferences](http://wiki.debian.org/AptPreferences). +## Resources -#### Actions -- :add: creates a preferences file under /etc/apt/preferences.d -- :remove: Removes the file, therefore unpin the package +### apt_preference -#### Attribute Parameters -- package_name: name attribute. The name of the package -- glob: Pin by glob() expression or regexp surrounded by /. -- pin: The package version/repository to pin -- pin_priority: The pinning priority aka "the highest package version wins" +The apt_preference resource has been moved into chef-client in Chef 13.3. -#### Examples -Pin libmysqlclient16 to version 5.1.49-3: +See for usage details -```ruby -apt_preference 'libmysqlclient16' do - pin 'version 5.1.49-3' - pin_priority '700' -end -``` +### apt_repository -Unpin libmysqlclient16: +The apt_repository resource has been moved into chef-client in Chef 12.9. -```ruby -apt_preference 'libmysqlclient16' do - action :remove -end -``` +See for usage details -Pin all packages from dotdeb.org: - -```ruby -apt_preference 'dotdeb' do - glob '*' - pin 'origin packages.dotdeb.org' - pin_priority '700' -end -``` - -## Usage -Put `recipe[apt]` first in the run list. If you have other recipes that you want to use to configure how apt behaves, like new sources, notify the execute resource to run, e.g.: +### apt_update -```ruby -template '/etc/apt/sources.list.d/my_apt_sources.list' do - notifies :run, 'execute[apt-get update]', :immediately -end -``` +The apt_update resource has been moved into chef-client in Chef 12.7. -The above will run during execution phase since it is a normal template resource, and should appear before other package resources that need the sources in the template. +See for usage details -Put `recipe[apt::cacher-ng]` in the run_list for a server to provide APT caching and add `recipe[apt::cacher-client]` on the rest of the Debian-based nodes to take advantage of the caching server. +## Maintainers -If you want to cleanup unused packages, there is also the `apt-get autoclean` and `apt-get autoremove` resources provided for automated cleanup. +This cookbook is maintained by Chef's Community Cookbook Engineering team. Our goal is to improve cookbook quality and to aid the community in contributing to cookbooks. To learn more about our team, process, and design goals see our [team documentation](https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/COOKBOOK_TEAM.MD). To learn more about contributing to cookbooks like this see our [contributing documentation](https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/CONTRIBUTING.MD), or if you have general questions about this cookbook come chat with us in #cookbok-engineering on the [Chef Community Slack](http://community-slack.chef.io/) -## License & Authors -**Author:** Cookbook Engineering Team ([cookbooks@chef.io](mailto:cookbooks@chef.io)) +## License -**Copyright:** 2009-2015, Chef Software, Inc. +**Copyright:** 2009-2017, Chef Software, Inc. ``` Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/cookbooks/apt/Rakefile b/cookbooks/apt/Rakefile deleted file mode 100644 index ccd07dd8..00000000 --- a/cookbooks/apt/Rakefile +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env rake - -# Style tests. cookstyle (rubocop) and Foodcritic -namespace :style do - begin - require 'cookstyle' - require 'rubocop/rake_task' - - desc 'Run Ruby style checks' - RuboCop::RakeTask.new(:ruby) - rescue LoadError => e - puts ">>> Gem load error: #{e}, omitting style:ruby" unless ENV['CI'] - end - - begin - require 'foodcritic' - - desc 'Run Chef style checks' - FoodCritic::Rake::LintTask.new(:chef) do |t| - t.options = { - fail_tags: ['any'], - progress: true - } - end - rescue LoadError - puts ">>> Gem load error: #{e}, omitting style:chef" unless ENV['CI'] - end -end - -desc 'Run all style checks' -task style: ['style:chef', 'style:ruby'] - -# ChefSpec -begin - require 'rspec/core/rake_task' - - desc 'Run ChefSpec examples' - RSpec::Core::RakeTask.new(:spec) -rescue LoadError => e - puts ">>> Gem load error: #{e}, omitting spec" unless ENV['CI'] -end - -# Integration tests. Kitchen.ci -namespace :integration do - begin - require 'kitchen/rake_tasks' - - desc 'Run kitchen integration tests' - Kitchen::RakeTasks.new - rescue LoadError => e - puts ">>> Gem load error: #{e}, omitting #{task.name}" unless ENV['CI'] - rescue Kitchen::UserError => e - puts ">>> Test Kitchen error: #{e}" unless ENV['CI'] - end -end - -namespace :supermarket do - begin - require 'stove/rake_task' - - desc 'Publish cookbook to Supermarket with Stove' - Stove::RakeTask.new - rescue LoadError => e - puts ">>> Gem load error: #{e}, omitting #{task.name}" unless ENV['CI'] - end -end - -# Default -task default: %w(style spec) diff --git a/cookbooks/apt/attributes/default.rb b/cookbooks/apt/attributes/default.rb index 37680caa..6e77384e 100644 --- a/cookbooks/apt/attributes/default.rb +++ b/cookbooks/apt/attributes/default.rb @@ -1,8 +1,8 @@ # -# Cookbook Name:: apt +# Cookbook:: apt # Attributes:: default # -# Copyright 2009-2016, Chef Software, Inc. +# Copyright:: 2009-2017, 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. @@ -17,16 +17,12 @@ # limitations under the License. # -default['apt']['cacher-client']['restrict_environment'] = false default['apt']['cacher_dir'] = '/var/cache/apt-cacher-ng' default['apt']['cacher_interface'] = nil default['apt']['cacher_port'] = 3142 -default['apt']['cacher_ssl_support'] = false -default['apt']['caching_server'] = false default['apt']['compiletime'] = false default['apt']['compile_time_update'] = false default['apt']['key_proxy'] = '' -default['apt']['cache_bypass'] = {} default['apt']['periodic_update_min_delay'] = 86_400 default['apt']['launchpad_api_version'] = '1.0' default['apt']['unattended_upgrades']['enable'] = false @@ -34,20 +30,31 @@ # this needs a good default codename = node.attribute?('lsb') ? node['lsb']['codename'] : 'notlinux' default['apt']['unattended_upgrades']['allowed_origins'] = [ - "#{node['platform'].capitalize} #{codename}" + "#{node['platform'].capitalize} #{codename}", ] + +default['apt']['cacher_client']['cacher_server'] = {} + default['apt']['unattended_upgrades']['origins_patterns'] = [] default['apt']['unattended_upgrades']['package_blacklist'] = [] default['apt']['unattended_upgrades']['auto_fix_interrupted_dpkg'] = false default['apt']['unattended_upgrades']['minimal_steps'] = false default['apt']['unattended_upgrades']['install_on_shutdown'] = false default['apt']['unattended_upgrades']['mail'] = nil +default['apt']['unattended_upgrades']['sender'] = nil default['apt']['unattended_upgrades']['mail_only_on_error'] = true default['apt']['unattended_upgrades']['remove_unused_dependencies'] = false default['apt']['unattended_upgrades']['automatic_reboot'] = false default['apt']['unattended_upgrades']['automatic_reboot_time'] = 'now' default['apt']['unattended_upgrades']['dl_limit'] = nil default['apt']['unattended_upgrades']['random_sleep'] = nil +default['apt']['unattended_upgrades']['syslog_enable'] = false +default['apt']['unattended_upgrades']['syslog_facility'] = 'daemon' +default['apt']['confd']['force_confask'] = false +default['apt']['confd']['force_confdef'] = false +default['apt']['confd']['force_confmiss'] = false +default['apt']['confd']['force_confnew'] = false +default['apt']['confd']['force_confold'] = false default['apt']['confd']['install_recommends'] = true default['apt']['confd']['install_suggests'] = false diff --git a/cookbooks/apt/chefignore b/cookbooks/apt/chefignore index a9769175..7e4ab407 100644 --- a/cookbooks/apt/chefignore +++ b/cookbooks/apt/chefignore @@ -45,22 +45,19 @@ a.out # Testing # ########### -.watchr .rspec spec/* spec/fixtures/* test/* features/* examples/* -Guardfile Procfile .kitchen* .rubocop.yml spec/* -Rakefile .travis.yml .foodcritic -.codeclimate.yml +appveyor.yml # SCM # ####### @@ -82,21 +79,14 @@ Berksfile.lock cookbooks/* tmp +# Policyfile # +############## +Policyfile.rb +Policyfile.lock.json + # Cookbooks # ############# CONTRIBUTING* CHANGELOG* TESTING* -MAINTAINERS.toml -# Strainer # -############ -Colanderfile -Strainerfile -.colander -.strainer - -# Vagrant # -########### -.vagrant -Vagrantfile diff --git a/cookbooks/apt/files/default/15update-stamp b/cookbooks/apt/files/15update-stamp similarity index 100% rename from cookbooks/apt/files/default/15update-stamp rename to cookbooks/apt/files/15update-stamp diff --git a/cookbooks/apt/files/default/apt-proxy-v2.conf b/cookbooks/apt/files/apt-proxy-v2.conf similarity index 100% rename from cookbooks/apt/files/default/apt-proxy-v2.conf rename to cookbooks/apt/files/apt-proxy-v2.conf diff --git a/cookbooks/apt/kitchen.dokken.yml b/cookbooks/apt/kitchen.dokken.yml new file mode 100644 index 00000000..2cb5c426 --- /dev/null +++ b/cookbooks/apt/kitchen.dokken.yml @@ -0,0 +1,51 @@ +driver: + name: dokken + privileged: true # because Docker and SystemD/Upstart + chef_version: <%= ENV['CHEF_VERSION'] || 'current' %> + +transport: + name: dokken + +provisioner: + name: dokken + deprecations_as_errors: true + +verifier: + name: inspec + +platforms: +- name: debian-8 + driver: + image: dokken/debian-8 + pid_one_command: /bin/systemd + +- name: debian-9 + driver: + # Need a custom Stretch image as dokken one contains extra packages and then we hit https://github.com/chef-cookbooks/apt/issues/234 + image: debian:9 + pid_one_command: /bin/systemd + intermediate_instructions: + - RUN /usr/bin/apt-get update + - RUN /usr/bin/apt-get install -y systemd + - RUN rm /etc/systemd/system/getty.target.wants/getty\@tty1.service + +- name: centos-7 + driver: + image: dokken/centos-7 + pid_one_command: /usr/lib/systemd/systemd + + +- name: ubuntu-14.04 + driver: + image: dokken/ubuntu-14.04 + pid_one_command: /sbin/init + +- name: ubuntu-16.04 + driver: + image: dokken/ubuntu-16.04 + pid_one_command: /bin/systemd + +- name: ubuntu-18.04 + driver: + image: dokken/ubuntu-18.04 + pid_one_command: /bin/systemd diff --git a/cookbooks/apt/kitchen.yml b/cookbooks/apt/kitchen.yml new file mode 100644 index 00000000..6661b875 --- /dev/null +++ b/cookbooks/apt/kitchen.yml @@ -0,0 +1,54 @@ +driver: + name: vagrant + +provisioner: + name: chef_zero + deprecations_as_errors: true + +verifier: + name: inspec + +platforms: + - name: centos-7 + - name: debian-8 + - name: debian-9 + - name: ubuntu-14.04 + - name: ubuntu-16.04 + - name: ubuntu-18.04 + - name: ubuntu-16.04-chef-12.9 + driver_config: + box: bento/ubuntu-16.04 + provisioner: + require_chef_omnibus: 12.9.41 + +suites: + - name: default + run_list: + - recipe[apt] + + - name: cacher + run_list: + - recipe[test::cacher] + excludes: centos-7 + + - name: compile-time + run_list: + - recipe[apt::default] + attributes: + apt: + compile_time_update: true + excludes: centos-7 + + - name: resources + run_list: + - recipe[test::resources] + excludes: centos-7 + + - name: unattended-upgrades + run_list: + - recipe[test::unattended-upgrades] + attributes: + apt: + unattended_upgrades: + enable: true + excludes: centos-7 diff --git a/cookbooks/apt/libraries/apt_update.rb b/cookbooks/apt/libraries/apt_update.rb deleted file mode 100644 index 4ec4f947..00000000 --- a/cookbooks/apt/libraries/apt_update.rb +++ /dev/null @@ -1,56 +0,0 @@ -unless defined? Chef::Resource::AptUpdate - require 'chef_compat/copied_from_chef/chef/dsl/declare_resource' - require 'chef/mixin/shell_out' - - class AptUpdate < ChefCompat::Resource - include ChefCompat::CopiedFromChef::Chef::DSL::DeclareResource - include Chef::Mixin::ShellOut - - resource_name :apt_update - - provides :apt_update, os: 'linux' - property :frequency, Integer, default: 86_400 - - default_action :periodic - allowed_actions :update, :periodic - - APT_CONF_DIR = '/etc/apt/apt.conf.d'.freeze - STAMP_DIR = '/var/lib/apt/periodic'.freeze - - action :periodic do - unless apt_up_to_date? # ~FC023 - 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 - - # 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| - build_resource(:directory, d, caller[0]) do - recursive true - end.run_action(:create) - end - - build_resource(:file, "#{APT_CONF_DIR}/15update-stamp", caller[0]) do - content "APT::Update::Post-Invoke-Success {\"touch #{STAMP_DIR}/update-success-stamp 2>/dev/null || true\";};" - end.run_action(:create_if_missing) - - shell_out!('apt-get -q update') - end - end -end diff --git a/cookbooks/apt/libraries/helpers.rb b/cookbooks/apt/libraries/helpers.rb index d576cdec..6d98060c 100644 --- a/cookbooks/apt/libraries/helpers.rb +++ b/cookbooks/apt/libraries/helpers.rb @@ -1,8 +1,8 @@ # -# Cookbook Name:: apt +# Cookbook:: apt # Library:: helpers # -# Copyright 2013-2016 Chef Software, Inc. +# Copyright:: 2013-2017, 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. @@ -27,18 +27,6 @@ def apt_installed? !which('apt-get').nil? end - # Determines whether we need to run `apt-get update` - # - # @return [Boolean] - def apt_up_to_date? - if ::File.exist?('/var/lib/apt/periodic/update-success-stamp') && - ::File.mtime('/var/lib/apt/periodic/update-success-stamp') > Time.now - node['apt']['periodic_update_min_delay'] - true - else - false - end - end - # Finds a command in $PATH # # @return [String, nil] diff --git a/cookbooks/apt/libraries/matchers.rb b/cookbooks/apt/libraries/matchers.rb deleted file mode 100644 index b57d2c68..00000000 --- a/cookbooks/apt/libraries/matchers.rb +++ /dev/null @@ -1,38 +0,0 @@ -if defined?(ChefSpec) - - ################# - # apt_preference - ################# - - def add_apt_preference(resource_name) - ChefSpec::Matchers::ResourceMatcher.new(:apt_preference, :add, resource_name) - end - - def remove_apt_preference(resource_name) - ChefSpec::Matchers::ResourceMatcher.new(:apt_preference, :remove, resource_name) - end - - ################# - # apt_repository - ################# - - def add_apt_repository(resource_name) - ChefSpec::Matchers::ResourceMatcher.new(:apt_repository, :add, resource_name) - end - - def remove_apt_repository(resource_name) - ChefSpec::Matchers::ResourceMatcher.new(:apt_repository, :remove, resource_name) - end - - ################# - # apt_update - ################# - - def update_apt_update(resource_name) - ChefSpec::Matchers::ResourceMatcher.new(:apt_update, :update, resource_name) - end - - def periodic_apt_update(resource_name) - ChefSpec::Matchers::ResourceMatcher.new(:apt_update, :periodic, resource_name) - end -end diff --git a/cookbooks/apt/libraries/network.rb b/cookbooks/apt/libraries/network.rb deleted file mode 100644 index 307c5f45..00000000 --- a/cookbooks/apt/libraries/network.rb +++ /dev/null @@ -1,31 +0,0 @@ -# -# Cookbook Name:: apt -# library:: network -# -# Copyright 2013-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. -# - -module ::Apt - def interface_ipaddress(host, interface) - if interface # rubocop: disable Style/GuardClause - addresses = host['network']['interfaces'][interface]['addresses'] - addresses.select do |ip, data| - return ip if data['family'].eql?('inet') - end - else - return host.ipaddress - end - end -end diff --git a/cookbooks/apt/metadata.rb b/cookbooks/apt/metadata.rb index 00a9fe85..f0458449 100644 --- a/cookbooks/apt/metadata.rb +++ b/cookbooks/apt/metadata.rb @@ -1,10 +1,10 @@ name 'apt' maintainer 'Chef Software, Inc.' maintainer_email 'cookbooks@chef.io' -license 'Apache 2.0' -description 'Configures apt and apt services. Ships resources for managing apt repositories' +license 'Apache-2.0' +description 'Configures apt and apt caching.' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) -version '4.0.2' +version '7.1.1' recipe 'apt::default', 'Runs apt-get update during compile phase and sets up preseed directories' recipe 'apt::cacher-ng', 'Set up an apt-cacher-ng caching proxy' @@ -16,7 +16,4 @@ source_url 'https://github.com/chef-cookbooks/apt' issues_url 'https://github.com/chef-cookbooks/apt/issues' - -chef_version '>= 12.1' if respond_to?(:chef_version)\ - -depends 'compat_resource', '>= 12.10' +chef_version '>= 13.3' if respond_to?(:chef_version) diff --git a/cookbooks/apt/providers/preference.rb b/cookbooks/apt/providers/preference.rb deleted file mode 100644 index 0cef52f4..00000000 --- a/cookbooks/apt/providers/preference.rb +++ /dev/null @@ -1,84 +0,0 @@ -# -# Cookbook Name:: apt -# Provider:: preference -# -# Copyright 2010-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. -# - -use_inline_resources - -def whyrun_supported? - true -end - -# Build preferences.d file contents -def build_pref(package_name, pin, pin_priority) - "Package: #{package_name}\nPin: #{pin}\nPin-Priority: #{pin_priority}\n" -end - -def safe_name(name) - name.tr('.', '_').gsub('*', 'wildcard') -end - -action :add do - preference = build_pref( - new_resource.glob || new_resource.package_name, - new_resource.pin, - new_resource.pin_priority - ) - - directory '/etc/apt/preferences.d' do - owner 'root' - group 'root' - mode '0755' - recursive true - action :create - end - - name = safe_name(new_resource.name) - - file "/etc/apt/preferences.d/#{new_resource.name}.pref" do - action :delete - if ::File.exist?("/etc/apt/preferences.d/#{new_resource.name}.pref") - Chef::Log.warn "Replacing #{new_resource.name}.pref with #{name}.pref in /etc/apt/preferences.d/" - end - only_if { name != new_resource.name } - end - - file "/etc/apt/preferences.d/#{new_resource.name}" do - action :delete - if ::File.exist?("/etc/apt/preferences.d/#{new_resource.name}") - Chef::Log.warn "Replacing #{new_resource.name} with #{new_resource.name}.pref in /etc/apt/preferences.d/" - end - end - - file "/etc/apt/preferences.d/#{name}.pref" do - owner 'root' - group 'root' - mode '0644' - content preference - action :create - end -end - -action :remove do - name = safe_name(new_resource.name) - if ::File.exist?("/etc/apt/preferences.d/#{name}.pref") - Chef::Log.info "Un-pinning #{name} from /etc/apt/preferences.d/" - file "/etc/apt/preferences.d/#{name}.pref" do - action :delete - end - end -end diff --git a/cookbooks/apt/providers/repository.rb b/cookbooks/apt/providers/repository.rb deleted file mode 100644 index 1a4e7648..00000000 --- a/cookbooks/apt/providers/repository.rb +++ /dev/null @@ -1,246 +0,0 @@ -# -# Cookbook Name:: apt -# Provider:: repository -# -# Copyright 2010-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. -# - -use_inline_resources - -def whyrun_supported? - true -end - -# install apt key from keyserver -def install_key_from_keyserver(key, keyserver, key_proxy) - execute "install-key #{key}" do - if keyserver.start_with?('hkp://') - command "apt-key adv --keyserver #{keyserver} --recv #{key}" - elsif key_proxy.empty? - command "apt-key adv --keyserver hkp://#{keyserver}:80 --recv #{key}" - else - command "apt-key adv --keyserver-options http-proxy=#{key_proxy} --keyserver hkp://#{keyserver}:80 --recv #{key}" - end - sensitive new_resource.sensitive if respond_to?(:sensitive) - action :run - not_if do - key_present = extract_fingerprints_from_cmd('apt-key finger').any? do |fingerprint| - fingerprint.end_with?(key.upcase) - end - - key_present && key_is_valid('apt-key list', key.upcase) - end - end - - ruby_block "validate-key #{key}" do - block do - raise "The key #{key} is no longer valid and cannot be used for an apt repository." - end - not_if { key_is_valid('apt-key list', key.upcase) } - end -end - -# run command and extract gpg ids -def extract_fingerprints_from_cmd(cmd) - so = Mixlib::ShellOut.new(cmd, env: { 'LANG' => 'en_US', 'LANGUAGE' => 'en_US' }) - so.run_command - so.stdout.split(/\n/).map do |t| - if z = t.match(/^ +Key fingerprint = ([0-9A-F ]+)/) # rubocop: disable Lint/AssignmentInCondition - z[1].split.join - end - end.compact -end - -# determine whether apt thinks the key is still valid -def key_is_valid(cmd, key) - valid = true - - so = Mixlib::ShellOut.new(cmd, env: { 'LANG' => 'en_US', 'LANGUAGE' => 'en_US' }) - so.run_command - # rubocop:disable Style/Next - 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} validity: #{valid}" - valid -end - -# install apt key from URI -def install_key_from_uri(uri) - key_name = uri.split(%r{\/}).last - cached_keyfile = "#{Chef::Config[:file_cache_path]}/#{key_name}" - if new_resource.key =~ /http/ - remote_file cached_keyfile do - source new_resource.key - mode '0644' - sensitive new_resource.sensitive if respond_to?(:sensitive) - action :create - end - else - cookbook_file cached_keyfile do - source new_resource.key - cookbook new_resource.cookbook - mode '0644' - sensitive new_resource.sensitive if respond_to?(:sensitive) - action :create - end - - ruby_block "validate-key #{cached_keyfile}" do - block do - raise "The key #{cached_keyfile} is no longer valid and cannot be used for an apt repository." unless key_is_valid("gpg #{cached_keyfile}", '') - end - end - end - - execute "install-key #{key_name}" do - command "apt-key add #{cached_keyfile}" - sensitive new_resource.sensitive if respond_to?(:sensitive) - action :run - not_if do - installed_keys = extract_fingerprints_from_cmd('apt-key finger') - proposed_keys = extract_fingerprints_from_cmd("gpg --with-fingerprint #{cached_keyfile}") - (installed_keys & proposed_keys).sort == proposed_keys.sort - end - end -end - -# build repo file contents -def build_repo(uri, distribution, components, trusted, arch, add_deb_src) # rubocop: disable Metrics/ParameterLists - uri = '"' + uri + '"' unless uri.start_with?('"', "'") - components = components.join(' ') if components.respond_to?(:join) - repo_options = [] - repo_options << "arch=#{arch}" if arch - repo_options << 'trusted=yes' if trusted - repo_opts = '[' + repo_options.join(' ') + ']' unless repo_options.empty? - repo_info = "#{repo_opts} #{uri} #{distribution} #{components}\n".lstrip - repo = "deb #{repo_info}" - repo << "deb-src #{repo_info}" if add_deb_src - repo -end - -def get_ppa_key(ppa_owner, ppa_repo, key_proxy) - # Launchpad has currently only one stable API which is marked as EOL April 2015. - # The new api in devel still uses the same api call for +archive, so I made the version - # configurable to provide some sort of workaround if api 1.0 ceases to exist. - # See https://launchpad.net/+apidoc/ - launchpad_ppa_api = "https://launchpad.net/api/#{node['apt']['launchpad_api_version']}/~%s/+archive/%s" - default_keyserver = 'keyserver.ubuntu.com' - - require 'open-uri' - api_query = format("#{launchpad_ppa_api}/signing_key_fingerprint", ppa_owner, ppa_repo) - begin - key_id = open(api_query).read.delete('"') - rescue OpenURI::HTTPError => e - error = 'Could not access launchpad ppa key api: HttpError: ' + e.message - raise error - rescue SocketError => e - error = 'Could not access launchpad ppa key api: SocketError: ' + e.message - raise error - end - - install_key_from_keyserver(key_id, default_keyserver, key_proxy) -end - -# fetch ppa key, return full repo url -def get_ppa_url(ppa, key_proxy) - repo_schema = 'http://ppa.launchpad.net/%s/%s/ubuntu' - - # ppa:user/repo logic ported from - # http://bazaar.launchpad.net/~ubuntu-core-dev/software-properties/main/view/head:/softwareproperties/ppa.py#L86 - return false unless ppa.start_with?('ppa:') - - ppa_name = ppa.split(':')[1] - ppa_owner = ppa_name.split('/')[0] - ppa_repo = ppa_name.split('/')[1] - ppa_repo = 'ppa' if ppa_repo.nil? - - get_ppa_key(ppa_owner, ppa_repo, key_proxy) - - format(repo_schema, ppa_owner, ppa_repo) -end - -action :add do - # add key - if new_resource.keyserver && new_resource.key - install_key_from_keyserver(new_resource.key, new_resource.keyserver, new_resource.key_proxy) - elsif new_resource.key - install_key_from_uri(new_resource.key) - end - - file '/var/lib/apt/periodic/update-success-stamp' do - action :nothing - end - - execute 'apt-cache gencaches' do - ignore_failure true - action :nothing - end - - execute 'apt-get update' do - command "apt-get update -o Dir::Etc::sourcelist='sources.list.d/#{new_resource.name}.list' -o Dir::Etc::sourceparts='-' -o APT::Get::List-Cleanup='0'" - ignore_failure true - sensitive new_resource.sensitive if respond_to?(:sensitive) - action :nothing - notifies :run, 'execute[apt-cache gencaches]', :immediately - end - - repository = if new_resource.uri.start_with?('ppa:') - # build ppa repo file - build_repo( - get_ppa_url(new_resource.uri, new_resource.key_proxy), - new_resource.distribution, - 'main', - new_resource.trusted, - new_resource.arch, - new_resource.deb_src - ) - else - # build repo file - build_repo( - new_resource.uri, - new_resource.distribution, - new_resource.components, - new_resource.trusted, - new_resource.arch, - new_resource.deb_src - ) - end - - file "/etc/apt/sources.list.d/#{new_resource.name}.list" do - owner 'root' - group 'root' - mode '0644' - content repository - sensitive new_resource.sensitive if respond_to?(:sensitive) - action :create - notifies :delete, 'file[/var/lib/apt/periodic/update-success-stamp]', :immediately - notifies :run, 'execute[apt-get update]', :immediately if new_resource.cache_rebuild - end -end - -action :remove do - if ::File.exist?("/etc/apt/sources.list.d/#{new_resource.name}.list") - Chef::Log.info "Removing #{new_resource.name} repository from /etc/apt/sources.list.d/" - file "/etc/apt/sources.list.d/#{new_resource.name}.list" do - sensitive new_resource.sensitive if respond_to?(:sensitive) - action :delete - end - end -end diff --git a/cookbooks/apt/recipes/cacher-client.rb b/cookbooks/apt/recipes/cacher-client.rb index 10eeeb04..1bbf92c1 100644 --- a/cookbooks/apt/recipes/cacher-client.rb +++ b/cookbooks/apt/recipes/cacher-client.rb @@ -1,8 +1,8 @@ # -# Cookbook Name:: apt +# Cookbook:: apt # Recipe:: cacher-client # -# Copyright 2011-2016 Chef Software, Inc. +# Copyright:: 2011-2017, 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. @@ -17,10 +17,6 @@ # limitations under the License. # -class ::Chef::Recipe - include ::Apt -end - # remove Acquire::http::Proxy lines from /etc/apt/apt.conf since we use 01proxy # these are leftover from preseed installs execute 'Remove proxy from /etc/apt/apt.conf' do @@ -28,56 +24,29 @@ class ::Chef::Recipe only_if 'grep Acquire::http::Proxy /etc/apt/apt.conf' end -servers = [] -if node['apt'] - if node['apt']['cacher_ipaddress'] - cacher = Chef::Node.new - cacher.default.name = node['apt']['cacher_ipaddress'] - cacher.default.ipaddress = node['apt']['cacher_ipaddress'] - cacher.default.apt.cacher_port = node['apt']['cacher_port'] - cacher.default.apt.cacher_interface = node['apt']['cacher_interface'] - cacher.default.apt.cacher_ssl_support = node['apt']['cacher_ssl_support'] - servers << cacher - elsif node['apt']['caching_server'] - node.override['apt']['compiletime'] = false - servers << node +if node['apt']['cacher_client']['cacher_server'].empty? + Chef::Log.warn("No cache server defined in node['apt']['cacher_client']['cacher_server']. Not setting up caching") + f = file '/etc/apt/apt.conf.d/01proxy' do + action(node['apt']['compiletime'] ? :nothing : :delete) + end + f.run_action(:delete) if node['apt']['compiletime'] +else + apt_update 'update for notification' do + action :nothing end -end - -unless Chef::Config[:solo] || !servers.empty? - query = 'apt_caching_server:true' - query += " AND chef_environment:#{node.chef_environment}" if node['apt']['cacher-client']['restrict_environment'] - Chef::Log.debug("apt::cacher-client searching for '#{query}'") - servers += search(:node, query) -end -if !servers.empty? - Chef::Log.info("apt-cacher-ng server found on #{servers[0]}.") - cacher_ipaddress = if servers[0]['apt']['cacher_interface'] - interface_ipaddress(servers[0], servers[0]['apt']['cacher_interface']) - else - servers[0].ipaddress - end t = template '/etc/apt/apt.conf.d/01proxy' do source '01proxy.erb' owner 'root' group 'root' mode '0644' variables( - proxy: cacher_ipaddress, - port: servers[0]['apt']['cacher_port'], - proxy_ssl: servers[0]['apt']['cacher_ssl_support'], - bypass: node['apt']['cache_bypass'] + server: node['apt']['cacher_client']['cacher_server'] ) action(node['apt']['compiletime'] ? :nothing : :create) - notifies :run, 'execute[apt-get update]', :immediately + notifies :update, 'apt_update[update for notification]', :immediately end t.run_action(:create) if node['apt']['compiletime'] -else - Chef::Log.info('No apt-cacher-ng server found.') - file '/etc/apt/apt.conf.d/01proxy' do - action :delete - end end include_recipe 'apt::default' diff --git a/cookbooks/apt/recipes/cacher-ng.rb b/cookbooks/apt/recipes/cacher-ng.rb index 25770117..5d7e8462 100644 --- a/cookbooks/apt/recipes/cacher-ng.rb +++ b/cookbooks/apt/recipes/cacher-ng.rb @@ -1,8 +1,8 @@ # -# Cookbook Name:: apt +# Cookbook:: apt # Recipe:: cacher-ng # -# Copyright 2008-2016, Chef Software, Inc. +# Copyright:: 2008-2017, 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. @@ -17,8 +17,6 @@ # limitations under the License. # -node.set['apt']['caching_server'] = true - package 'apt-cacher-ng' directory node['apt']['cacher_dir'] do diff --git a/cookbooks/apt/recipes/default.rb b/cookbooks/apt/recipes/default.rb index 1280dfd3..e8c9e8cd 100644 --- a/cookbooks/apt/recipes/default.rb +++ b/cookbooks/apt/recipes/default.rb @@ -1,9 +1,9 @@ # -# Cookbook Name:: apt +# Cookbook:: apt # Recipe:: default # -# Copyright 2008-2016, Chef Software, Inc. -# Copyright 2009, Bryan McLellan +# Copyright:: 2008-2017, Chef Software, Inc. +# Copyright:: 2009-2017, Bryan McLellan # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. @@ -31,11 +31,14 @@ # If compile_time_update run apt-get update at compile time if node['apt']['compile_time_update'] && apt_installed? - apt_update('compile time').run_action(:periodic) + apt_update('compile time') do + frequency node['apt']['periodic_update_min_delay'] + ignore_failure true + end.run_action(:periodic) end apt_update 'periodic' do - only_if { apt_installed? } + frequency node['apt']['periodic_update_min_delay'] end # For other recipes to call to force an update @@ -74,6 +77,14 @@ end end +template '/etc/apt/apt.conf.d/10dpkg-options' do + owner 'root' + group 'root' + mode '0644' + source '10dpkg-options.erb' + only_if { apt_installed? } +end + template '/etc/apt/apt.conf.d/10recommends' do owner 'root' group 'root' @@ -82,6 +93,6 @@ only_if { apt_installed? } end -package 'apt-transport-https' do +package %w(apt-transport-https gnupg dirmngr) do only_if { apt_installed? } end diff --git a/cookbooks/apt/recipes/unattended-upgrades.rb b/cookbooks/apt/recipes/unattended-upgrades.rb index 82c4cca2..ee2cb6e8 100644 --- a/cookbooks/apt/recipes/unattended-upgrades.rb +++ b/cookbooks/apt/recipes/unattended-upgrades.rb @@ -1,8 +1,8 @@ # -# Cookbook Name:: apt +# Cookbook:: apt # Recipe:: unattended-upgrades # -# Copyright 2014-2016, Chef Software, Inc. +# Copyright:: 2014-2017, 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. @@ -29,7 +29,7 @@ end package 'bsd-mailx' do - only_if { node['apt']['unattended_upgrades']['mail'] } + not_if { node['apt']['unattended_upgrades']['mail'].nil? } end template '/etc/apt/apt.conf.d/20auto-upgrades' do diff --git a/cookbooks/apt/resources/preference.rb b/cookbooks/apt/resources/preference.rb deleted file mode 100644 index 0c700c8c..00000000 --- a/cookbooks/apt/resources/preference.rb +++ /dev/null @@ -1,31 +0,0 @@ -# -# Cookbook Name:: apt -# Resource:: preference -# -# Copyright 2010-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. -# - -actions :add, :remove -default_action :add - -state_attrs :glob, - :package_name, - :pin, - :pin_priority - -attribute :package_name, kind_of: String, name_attribute: true, regex: [/^([a-z]|[A-Z]|[0-9]|_|-|\.|\*|\+)+$/] -attribute :glob, kind_of: String -attribute :pin, kind_of: String -attribute :pin_priority, kind_of: String diff --git a/cookbooks/apt/resources/repository.rb b/cookbooks/apt/resources/repository.rb deleted file mode 100644 index d0e49f52..00000000 --- a/cookbooks/apt/resources/repository.rb +++ /dev/null @@ -1,54 +0,0 @@ -# -# Cookbook Name:: apt -# Resource:: repository -# -# Copyright 2010-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. -# - -actions :add, :remove -default_action :add - -state_attrs :arch, - :cache_rebuild, - :components, - :cookbook, - :deb_src, - :distribution, - :key, - :keyserver, - :key_proxy, - :repo_name, - :trusted, - :uri, - :sensitive - -# name of the repo, used for source.list filename -attribute :repo_name, kind_of: String, name_attribute: true, regex: [/^([a-z]|[A-Z]|[0-9]|_|-|\.)+$/] -attribute :uri, kind_of: String -attribute :distribution, kind_of: String -attribute :components, kind_of: Array, default: [] -attribute :arch, kind_of: String, default: nil -attribute :trusted, kind_of: [TrueClass, FalseClass], default: false -# whether or not to add the repository as a source repo as well -attribute :deb_src, default: false -attribute :keyserver, kind_of: String, default: nil -attribute :key, kind_of: String, default: nil -attribute :key_proxy, kind_of: String, default: node['apt']['key_proxy'] -attribute :cookbook, kind_of: String, default: nil -# trigger cache rebuild -# If not you can trigger in the recipe itself after checking the status of resource.updated{_by_last_action}? -attribute :cache_rebuild, kind_of: [TrueClass, FalseClass], default: true -# Hide content of the source file, don't show output for commands being run, etc. -attribute :sensitive, kind_of: [TrueClass, FalseClass], default: false diff --git a/cookbooks/apt/spec/spec_helper.rb b/cookbooks/apt/spec/spec_helper.rb index 4e000048..773d5579 100644 --- a/cookbooks/apt/spec/spec_helper.rb +++ b/cookbooks/apt/spec/spec_helper.rb @@ -1,4 +1,8 @@ require 'chefspec' require 'chefspec/berkshelf' -at_exit { ChefSpec::Coverage.report! } +RSpec.configure do |config| + config.color = true # Use color in STDOUT + config.formatter = :documentation # Use the specified formatter + config.log_level = :error # Avoid deprecation notice SPAM +end diff --git a/cookbooks/apt/spec/unit/recipes/cacher-client_spec.rb b/cookbooks/apt/spec/unit/recipes/cacher-client_spec.rb index 37d23ce8..ed9e378f 100644 --- a/cookbooks/apt/spec/unit/recipes/cacher-client_spec.rb +++ b/cookbooks/apt/spec/unit/recipes/cacher-client_spec.rb @@ -2,24 +2,34 @@ describe 'apt::cacher-client' do context 'no server' do - let(:chef_run) { ChefSpec::ServerRunner.new.converge(described_recipe) } + let(:chef_run) { ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04').converge(described_recipe) } - # it 'does not create 01proxy file' do - # expect(chef_run).not_to create_file('/etc/apt/apt.conf.d/01proxy') - # end + before do + stub_command('grep Acquire::http::Proxy /etc/apt/apt.conf').and_return(false) + end + + it 'does not create 01proxy file' do + expect(chef_run).not_to create_file('/etc/apt/apt.conf.d/01proxy') + end end context 'server provided' do let(:chef_run) do - runner = ChefSpec::ServerRunner.new - runner.node.set['apt']['cacher_ipaddress'] = '22.33.44.55' - runner.node.set['apt']['cacher_port'] = '9876' + runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') + runner.node.normal['apt']['cacher_client']['cacher_server'] = { + host: 'localhost', + port: 9876, + proxy_ssl: true, + } runner.converge('apt::cacher-client') end - # it 'creates 01proxy file' do - # expect(chef_run).to render_file('/etc/apt/apt.conf.d/01proxy').with_content() - # expect(chef_run).to create_file_with_content('/etc/apt/apt.conf.d/01proxy', 'Acquire::http::Proxy "http://22.33.44.55:9876";') - # end + before do + stub_command('grep Acquire::http::Proxy /etc/apt/apt.conf').and_return(false) + end + + it 'creates 01proxy file' do + expect(chef_run).to render_file('/etc/apt/apt.conf.d/01proxy').with_content('Acquire::http::Proxy "http://localhost:9876";') + end end end diff --git a/cookbooks/apt/spec/unit/recipes/cacher-ng_spec.rb b/cookbooks/apt/spec/unit/recipes/cacher-ng_spec.rb index 2c5abd83..0935cb85 100644 --- a/cookbooks/apt/spec/unit/recipes/cacher-ng_spec.rb +++ b/cookbooks/apt/spec/unit/recipes/cacher-ng_spec.rb @@ -4,7 +4,7 @@ context 'server' do let(:chef_run) do runner = ChefSpec::ServerRunner.new - runner.node.set['apt']['cacher_port'] = '9876' + runner.node.normal['apt']['cacher_port'] = '9876' runner.converge('apt::cacher-ng') end diff --git a/cookbooks/apt/spec/unit/recipes/default_spec.rb b/cookbooks/apt/spec/unit/recipes/default_spec.rb index ee344080..6e8f0248 100644 --- a/cookbooks/apt/spec/unit/recipes/default_spec.rb +++ b/cookbooks/apt/spec/unit/recipes/default_spec.rb @@ -1,11 +1,8 @@ require 'spec_helper' describe 'apt::default' do - let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '14.04') do |node| - node.automatic[:lsb][:codename] = 'trusty' - end.converge('apt::default') - end + let(:runner) { ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') } + let(:chef_run) { runner.converge('apt::default') } before do allow(::File).to receive(:executable?).and_return(true) @@ -17,8 +14,8 @@ expect(chef_run).to render_file('/etc/apt/apt.conf.d/10recommends').with_content('APT::Install-Suggests "0";') end - it 'installs apt-transport-https' do - expect(chef_run).to install_package('apt-transport-https') + it 'installs apt-transport-https, gnupg and dirmngr' do + expect(chef_run).to install_package(['apt-transport-https', 'gnupg', 'dirmngr']) end it 'creates preseeding directory' do diff --git a/cookbooks/apt/tasks/maintainers.rb b/cookbooks/apt/tasks/maintainers.rb deleted file mode 100644 index 7e996333..00000000 --- a/cookbooks/apt/tasks/maintainers.rb +++ /dev/null @@ -1,76 +0,0 @@ -# -# Copyright:: Copyright (c) 2015 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 'rake' - -SOURCE = File.join(File.dirname(__FILE__), '..', 'MAINTAINERS.toml') -TARGET = File.join(File.dirname(__FILE__), '..', 'MAINTAINERS.md') - -begin - require 'tomlrb' - task default: 'maintainers:generate' - - namespace :maintainers do - desc 'Generate MarkDown version of MAINTAINERS file' - task :generate do - @toml = Tomlrb.load_file SOURCE - out = "\n\n" - - out << preamble - out << project_lieutenant - out << all_maintainers - - File.open(TARGET, 'w') do |fn| - fn.write out - end - end - end - -rescue LoadError - STDERR.puts "\n*** TomlRb not available.\n\n" -end - -private - -def preamble - <<-EOL -# #{@toml['Preamble']['title']} -#{@toml['Preamble']['text']} -EOL -end - -def project_lieutenant - <<-EOL -# #{@toml['Org']['Components']['Core']['title']} -#{github_link(@toml['Org']['Components']['Core']['lieutenant'])} - -EOL -end - -def all_maintainers - text = "# Maintainers\n" - @toml['Org']['Components']['Core']['maintainers'].each do |m| - text << "#{github_link(m)}\n" - end - text -end - -def github_link(person) - name = @toml['people'][person]['name'] - github = @toml['people'][person]['github'] - "* [#{name}](https://github.com/#{github})" -end diff --git a/cookbooks/apt/templates/01proxy.erb b/cookbooks/apt/templates/01proxy.erb new file mode 100644 index 00000000..1ede9b33 --- /dev/null +++ b/cookbooks/apt/templates/01proxy.erb @@ -0,0 +1,11 @@ +Acquire::http::Proxy "http://<%= @server['host'] %>:<%= @server['port'] %>"; +<% if @server['proxy_ssl'] %> +Acquire::https::Proxy "http://<%= @server['host'] %>:<%= @server['port'] %>"; +<% else %> +Acquire::https::Proxy "DIRECT"; +<% end %> +<% unless @server['cache_bypass'].nil? %> +<% @server['cache_bypass'].each do |bypass, type| %> +Acquire::<%= type %>::Proxy::<%= bypass %> "DIRECT"; +<% end %> +<% end %> diff --git a/cookbooks/apt/templates/10dpkg-options.erb b/cookbooks/apt/templates/10dpkg-options.erb new file mode 100644 index 00000000..3111026f --- /dev/null +++ b/cookbooks/apt/templates/10dpkg-options.erb @@ -0,0 +1,8 @@ +# Managed by Chef +DPkg::Options { +<%= node['apt']['confd']['force_confask'] ? '"--force-confask";' : '' -%> +<%= node['apt']['confd']['force_confdef'] ? '"--force-confdef";' : '' -%> +<%= node['apt']['confd']['force_confmiss'] ? '"--force-confmiss";' : '' -%> +<%= node['apt']['confd']['force_confnew'] ? '"--force-confnew";' : '' -%> +<%= node['apt']['confd']['force_confold'] ? '"--force-confold";' : '' -%> +} diff --git a/cookbooks/apt/templates/default/10recommends.erb b/cookbooks/apt/templates/10recommends.erb similarity index 100% rename from cookbooks/apt/templates/default/10recommends.erb rename to cookbooks/apt/templates/10recommends.erb diff --git a/cookbooks/apt/templates/default/20auto-upgrades.erb b/cookbooks/apt/templates/20auto-upgrades.erb similarity index 100% rename from cookbooks/apt/templates/default/20auto-upgrades.erb rename to cookbooks/apt/templates/20auto-upgrades.erb diff --git a/cookbooks/apt/templates/default/50unattended-upgrades.erb b/cookbooks/apt/templates/50unattended-upgrades.erb similarity index 79% rename from cookbooks/apt/templates/default/50unattended-upgrades.erb rename to cookbooks/apt/templates/50unattended-upgrades.erb index 9bf0380d..599a1c84 100644 --- a/cookbooks/apt/templates/default/50unattended-upgrades.erb +++ b/cookbooks/apt/templates/50unattended-upgrades.erb @@ -25,7 +25,7 @@ Unattended-Upgrade::Package-Blacklist { }; // This option allows you to control if on a unclean dpkg exit -// unattended-upgrades will automatically run +// unattended-upgrades will automatically run // dpkg --force-confold --configure -a // The default is true, to ensure updates keep getting installed Unattended-Upgrade::AutoFixInterruptedDpkg "<%= node['apt']['unattended_upgrades']['auto_fix_interrupted_dpkg'] ? 'true' : 'false' %>"; @@ -41,14 +41,20 @@ Unattended-Upgrade::MinimalSteps "<%= node['apt']['unattended_upgrades']['minima // This will (obviously) make shutdown slower Unattended-Upgrade::InstallOnShutdown "<%= node['apt']['unattended_upgrades']['install_on_shutdown'] ? 'true' : 'false' %>"; +<% if node['apt']['unattended_upgrades']['mail'] -%> // Send email to this address for problems or packages upgrades // If empty or unset then no email is sent, make sure that you // have a working mail setup on your system. A package that provides // 'mailx' must be installed. -<% if node['apt']['unattended_upgrades']['mail'] -%> Unattended-Upgrade::Mail "<%= node['apt']['unattended_upgrades']['mail'] %>"; <% end -%> +<% if node['apt']['unattended_upgrades']['sender'] -%> +// This option allows to customize the email address used in the +// 'From' header. unattended-upgrades will use "root" if unset. +Unattended-Upgrade::Sender "<%= node['apt']['unattended_upgrades']['sender'] %>"; +<% end -%> + // Set this value to "true" to get emails only on errors. Default // is to always send a mail if Unattended-Upgrade::Mail is set Unattended-Upgrade::MailOnlyOnError "<%= node['apt']['unattended_upgrades']['mail_only_on_error'] ? 'true' : 'false' %>"; @@ -57,19 +63,25 @@ Unattended-Upgrade::MailOnlyOnError "<%= node['apt']['unattended_upgrades']['mai // (equivalent to apt-get autoremove) Unattended-Upgrade::Remove-Unused-Dependencies "<%= node['apt']['unattended_upgrades']['remove_unused_dependencies'] ? 'true' : 'false' %>"; -// Automatically reboot *WITHOUT CONFIRMATION* if a -// the file /var/run/reboot-required is found after the upgrade +// Automatically reboot *WITHOUT CONFIRMATION* if a +// the file /var/run/reboot-required is found after the upgrade Unattended-Upgrade::Automatic-Reboot "<%= node['apt']['unattended_upgrades']['automatic_reboot'] ? 'true' : 'false' %>"; -// If automatic reboot is enabled and needed, reboot at the specific -// time instead of immediately -// Default: "now" <% if node['apt']['unattended_upgrades']['automatic_reboot'] -%> +// If automatic reboot is enabled and needed, reboot at the specific +// time instead of immediately. Default is "now" Unattended-Upgrade::Automatic-Reboot-Time "<%= node['apt']['unattended_upgrades']['automatic_reboot_time'] %>"; <% end %> +<% if node['apt']['unattended_upgrades']['dl_limit'] -%> // Use apt bandwidth limit feature, this example limits the download // speed to 70kb/sec -<% if node['apt']['unattended_upgrades']['dl_limit'] -%> +// Acquire::http::Dl-Limit "70"; Acquire::http::Dl-Limit "<%= node['apt']['unattended_upgrades']['dl_limit'] %>"; <% end -%> + +// Enable logging to syslog. Default is False +Unattended-Upgrade::SyslogEnable "<%= node['apt']['unattended_upgrades']['syslog_enable'] ? 'true' : 'false' %>"; + +// Specify syslog facility. Default is daemon +Unattended-Upgrade::SyslogFacility "<%= node['apt']['unattended_upgrades']['syslog_facility'] %>"; diff --git a/cookbooks/apt/templates/default/acng.conf.erb b/cookbooks/apt/templates/acng.conf.erb similarity index 100% rename from cookbooks/apt/templates/default/acng.conf.erb rename to cookbooks/apt/templates/acng.conf.erb diff --git a/cookbooks/apt/templates/default/01proxy.erb b/cookbooks/apt/templates/default/01proxy.erb deleted file mode 100644 index 1cd22565..00000000 --- a/cookbooks/apt/templates/default/01proxy.erb +++ /dev/null @@ -1,9 +0,0 @@ -Acquire::http::Proxy "http://<%= @proxy %>:<%= @port %>"; -<% if @proxy_ssl %> -Acquire::https::Proxy "http://<%= @proxy %>:<%= @port %>"; -<% else %> -Acquire::https::Proxy "DIRECT"; -<% end %> -<% @bypass.each do |bypass, type| %> -Acquire::<%= type %>::Proxy::<%= bypass %> "DIRECT"; -<% end %> diff --git a/cookbooks/apt/templates/default/unattended-upgrades.seed.erb b/cookbooks/apt/templates/unattended-upgrades.seed.erb similarity index 100% rename from cookbooks/apt/templates/default/unattended-upgrades.seed.erb rename to cookbooks/apt/templates/unattended-upgrades.seed.erb diff --git a/cookbooks/apt/test/fixtures/cookbooks/apt_test/README.md b/cookbooks/apt/test/fixtures/cookbooks/apt_test/README.md deleted file mode 100644 index 6e1f5788..00000000 --- a/cookbooks/apt/test/fixtures/cookbooks/apt_test/README.md +++ /dev/null @@ -1 +0,0 @@ -This cookbook is used with test-kitchen to test the parent, apt cookbok diff --git a/cookbooks/apt/test/fixtures/cookbooks/apt_test/metadata.rb b/cookbooks/apt/test/fixtures/cookbooks/test/metadata.rb similarity index 73% rename from cookbooks/apt/test/fixtures/cookbooks/apt_test/metadata.rb rename to cookbooks/apt/test/fixtures/cookbooks/test/metadata.rb index 95448c80..75706ef1 100644 --- a/cookbooks/apt/test/fixtures/cookbooks/apt_test/metadata.rb +++ b/cookbooks/apt/test/fixtures/cookbooks/test/metadata.rb @@ -1,7 +1,7 @@ -name 'apt_test' +name 'test' maintainer 'Chef Software, Inc.' maintainer_email 'cookbooks@chef.io' -license 'Apache 2.0' -description 'This cookbook is used with test-kitchen to test the parent, apt cookbok' +license 'Apache-2.0' +description 'This cookbook is used with test-kitchen to test the parent, apt cookbook' version '1.0.0' depends 'apt' diff --git a/cookbooks/apt/test/integration/cacher-client/serverspec/cacher-client_spec.rb b/cookbooks/apt/test/fixtures/cookbooks/test/recipes/base.rb similarity index 60% rename from cookbooks/apt/test/integration/cacher-client/serverspec/cacher-client_spec.rb rename to cookbooks/apt/test/fixtures/cookbooks/test/recipes/base.rb index 2f50dd44..32e1972d 100644 --- a/cookbooks/apt/test/integration/cacher-client/serverspec/cacher-client_spec.rb +++ b/cookbooks/apt/test/fixtures/cookbooks/test/recipes/base.rb @@ -1,8 +1,8 @@ # -# Cookbook Name:: apt_test -# Recipe:: cacher-client_test +# Cookbook:: test +# Recipe:: base # -# Copyright 2013, Chef Software, Inc. +# Copyright:: 2016-2017, 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. @@ -17,10 +17,18 @@ # limitations under the License. # -require_relative './spec_helper' +apt_update 'update' -describe 'apt_test::cacher-client' do - it 'does not create 01proxy' do - expect(file('/etc/apt/apt.conf.d/01proxy')).to_not exist +# without this dist data won't be populated by Ohai in docker +if platform?('debian') + package 'lsb-release' do + action :install + notifies :reload, 'ohai[reload_ohai]', :immediately + end + + ohai 'reload_ohai' do + action :nothing end end + +include_recipe 'apt::default' diff --git a/cookbooks/apt/test/fixtures/cookbooks/test/recipes/cacher.rb b/cookbooks/apt/test/fixtures/cookbooks/test/recipes/cacher.rb new file mode 100644 index 00000000..86ad60e7 --- /dev/null +++ b/cookbooks/apt/test/fixtures/cookbooks/test/recipes/cacher.rb @@ -0,0 +1,39 @@ +# +# Cookbook:: test +# Recipe:: cacher +# +# Copyright:: 2013-2017, 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. +# + +node.default['apt']['cacher_dir'] = '/tmp/apt-cacher' +node.default['apt']['cacher_port'] = '9876' +node.default['apt']['cacher_interface'] = 'eth0' +node.default['apt']['cacher_client']['cacher_server'] = { + host: 'localhost', + port: 9876, + proxy_ssl: true, + cache_bypass: { + 'download.oracle.com' => 'https', + 'nginx.org' => 'https', + }, +} + +include_recipe 'test::base' + +include_recipe 'apt::cacher-ng' +include_recipe 'apt::cacher-client' + +# install a small, innocuous application to verify this works +package 'colordiff' diff --git a/cookbooks/apt/test/fixtures/cookbooks/apt_test/recipes/lwrps.rb b/cookbooks/apt/test/fixtures/cookbooks/test/recipes/resources.rb similarity index 61% rename from cookbooks/apt/test/fixtures/cookbooks/apt_test/recipes/lwrps.rb rename to cookbooks/apt/test/fixtures/cookbooks/test/recipes/resources.rb index 55041007..dbb27e9f 100644 --- a/cookbooks/apt/test/fixtures/cookbooks/apt_test/recipes/lwrps.rb +++ b/cookbooks/apt/test/fixtures/cookbooks/test/recipes/resources.rb @@ -1,8 +1,8 @@ # -# Cookbook Name:: apt_test -# Recipe:: lwrps +# Cookbook:: test +# Recipe:: resources # -# Copyright 2012-2016, Chef Software, Inc. +# Copyright:: 2012-2017, 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. @@ -17,33 +17,43 @@ # limitations under the License. # -include_recipe 'apt' - -# Apt Repository -apt_repository 'juju' do - uri '"http://ppa.launchpad.net/juju/stable/ubuntu"' - components ['main'] - distribution 'trusty' - key 'C8068B11' - keyserver 'keyserver.ubuntu.com' - action :add -end - -# Apt Repository -apt_repository 'nodejs' do - uri 'http://ppa.launchpad.net/chris-lea/node.js/ubuntu' - components ['main'] - distribution 'trusty' - key 'C7917B12' - keyserver 'hkp://keyserver.ubuntu.com:80' - action :add -end - -# PPA Repository -apt_repository 'rust' do - uri 'ppa:hansjorg/rust' - distribution node['lsb']['codename'] - not_if { node['platform'] == 'debian' } +include_recipe 'test::base' + +if node['platform'] == 'ubuntu' + # Apt Repository + apt_repository 'juju' do + uri '"http://ppa.launchpad.net/juju/stable/ubuntu"' + components ['main'] + distribution 'trusty' + key 'C8068B11' + keyserver 'keyserver.ubuntu.com' + action :add + end + + # Apt Repository + apt_repository 'nodejs' do + uri 'http://ppa.launchpad.net/chris-lea/node.js/ubuntu' + components ['main'] + distribution 'trusty' + key 'C7917B12' + keyserver 'hkp://keyserver.ubuntu.com:80' + action :add + end + + # PPA Repository w/o key specified + apt_repository 'gimp' do + uri 'ppa:otto-kesselgulasch/gimp' + end + + # Apt repository that suppresses output for sensitive resources. + apt_repository 'haproxy' do + uri 'http://ppa.launchpad.net/vbernat/haproxy-1.5/ubuntu' + components ['main'] + keyserver 'keyserver.ubuntu.com' + key '1C61B9CD' + sensitive true + action :add + end end # Apt Repository with arch @@ -59,25 +69,13 @@ # Apt repository and install a package it contains apt_repository 'nginx' do uri "http://nginx.org/packages/#{node['platform']}" - distribution node['lsb']['codename'] components ['nginx'] key 'http://nginx.org/keys/nginx_signing.key' deb_src true end -# Apt repository that suppresses output for sensitive resources. -apt_repository 'haproxy' do - uri 'http://ppa.launchpad.net/vbernat/haproxy-1.5/ubuntu' - distribution node['lsb']['codename'] - components ['main'] - keyserver 'keyserver.ubuntu.com' - key '1C61B9CD' - sensitive true - action :add -end - package 'nginx' do - action :upgrade + action :install end # Apt Preferences @@ -93,6 +91,7 @@ apt_preference 'wget' do pin 'version 1.13.4-3' + pin_priority '1001' end # COOK-2338 @@ -109,6 +108,7 @@ apt_preference '*' do pin 'origin nginx.org' + pin_priority '1001' end # Preference file removal diff --git a/cookbooks/apt/test/fixtures/cookbooks/apt_test/recipes/cacher-ng-client.rb b/cookbooks/apt/test/fixtures/cookbooks/test/recipes/unattended-upgrades.rb similarity index 69% rename from cookbooks/apt/test/fixtures/cookbooks/apt_test/recipes/cacher-ng-client.rb rename to cookbooks/apt/test/fixtures/cookbooks/test/recipes/unattended-upgrades.rb index b03382e9..77c955da 100644 --- a/cookbooks/apt/test/fixtures/cookbooks/apt_test/recipes/cacher-ng-client.rb +++ b/cookbooks/apt/test/fixtures/cookbooks/test/recipes/unattended-upgrades.rb @@ -1,8 +1,8 @@ # -# Cookbook Name:: apt_test -# Recipe:: cacher-ng-client +# Cookbook:: test +# Recipe:: unattended-upgrades # -# Copyright 2013, Chef Software, Inc. +# Copyright:: 2016-2017, 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. @@ -17,8 +17,5 @@ # limitations under the License. # -include_recipe 'apt::cacher-ng' -include_recipe 'apt::cacher-client' - -# install a small, innocuous application to verify this works -package 'colordiff' +include_recipe 'test::base' +include_recipe 'apt::unattended-upgrades' diff --git a/cookbooks/apt/test/integration/cacher-ng/serverspec/cacher-ng_spec.rb b/cookbooks/apt/test/integration/cacher-ng/serverspec/cacher-ng_spec.rb deleted file mode 100644 index 07192fbe..00000000 --- a/cookbooks/apt/test/integration/cacher-ng/serverspec/cacher-ng_spec.rb +++ /dev/null @@ -1,26 +0,0 @@ -# -# Cookbook Name:: apt_test -# Recipe:: default -# -# Copyright 2012, 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. -# - -require_relative './spec_helper' - -describe 'apt_test::default' do - it 'runs the cacher service' do - expect(service('apt-cacher-ng')).to be_running - end -end diff --git a/cookbooks/apt/test/integration/cacher-ng-client/serverspec/cacher-ng-client_spec.rb b/cookbooks/apt/test/integration/cacher/cacher-ng-client_spec.rb similarity index 85% rename from cookbooks/apt/test/integration/cacher-ng-client/serverspec/cacher-ng-client_spec.rb rename to cookbooks/apt/test/integration/cacher/cacher-ng-client_spec.rb index 6dd15d6d..1ecaf1db 100644 --- a/cookbooks/apt/test/integration/cacher-ng-client/serverspec/cacher-ng-client_spec.rb +++ b/cookbooks/apt/test/integration/cacher/cacher-ng-client_spec.rb @@ -1,8 +1,8 @@ # -# Cookbook Name:: apt_test +# Cookbook:: test # Recipe:: cacher-ng-client_test.rb # -# Copyright 2013, Chef Software, Inc. +# Copyright:: 2013-2017, 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. @@ -17,9 +17,11 @@ # limitations under the License. # -require_relative './spec_helper' +describe 'test::cacher' do + it 'runs the cacher service' do + expect(service('apt-cacher-ng')).to be_running + end -describe 'apt_test::cacher-ng-client' do it 'creates the cacher_dir' do expect(file('/var/cache/apt-cacher-ng')).to be_directory expect(file('/var/cache/apt-cacher-ng')).to be_owned_by('apt-cacher-ng') diff --git a/cookbooks/apt/test/integration/compile-time/default_spec.rb b/cookbooks/apt/test/integration/compile-time/default_spec.rb new file mode 100644 index 00000000..51b0a19f --- /dev/null +++ b/cookbooks/apt/test/integration/compile-time/default_spec.rb @@ -0,0 +1,7 @@ +control 'apt::default' do + describe file('/var/lib/apt/periodic/update-success-stamp') do + it 'exists' do + expect(subject).to exist + end + end +end diff --git a/cookbooks/apt/test/integration/compile_time/serverspec/default_spec.rb b/cookbooks/apt/test/integration/compile_time/serverspec/default_spec.rb deleted file mode 100644 index cc5e23dd..00000000 --- a/cookbooks/apt/test/integration/compile_time/serverspec/default_spec.rb +++ /dev/null @@ -1,9 +0,0 @@ -require_relative './spec_helper' - -describe 'apt::default' do - describe file('/tmp/kitchen/cache/apt_compile_time_update_first_run') do - it 'exists' do - expect(subject).to exist - end - end -end diff --git a/cookbooks/apt/test/integration/default/default_spec.rb b/cookbooks/apt/test/integration/default/default_spec.rb new file mode 100644 index 00000000..291fd5e4 --- /dev/null +++ b/cookbooks/apt/test/integration/default/default_spec.rb @@ -0,0 +1,45 @@ +if os.name == 'debian' || os.name == 'ubuntu' + describe file('/var/cache/local/preseeding') do + it { should be_a_directory } + end + + content_dpkg_options = [ + '# Managed by Chef', + 'DPkg::Options {', + '}', + ].join("\n") << "\n" + + content_recommends = [ + '# Managed by Chef', + 'APT::Install-Recommends "1";', + 'APT::Install-Suggests "0";', + ].join("\n") << "\n" + + describe file('/etc/apt/apt.conf.d/10dpkg-options') do + it { should be_file } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 0644 } + its(:content) { should eq content_dpkg_options } + end + + describe file('/etc/apt/apt.conf.d/10recommends') do + it { should be_file } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 0644 } + its(:content) { should eq content_recommends } + end +else + describe file('/etc/apt/') do + it { should_not exist } + end + + describe file('/var/lib/apt/periodic/update-success-stamp') do + it { should_not exist } + end + + describe file('/var/cache/local/preseeding') do + it { should_not exist } + end +end diff --git a/cookbooks/apt/test/integration/default/serverspec/default_spec.rb b/cookbooks/apt/test/integration/default/serverspec/default_spec.rb deleted file mode 100644 index c6b885a7..00000000 --- a/cookbooks/apt/test/integration/default/serverspec/default_spec.rb +++ /dev/null @@ -1,37 +0,0 @@ -require_relative './spec_helper' - -if %w(debian ubuntu).include?(os[:family]) - describe 'apt::default' do - describe file('/var/cache/local/preseeding') do - it 'is a directory' do - expect(subject).to be_a_directory - end - end - - content = [ - '# Managed by Chef', - 'APT::Install-Recommends "1";', - 'APT::Install-Suggests "0";' - ].join("\n") << "\n" - - describe file('/etc/apt/apt.conf.d/10recommends') do - it { should be_file } - it { should be_owned_by 'root' } - it { should be_grouped_into 'root' } - it { should be_mode 644 } - its(:content) { should eq content } - end - end -else - describe file('/etc/apt/') do - it { should_not exist } - end - - describe file('/var/lib/apt/periodic/update-success-stamp') do - it { should_not exist } - end - - describe file('/var/cache/local/preseeding') do - it { should_not exist } - end -end diff --git a/cookbooks/apt/test/integration/helpers/serverspec/spec_helper.rb b/cookbooks/apt/test/integration/helpers/serverspec/spec_helper.rb deleted file mode 100644 index 5f07c486..00000000 --- a/cookbooks/apt/test/integration/helpers/serverspec/spec_helper.rb +++ /dev/null @@ -1,4 +0,0 @@ -require 'serverspec' - -set :backend, :exec -set :path, '/sbin:/usr/sbin:$PATH' diff --git a/cookbooks/apt/test/integration/lwrps/serverspec/lwrps_spec.rb b/cookbooks/apt/test/integration/resources/resources_spec.rb similarity index 74% rename from cookbooks/apt/test/integration/lwrps/serverspec/lwrps_spec.rb rename to cookbooks/apt/test/integration/resources/resources_spec.rb index 2105bddb..3f34f4e6 100644 --- a/cookbooks/apt/test/integration/lwrps/serverspec/lwrps_spec.rb +++ b/cookbooks/apt/test/integration/resources/resources_spec.rb @@ -1,8 +1,8 @@ # -# Cookbook Name:: apt_test -# Recipe:: lwrps +# Cookbook:: test +# Recipe:: resources # -# Copyright 2012, Chef Software, Inc. +# Copyright:: 2012-2017, 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. @@ -16,29 +16,31 @@ # See the License for the specific language governing permissions and # limitations under the License. # - -require_relative './spec_helper' - -describe 'apt_test::lwrps' do +describe 'apt::resources' do it 'creates the JuJu sources.list' do + skip('not on ubuntu') unless os.name == 'ubuntu' expect(file('/etc/apt/sources.list.d/juju.list')).to exist end it 'creates the NodeJS sources.list' do + skip('not on ubuntu') unless os.name == 'ubuntu' expect(file('/etc/apt/sources.list.d/nodejs.list')).to exist end it 'creates the HAProxy sources.list' do + skip('not on ubuntu') unless os.name == 'ubuntu' expect(file('/etc/apt/sources.list.d/haproxy.list')).to exist end it 'creates a repo with a url that is already quoted' do + skip('not on ubuntu') unless os.name == 'ubuntu' src = 'deb\s+\"http://ppa.launchpad.net/juju/stable/ubuntu\" trusty main' expect(file('/etc/apt/sources.list.d/juju.list').content).to match(/#{src}/) end it 'adds the JuJu package signing key' do - expect(command('apt-key list').stdout).to contain('Launchpad Ensemble PPA') + skip('not on ubuntu') unless os.name == 'ubuntu' + expect(command('apt-key list').stdout).to include('Launchpad Ensemble PPA') end it 'creates the correct pinning preferences for chef' do @@ -47,9 +49,9 @@ end it 'correctly handles a ppa: repository' do - skip('not on ubuntu') unless os[:family] == 'ubuntu' - rust = 'http://ppa.launchpad.net/hansjorg/rust/ubuntu' - expect(file('/etc/apt/sources.list.d/rust.list').content).to match(/#{rust}/) + skip('not on ubuntu') unless os.name == 'ubuntu' + gimp = 'http://ppa.launchpad.net/otto-kesselgulasch/gimp/ubuntu' + expect(file('/etc/apt/sources.list.d/gimp.list').content).to match(/#{gimp}/) end it 'renames an old preferences file' do @@ -67,7 +69,7 @@ end it 'creates a repo with an architecture' do - cloudera = 'deb\s+\[arch=amd64 \] \"http:\/\/archive.cloudera.com\/cdh4\/ubuntu\/precise\/amd64\/cdh\" precise-cdh4 contrib' + cloudera = 'deb\s+\[arch=amd64\] "http:\/\/archive.cloudera.com\/cdh4\/ubuntu\/precise\/amd64\/cdh" precise-cdh4 contrib' expect(file('/etc/apt/sources.list.d/cloudera.list').content).to match(/#{cloudera}/) end diff --git a/cookbooks/build-essential/.delivery/project.toml b/cookbooks/build-essential/.delivery/project.toml new file mode 100644 index 00000000..6d5e3617 --- /dev/null +++ b/cookbooks/build-essential/.delivery/project.toml @@ -0,0 +1 @@ +remote_file = "https://raw.githubusercontent.com/chef-cookbooks/community_cookbook_tools/master/delivery/project.toml" diff --git a/cookbooks/build-essential/.github/ISSUE_TEMPLATE.md b/cookbooks/build-essential/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..651e753a --- /dev/null +++ b/cookbooks/build-essential/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,20 @@ +### Cookbook version +[Version of the cookbook where you are encountering the issue] + +### Chef-client version +[Version of chef-client in your environment] + +### Platform Details +[Operating system distribution and release version. Cloud provider if running in the cloud] + +### Scenario: +[What you are trying to achieve and you can't?] + +### Steps to Reproduce: +[If you are filing an issue what are the things we need to do in order to repro your problem? How are you using this cookbook or any resources it includes?] + +### Expected Result: +[What are you expecting to happen as the consequence of above reproduction steps?] + +### Actual Result: +[What actually happens after the reproduction steps? Include the error output or a link to a gist if possible.] diff --git a/cookbooks/build-essential/.github/PULL_REQUEST_TEMPLATE.md b/cookbooks/build-essential/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..b8c6d9f9 --- /dev/null +++ b/cookbooks/build-essential/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,14 @@ +### Description + +[Describe what this change achieves] + +### Issues Resolved + +[List any existing issues this PR resolves] + +### Check List + +- [ ] All tests pass. See +- [ ] New functionality includes testing. +- [ ] New functionality has been documented in the README if applicable +- [ ] All commits have been signed for the Developer Certificate of Origin. See diff --git a/cookbooks/build-essential/.gitignore b/cookbooks/build-essential/.gitignore new file mode 100644 index 00000000..6c97e28f --- /dev/null +++ b/cookbooks/build-essential/.gitignore @@ -0,0 +1,49 @@ +*.rbc +.config +coverage +InstalledFiles +lib/bundler/man +pkg +rdoc +spec/reports +test/tmp +test/version_tmp +tmp +_Store +*~ +*# +.#* +\#*# +.*.sw[a-z] +*.un~ +*.tmp +*.bk +*.bkup + +# ruby/bundler files +.ruby-version +.ruby-gemset +.rvmrc +Gemfile.lock +.bundle +*.gem + +# YARD artifacts +.yardoc +_yardoc +doc/ +.idea + +# chef stuff +Berksfile.lock +.kitchen +.kitchen.local.yml +vendor/ +.coverage/ +.zero-knife.rb +Policyfile.lock.json + +# vagrant stuff +.vagrant/ +.vagrant.d/ +.kitchen/ diff --git a/cookbooks/build-essential/.kitchen.dokken.yml b/cookbooks/build-essential/.kitchen.dokken.yml new file mode 100644 index 00000000..176f867f --- /dev/null +++ b/cookbooks/build-essential/.kitchen.dokken.yml @@ -0,0 +1,82 @@ +driver: + name: dokken + privileged: true # because Docker and SystemD/Upstart + chef_version: <%= ENV['CHEF_VERSION'] || 'current' %> + +transport: + name: dokken + +provisioner: + name: dokken + deprecations_as_errors: true + +verifier: + name: inspec + +platforms: +- name: amazonlinux + driver: + image: dokken/amazonlinux + pid_one_command: /sbin/init + dns: + - 8.8.8.8 + +- name: amazonlinux-2 + driver: + image: dokken/amazonlinux-2 + pid_one_command: /usr/lib/systemd/systemd + +- name: debian-8 + driver: + image: dokken/debian-8 + pid_one_command: /bin/systemd + intermediate_instructions: + - RUN /usr/bin/apt-get update + +- name: debian-9 + driver: + image: dokken/debian-9 + pid_one_command: /bin/systemd + intermediate_instructions: + - RUN /usr/bin/apt-get update + +- name: centos-6 + driver: + image: dokken/centos-6 + pid_one_command: /sbin/init + +- name: centos-7 + driver: + image: dokken/centos-7 + pid_one_command: /usr/lib/systemd/systemd + +- name: fedora-latest + driver: + image: dokken/fedora-latest + pid_one_command: /usr/lib/systemd/systemd + +- name: ubuntu-14.04 + driver: + image: dokken/ubuntu-14.04 + pid_one_command: /sbin/init + intermediate_instructions: + - RUN /usr/bin/apt-get update + +- name: ubuntu-16.04 + driver: + image: dokken/ubuntu-16.04 + pid_one_command: /bin/systemd + intermediate_instructions: + - RUN /usr/bin/apt-get update + +- name: ubuntu-18.04 + driver: + image: dokken/ubuntu-18.04 + pid_one_command: /bin/systemd + intermediate_instructions: + - RUN /usr/bin/apt-get update + +- name: opensuse-leap + driver: + image: dokken/opensuse-leap-42 + pid_one_command: /bin/systemd diff --git a/cookbooks/build-essential/.kitchen.yml b/cookbooks/build-essential/.kitchen.yml new file mode 100644 index 00000000..0c2911f7 --- /dev/null +++ b/cookbooks/build-essential/.kitchen.yml @@ -0,0 +1,46 @@ +driver: + name: vagrant + +provisioner: + name: chef_zero + deprecations_as_errors: true + +verifier: + name: inspec + +platforms: + - name: amazonlinux + driver_config: + box: mvbcoding/awslinux + - name: centos-6 + - name: centos-7 + - name: debian-8 + - name: debian-9 + - name: fedora-28 + - name: freebsd-10 + - name: freebsd-11 + - name: opensuse-leap-42 + - name: ubuntu-14.04 + - name: ubuntu-16.04 + - name: solaris-11 + driver: + box: chef/solaris-11 + - name: windows-2012r2-standard + driver: + box: chef/windows-server-2012r2-standard # private box in Chef's Atlas account + - name: windows-2016 + driver_config: + box: chef/windows-server-2016-standard # private box in Chef's Atlas account + - name: macos-10.12 + driver: + box: chef/macos-10.12 # private box in Chef's Atlas account + provider: vmware_fusion + +suites: + - name: default + run_list: test::default + - name: compile_time + run_list: test::default + attributes: + build-essential: + compile_time: true diff --git a/cookbooks/build-essential/.travis.yml b/cookbooks/build-essential/.travis.yml new file mode 100644 index 00000000..6bc9fcb5 --- /dev/null +++ b/cookbooks/build-essential/.travis.yml @@ -0,0 +1,47 @@ +sudo: required +dist: trusty + +addons: + apt: + sources: + - chef-current-trusty + packages: + - chefdk + +# Don't `bundle install` which takes about 1.5 mins +install: echo "skip bundle install" + +branches: + only: + - master + +services: docker + +env: + matrix: + - INSTANCE=default-amazonlinux + - INSTANCE=default-amazonlinux-2 + - INSTANCE=default-centos-6 + - INSTANCE=default-centos-7 + - INSTANCE=default-debian-8 + - INSTANCE=default-debian-9 + - INSTANCE=default-fedora-latest + - INSTANCE=default-opensuse-leap + - INSTANCE=default-ubuntu-1404 + - INSTANCE=default-ubuntu-1604 + - INSTANCE=default-ubuntu-1804 + +before_script: + - sudo iptables -L DOCKER || ( echo "DOCKER iptables chain missing" ; sudo iptables -N DOCKER ) + - eval "$(chef shell-init bash)" + - chef --version + - cookstyle --version + - foodcritic --version + +script: KITCHEN_LOCAL_YAML=.kitchen.dokken.yml kitchen verify ${INSTANCE} + +matrix: + include: + - script: + - chef exec delivery local all + env: UNIT_AND_LINT=1 diff --git a/cookbooks/build-essential/Berksfile b/cookbooks/build-essential/Berksfile new file mode 100644 index 00000000..5a7274b5 --- /dev/null +++ b/cookbooks/build-essential/Berksfile @@ -0,0 +1,7 @@ +source 'https://supermarket.chef.io' + +metadata + +group :integration do + cookbook 'test', path: 'test/cookbooks/test' +end diff --git a/cookbooks/build-essential/CHANGELOG.md b/cookbooks/build-essential/CHANGELOG.md index e6d33f25..95c1a290 100644 --- a/cookbooks/build-essential/CHANGELOG.md +++ b/cookbooks/build-essential/CHANGELOG.md @@ -2,6 +2,34 @@ This file is used to list changes made in each version of the build-essential cookbook. +## 8.2.1 (2018-09-04) + +- Add a note that this cookbook is no longer maintained as the build_essential resource was moved directly into the chef-client making this cookbook no longer necessary. + +## 8.2.0 (2018-08-28) + +- Simplify the if installed logic for macos +- Remove support for FreeBSD < 10 which is VERY much EOL +- Avoid ChefSpec deprecation warnings +- Avoid deprecation warnings in Chef 14.3+ by not loading resources already in Chef + +## 8.1.1 (2018-03-17) + +- Make sure we install the last available xcode command line tool package so we get the latest version + +## 8.1.0 (2018-03-17) + +- Support Amazon Linux 2.0 +- Remove the ChefSpec matchers which are autogenerated now in recent ChefDK releaeses. If your specs fail because of this you need to update to a more recent ChefDK release. +- Swap Debian 7 testing for Amazon 2 & Ubuntu 18.04 testing since Debian 7 is EOL in May + +## 8.0.4 (2017-11-29) + +- Install gcc-c and gcc-c++ for solaris 11 +- Fix dokken's amazonlinux configuration +- Update chef dependency in metadata.rb to Chef 12.7 +- Clean up testing + ## 8.0.3 (2017-05-30) - Fix solaris metadata in metadata.rb diff --git a/cookbooks/build-essential/Gemfile b/cookbooks/build-essential/Gemfile index 4396eb13..c1dbddd8 100644 --- a/cookbooks/build-essential/Gemfile +++ b/cookbooks/build-essential/Gemfile @@ -6,6 +6,4 @@ source 'https://rubygems.org' -gem 'tomlrb' -gem 'stove' gem 'community_cookbook_releaser' diff --git a/cookbooks/build-essential/MAINTAINERS.md b/cookbooks/build-essential/MAINTAINERS.md deleted file mode 100644 index 645ed141..00000000 --- a/cookbooks/build-essential/MAINTAINERS.md +++ /dev/null @@ -1,15 +0,0 @@ - - -# 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 -* [Tim Smith](https://github.com/tas50) - -# Maintainers -* [Jennifer Davis](https://github.com/sigje) -* [Tim Smith](https://github.com/tas50) -* [Thom May](https://github.com/thommay) diff --git a/cookbooks/build-essential/MAINTAINERS.toml b/cookbooks/build-essential/MAINTAINERS.toml deleted file mode 100644 index 6bb35d63..00000000 --- a/cookbooks/build-essential/MAINTAINERS.toml +++ /dev/null @@ -1,38 +0,0 @@ -# -# This file is structured to be consumed by both humans and computers. -# It is a TOML document containing Markdown -# -[Preamble] - title = "Maintainers" - text = """ - -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. -""" - -[Org] - [Org.Components] - [Org.Components.Core] - title = "Project Maintainer" - - lieutenant = 'tas50' - - maintainers = [ - 'sigje', - 'tas50', - 'thommay' - ] - -[people] - [people.sigje] - name = "Jennifer Davis" - github = "sigje" - - [people.tas50] - name = "Tim Smith" - github = "tas50" - - [people.thommay] - name = "Thom May" - github = "thommay" diff --git a/cookbooks/build-essential/README.md b/cookbooks/build-essential/README.md index ac352671..0550ffbf 100644 --- a/cookbooks/build-essential/README.md +++ b/cookbooks/build-essential/README.md @@ -4,6 +4,10 @@ Installs packages required for compiling C software from source. Use this cookbook if you wish to compile C programs, or install RubyGems with native extensions. Contains a resource, 'build_essential', as as well as a default recipe that simply calls that same resource. +## Deprecation + +The functionality of this cookbook is now built into Chef 14+ in the [build_essential resource](https://docs.chef.io/resource_build_essential.html). This cookbook is no longer being maintained and all future changes will be done directly in the chef-client. We highly recommend you update your chef-client to the latest release and if possible migrate to using the build_essential resources instead of the recipe in this cookbook. + ## Requirements ### Platforms @@ -18,7 +22,7 @@ Installs packages required for compiling C software from source. Use this cookbo ### Chef -- Chef 12.5+ +- Chef 12.7+ ### Cookbooks @@ -110,9 +114,11 @@ build_essential 'some name you choose' do end ``` -## License & Authors +## Maintainers + +This cookbook is maintained by Chef's Community Cookbook Engineering team. Our goal is to improve cookbook quality and to aid the community in contributing to cookbooks. To learn more about our team, process, and design goals see our [team documentation](https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/COOKBOOK_TEAM.MD). To learn more about contributing to cookbooks like this see our [contributing documentation](https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/CONTRIBUTING.MD), or if you have general questions about this cookbook come chat with us in #cookbok-engineering on the [Chef Community Slack](http://community-slack.chef.io/) -**Author:** Cookbook Engineering Team ([cookbooks@chef.io](mailto:cookbooks@chef.io)) +## License **Copyright:** 2009-2016, Chef Software, Inc. diff --git a/cookbooks/build-essential/chefignore b/cookbooks/build-essential/chefignore index a9769175..cd4830c3 100644 --- a/cookbooks/build-essential/chefignore +++ b/cookbooks/build-essential/chefignore @@ -82,12 +82,16 @@ Berksfile.lock cookbooks/* tmp +# Policyfile # +############## +Policyfile.rb +Policyfile.lock.json + # Cookbooks # ############# CONTRIBUTING* CHANGELOG* TESTING* -MAINTAINERS.toml # Strainer # ############ diff --git a/cookbooks/build-essential/libraries/matchers.rb b/cookbooks/build-essential/libraries/matchers.rb deleted file mode 100644 index d4d1bd4c..00000000 --- a/cookbooks/build-essential/libraries/matchers.rb +++ /dev/null @@ -1,9 +0,0 @@ -if defined?(ChefSpec) - def install_xcode_command_line_tools(resource_name) - ChefSpec::Matchers::ResourceMatcher.new(:xcode_command_line_tools, :install, resource_name) - end - - def install_build_essential(resource_name) - ChefSpec::Matchers::ResourceMatcher.new(:build_essential, :install, resource_name) - end -end diff --git a/cookbooks/build-essential/metadata.rb b/cookbooks/build-essential/metadata.rb index 2adb51a7..36d078b7 100644 --- a/cookbooks/build-essential/metadata.rb +++ b/cookbooks/build-essential/metadata.rb @@ -4,7 +4,7 @@ license 'Apache-2.0' description 'Installs C compiler / build tools' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) -version '8.0.3' +version '8.2.1' recipe 'build-essential', 'Installs packages required for compiling C software from source.' supports 'amazon' @@ -30,4 +30,4 @@ source_url 'https://github.com/chef-cookbooks/build-essential' issues_url 'https://github.com/chef-cookbooks/build-essential/issues' -chef_version '>= 12.5' if respond_to?(:chef_version) +chef_version '>= 12.7' if respond_to?(:chef_version) diff --git a/cookbooks/build-essential/recipes/default.rb b/cookbooks/build-essential/recipes/default.rb index 11edff25..a5dfed37 100644 --- a/cookbooks/build-essential/recipes/default.rb +++ b/cookbooks/build-essential/recipes/default.rb @@ -2,7 +2,7 @@ # Cookbook:: build-essential # Recipe:: default # -# Copyright:: 2008-2017, Chef Software, Inc. +# Copyright:: 2008-2018, 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. diff --git a/cookbooks/build-essential/resources/build_essential.rb b/cookbooks/build-essential/resources/build_essential.rb index 76c67259..559284dc 100644 --- a/cookbooks/build-essential/resources/build_essential.rb +++ b/cookbooks/build-essential/resources/build_essential.rb @@ -2,7 +2,7 @@ # Cookbook:: build-essential # resource:: build_essential # -# Copyright:: 2008-2017, Chef Software, Inc. +# Copyright:: 2008-2018, 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. @@ -17,6 +17,7 @@ # limitations under the License. # +chef_version_for_provides '< 14.0' if respond_to?(:chef_version_for_provides) provides :build_essential resource_name :build_essential @@ -30,14 +31,12 @@ package %w( autoconf bison flex gcc gcc-c++ gettext kernel-devel make m4 ncurses-devel patch ) # Ensure GCC 4 is available on older pre-6 EL - package %w( gcc44 gcc44-c++ ) if node['platform_version'].to_i < 6 + package %w( gcc44 gcc44-c++ ) if !platform?('amazon') && node['platform_version'].to_i < 6 when 'freebsd' package 'devel/gmake' package 'devel/autoconf' package 'devel/m4' package 'devel/gettext' - # Only install gcc on freebsd 9.x - 10 uses clang - package 'lang/gcc49' if node['platform_version'].to_i <= 9 when 'mac_os_x' xcode_command_line_tools 'install' when 'omnios' @@ -62,11 +61,13 @@ package 'bison' package 'gnu-coreutils' package 'flex' - package 'gcc' do - # lock because we don't use 5 yet - version '4.8.2' + # lock gcc versions because we don't use 5 yet + %w(gcc gcc-c gcc-c++).each do |pkg| + package pkg do # ~FC009 + accept_license true + version '4.8.2' + end end - package 'gcc-3' package 'gnu-grep' package 'gnu-make' package 'gnu-patch' @@ -84,6 +85,7 @@ package 'pkg-config' when 'suse' package %w( autoconf bison flex gcc gcc-c++ kernel-default-devel make m4 ) + package 'insserv-compat' if node['platform_version'].to_i >= 15 package %w( gcc48 gcc48-c++ ) if node['platform_version'].to_i < 12 when 'windows' include_recipe 'build-essential::_windows' diff --git a/cookbooks/build-essential/resources/xcode_command_line_tools.rb b/cookbooks/build-essential/resources/xcode_command_line_tools.rb index 4c75cf17..44dbfaea 100644 --- a/cookbooks/build-essential/resources/xcode_command_line_tools.rb +++ b/cookbooks/build-essential/resources/xcode_command_line_tools.rb @@ -2,7 +2,7 @@ # Cookbook:: build-essential # Resource:: xcode_command_line_tools # -# Copyright:: 2014-2017, Chef Software, Inc. +# Copyright:: 2014-2018, 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. @@ -32,13 +32,12 @@ # in Apple's SUS catalog touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress # find the CLI Tools update - PROD=$(softwareupdate -l | grep "\*.*Command Line" | head -n 1 | awk -F"*" '{print $2}' | sed -e 's/^ *//' | tr -d '\n') + PROD=$(softwareupdate -l | grep "\*.*Command Line" | tail -n 1 | awk -F"*" '{print $2}' | sed -e 's/^ *//' | tr -d '\n') # install it softwareupdate -i "$PROD" --verbose # Remove the placeholder to prevent perpetual appearance in the update utility rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress EOH - # rubocop:enable Metrics/LineLength end end end @@ -53,9 +52,6 @@ def installed? cmd = Mixlib::ShellOut.new('pkgutil --pkgs=com.apple.pkg.CLTools_Executables') cmd.run_command - cmd.error! - true - rescue Mixlib::ShellOut::ShellCommandFailed - false + cmd.error? ? false : true end end diff --git a/cookbooks/build-essential/spec/recipes/debian_spec.rb b/cookbooks/build-essential/spec/recipes/debian_spec.rb index 6a4cc1a9..5ef04f72 100644 --- a/cookbooks/build-essential/spec/recipes/debian_spec.rb +++ b/cookbooks/build-essential/spec/recipes/debian_spec.rb @@ -1,12 +1,14 @@ require 'spec_helper' describe 'build-essential::default' do - let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'debian', version: '8.4', - step_into: ['build_essential']).converge('build-essential::default') - end + context 'Debian' do + let(:chef_run) do + ChefSpec::ServerRunner.new(platform: 'debian', version: '8.9', + step_into: ['build_essential']).converge('build-essential::default') + end - it 'installs the correct packages' do - expect(chef_run).to install_package(['autoconf', 'binutils-doc', 'bison', 'build-essential', 'flex', 'gettext', 'ncurses-dev']) + it 'installs the correct packages' do + expect(chef_run).to install_package(['autoconf', 'binutils-doc', 'bison', 'build-essential', 'flex', 'gettext', 'ncurses-dev']) + end end end diff --git a/cookbooks/build-essential/spec/recipes/fedora_spec.rb b/cookbooks/build-essential/spec/recipes/fedora_spec.rb index 421a3ed0..af62fd2c 100644 --- a/cookbooks/build-essential/spec/recipes/fedora_spec.rb +++ b/cookbooks/build-essential/spec/recipes/fedora_spec.rb @@ -1,12 +1,14 @@ require 'spec_helper' describe 'build-essential::default' do - let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'fedora', version: '23', - step_into: ['build_essential']).converge('build-essential::default') - end + context 'Fedora' do + let(:chef_run) do + ChefSpec::ServerRunner.new(platform: 'fedora', version: '28', + step_into: ['build_essential']).converge('build-essential::default') + end - it 'installs the correct packages' do - expect(chef_run).to install_package(['autoconf', 'bison', 'flex', 'gcc', 'gcc-c++', 'gettext', 'kernel-devel', 'make', 'm4', 'ncurses-devel', 'patch']) + it 'installs the correct packages' do + expect(chef_run).to install_package(['autoconf', 'bison', 'flex', 'gcc', 'gcc-c++', 'gettext', 'kernel-devel', 'make', 'm4', 'ncurses-devel', 'patch']) + end end end diff --git a/cookbooks/build-essential/spec/recipes/freebsd_spec.rb b/cookbooks/build-essential/spec/recipes/freebsd_spec.rb index 83619b40..5f09ce70 100644 --- a/cookbooks/build-essential/spec/recipes/freebsd_spec.rb +++ b/cookbooks/build-essential/spec/recipes/freebsd_spec.rb @@ -1,30 +1,17 @@ require 'spec_helper' describe 'build-essential::default' do - let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'freebsd', version: '10.3', - step_into: ['build_essential']).converge('build-essential::default') - end - - it 'installs the correct packages' do - expect(chef_run).to install_package('devel/gmake') - expect(chef_run).to install_package('devel/autoconf') - expect(chef_run).to install_package('devel/m4') - expect(chef_run).to install_package('devel/gettext') - end -end - -describe 'build-essential::default' do - let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'freebsd', version: '9.3', - step_into: ['build_essential']).converge('build-essential::default') - end + context 'FreeBSD 10+' do + let(:chef_run) do + ChefSpec::ServerRunner.new(platform: 'freebsd', version: '10.3', + step_into: ['build_essential']).converge('build-essential::default') + end - it 'installs the correct packages' do - expect(chef_run).to install_package('devel/gmake') - expect(chef_run).to install_package('devel/autoconf') - expect(chef_run).to install_package('devel/m4') - expect(chef_run).to install_package('devel/gettext') - expect(chef_run).to install_package('lang/gcc49') + it 'installs the correct packages' do + expect(chef_run).to install_package('devel/gmake') + expect(chef_run).to install_package('devel/autoconf') + expect(chef_run).to install_package('devel/m4') + expect(chef_run).to install_package('devel/gettext') + end end end diff --git a/cookbooks/build-essential/spec/recipes/mac_os_x_spec.rb b/cookbooks/build-essential/spec/recipes/mac_os_x_spec.rb index 39666eff..585796be 100644 --- a/cookbooks/build-essential/spec/recipes/mac_os_x_spec.rb +++ b/cookbooks/build-essential/spec/recipes/mac_os_x_spec.rb @@ -1,12 +1,14 @@ require 'spec_helper' describe 'build-essential::default' do - let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'mac_os_x', version: '10.11.1', - step_into: ['build_essential']).converge('build-essential::default') - end + context 'macOS' do + let(:chef_run) do + ChefSpec::ServerRunner.new(platform: 'mac_os_x', version: '10.12', + step_into: ['build_essential']).converge('build-essential::default') + end - it 'installs the xcode command line tools' do - expect(chef_run).to install_xcode_command_line_tools('install') + it 'installs the xcode command line tools' do + expect(chef_run).to install_xcode_command_line_tools('install') + end end end diff --git a/cookbooks/build-essential/spec/recipes/omnios_spec.rb b/cookbooks/build-essential/spec/recipes/omnios_spec.rb index d8692c9c..8f26e236 100644 --- a/cookbooks/build-essential/spec/recipes/omnios_spec.rb +++ b/cookbooks/build-essential/spec/recipes/omnios_spec.rb @@ -1,9 +1,9 @@ require 'spec_helper' describe 'build-essential::default' do - context 'omnios 151014' do + context 'omnios 151018' do let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'omnios', version: '151014', + ChefSpec::ServerRunner.new(platform: 'omnios', version: '151018', step_into: ['build_essential']).converge(described_recipe) end diff --git a/cookbooks/build-essential/spec/recipes/rhel_spec.rb b/cookbooks/build-essential/spec/recipes/rhel_spec.rb index c2fcd60c..283d291c 100644 --- a/cookbooks/build-essential/spec/recipes/rhel_spec.rb +++ b/cookbooks/build-essential/spec/recipes/rhel_spec.rb @@ -2,7 +2,7 @@ describe 'build-essential::default' do let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'centos', version: '6.7', + ChefSpec::ServerRunner.new(platform: 'centos', version: '6.9', step_into: ['build_essential']).converge(described_recipe) end diff --git a/cookbooks/build-essential/spec/recipes/smartos_spec.rb b/cookbooks/build-essential/spec/recipes/smartos_spec.rb index c02c5689..2a60a198 100644 --- a/cookbooks/build-essential/spec/recipes/smartos_spec.rb +++ b/cookbooks/build-essential/spec/recipes/smartos_spec.rb @@ -2,7 +2,7 @@ describe 'build-essential::default' do let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'smartos', version: 'joyent_20130111T180733Z', + ChefSpec::ServerRunner.new(platform: 'smartos', version: '5.11', step_into: ['build_essential']).converge('build-essential::default') end diff --git a/cookbooks/build-essential/spec/recipes/solaris2_spec.rb b/cookbooks/build-essential/spec/recipes/solaris2_spec.rb index a693ccd1..3c15380b 100644 --- a/cookbooks/build-essential/spec/recipes/solaris2_spec.rb +++ b/cookbooks/build-essential/spec/recipes/solaris2_spec.rb @@ -1,25 +1,28 @@ require 'spec_helper' describe 'build-essential::default' do - let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'solaris2', version: '5.11', - step_into: ['build_essential']).converge('build-essential::default') - end + context 'Solaris' do + let(:chef_run) do + ChefSpec::ServerRunner.new(platform: 'solaris2', version: '5.11', + step_into: ['build_essential']).converge('build-essential::default') + end - it 'installs the correct packages' do - expect(chef_run).to install_package('autoconf') - expect(chef_run).to install_package('automake') - expect(chef_run).to install_package('bison') - expect(chef_run).to install_package('gnu-coreutils') - expect(chef_run).to install_package('flex') - expect(chef_run).to install_package('gcc').with_version('4.8.2') - expect(chef_run).to install_package('gcc-3') - expect(chef_run).to install_package('gnu-grep') - expect(chef_run).to install_package('gnu-make') - expect(chef_run).to install_package('gnu-patch') - expect(chef_run).to install_package('gnu-tar') - expect(chef_run).to install_package('make') - expect(chef_run).to install_package('pkg-config') - expect(chef_run).to install_package('ucb') + it 'installs the correct packages' do + expect(chef_run).to install_package('autoconf') + expect(chef_run).to install_package('automake') + expect(chef_run).to install_package('bison') + expect(chef_run).to install_package('gnu-coreutils') + expect(chef_run).to install_package('flex') + expect(chef_run).to install_package('gcc').with_version('4.8.2') + expect(chef_run).to install_package('gcc-c').with_version('4.8.2') + expect(chef_run).to install_package('gcc-c++').with_version('4.8.2') + expect(chef_run).to install_package('gnu-grep') + expect(chef_run).to install_package('gnu-make') + expect(chef_run).to install_package('gnu-patch') + expect(chef_run).to install_package('gnu-tar') + expect(chef_run).to install_package('make') + expect(chef_run).to install_package('pkg-config') + expect(chef_run).to install_package('ucb') + end end end diff --git a/cookbooks/build-essential/spec/recipes/suse_spec.rb b/cookbooks/build-essential/spec/recipes/suse_spec.rb index 867c6b56..1cf7c361 100644 --- a/cookbooks/build-essential/spec/recipes/suse_spec.rb +++ b/cookbooks/build-essential/spec/recipes/suse_spec.rb @@ -1,23 +1,36 @@ require 'spec_helper' describe 'build-essential::default' do - let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'opensuse', version: '13.2', - step_into: ['build_essential']).converge('build-essential::default') - end + context 'SUSE' do + let(:chef_run) do + ChefSpec::ServerRunner.new(platform: 'opensuse', version: '42.3', + step_into: ['build_essential']).converge('build-essential::default') + end - it 'installs the correct packages' do - expect(chef_run).to install_package(['autoconf', 'bison', 'flex', 'gcc', 'gcc-c++', 'kernel-default-devel', 'make', 'm4']) - end + it 'installs the correct packages on modern SLES/openSUSE' do + expect(chef_run).to install_package(['autoconf', 'bison', 'flex', 'gcc', 'gcc-c++', 'kernel-default-devel', 'make', 'm4']) + end - context 'on suse < 12' do - let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'suse', version: '11.4', - step_into: ['build_essential']).converge(described_recipe) + context 'on suse < 12' do + let(:chef_run) do + ChefSpec::ServerRunner.new(platform: 'suse', version: '11.4', + step_into: ['build_essential']).converge(described_recipe) + end + + it 'installs more packages' do + expect(chef_run).to install_package(['gcc48', 'gcc48-c++']) + end end - it 'installs more packages' do - expect(chef_run).to install_package(['gcc48', 'gcc48-c++']) + context 'on suse >= 15' do + let(:chef_run) do + ChefSpec::ServerRunner.new(platform: 'suse', version: '15.0', + step_into: ['build_essential']).converge(described_recipe) + end + + it 'installs insserv-compat' do + expect(chef_run).to install_package(['insserv-compat']) + end end end end diff --git a/cookbooks/build-essential/spec/recipes/windows_spec.rb b/cookbooks/build-essential/spec/recipes/windows_spec.rb deleted file mode 100644 index c9981872..00000000 --- a/cookbooks/build-essential/spec/recipes/windows_spec.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'spec_helper' - -describe 'build-essential::default' do - let(:path) { 'C:\\msys2' } - let(:chef_run) do - ChefSpec::ServerRunner.new(platform: 'windows', version: '2012R2', - step_into: ['build_essential']) do |node| - node.normal['build-essential']['msys2']['path'] = path - end.converge(described_recipe) - end - - it 'creates the correct toolchain dir structure' do - expect(chef_run).to create_directory(path).with(recursive: true) - end - - it 'creates binstub for tar' do - expect(chef_run).to create_file("#{path}\\bin\\tar.bat") - end - - it 'creates binstub for patch' do - expect(chef_run).to create_file("#{path}\\bin\\patch.bat") - end -end diff --git a/cookbooks/build-essential/tasks/maintainers.rb b/cookbooks/build-essential/tasks/maintainers.rb deleted file mode 100644 index aa8e2540..00000000 --- a/cookbooks/build-essential/tasks/maintainers.rb +++ /dev/null @@ -1,76 +0,0 @@ -# -# Copyright:: 2015-2017, 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 'rake' - -SOURCE = File.join(File.dirname(__FILE__), '..', 'MAINTAINERS.toml') -TARGET = File.join(File.dirname(__FILE__), '..', 'MAINTAINERS.md') - -begin - require 'tomlrb' - task default: 'maintainers:generate' - - namespace :maintainers do - desc 'Generate MarkDown version of MAINTAINERS file' - task :generate do - @toml = Tomlrb.load_file SOURCE - out = "\n\n" - - out << preamble - out << project_lieutenant - out << all_maintainers - - File.open(TARGET, 'w') do |fn| - fn.write out - end - end - end - -rescue LoadError - STDERR.puts "\n*** TomlRb not available. Skipping the Maintainers Rake task\n\n" -end - -private - -def preamble - <<-EOL -# #{@toml['Preamble']['title']} -#{@toml['Preamble']['text']} -EOL -end - -def project_lieutenant - <<-EOL -# #{@toml['Org']['Components']['Core']['title']} -#{github_link(@toml['Org']['Components']['Core']['lieutenant'])} - -EOL -end - -def all_maintainers - text = "# Maintainers\n" - @toml['Org']['Components']['Core']['maintainers'].each do |m| - text << "#{github_link(m)}\n" - end - text -end - -def github_link(person) - name = @toml['people'][person]['name'] - github = @toml['people'][person]['github'] - "* [#{name}](https://github.com/#{github})" -end diff --git a/cookbooks/build-essential/test/cookbooks/test/README.md b/cookbooks/build-essential/test/cookbooks/test/README.md deleted file mode 100644 index 3c47ca36..00000000 --- a/cookbooks/build-essential/test/cookbooks/test/README.md +++ /dev/null @@ -1 +0,0 @@ -Test cookbook for build-essential diff --git a/cookbooks/build-essential/test/cookbooks/test/recipes/default.rb b/cookbooks/build-essential/test/cookbooks/test/recipes/default.rb index ab4cce82..52da301b 100644 --- a/cookbooks/build-essential/test/cookbooks/test/recipes/default.rb +++ b/cookbooks/build-essential/test/cookbooks/test/recipes/default.rb @@ -1,3 +1,3 @@ -apt_update 'update' if platform_family?('debian') +apt_update 'update' include_recipe 'build-essential::default' diff --git a/cookbooks/compat_resource b/cookbooks/compat_resource new file mode 160000 index 00000000..e36200f6 --- /dev/null +++ b/cookbooks/compat_resource @@ -0,0 +1 @@ +Subproject commit e36200f6b804915b68a4ce74c8b7a293c041d9fe diff --git a/cookbooks/compat_resource/CHANGELOG.md b/cookbooks/compat_resource/CHANGELOG.md deleted file mode 100644 index 79081964..00000000 --- a/cookbooks/compat_resource/CHANGELOG.md +++ /dev/null @@ -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 diff --git a/cookbooks/compat_resource/CONTRIBUTING.md b/cookbooks/compat_resource/CONTRIBUTING.md deleted file mode 100644 index ef2f2b80..00000000 --- a/cookbooks/compat_resource/CONTRIBUTING.md +++ /dev/null @@ -1,2 +0,0 @@ -Please refer to -https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/CONTRIBUTING.MD diff --git a/cookbooks/compat_resource/CONVERTING.md b/cookbooks/compat_resource/CONVERTING.md deleted file mode 100644 index ab820e9f..00000000 --- a/cookbooks/compat_resource/CONVERTING.md +++ /dev/null @@ -1,38 +0,0 @@ -# Converting cookbooks from the old resource model to the new - -## Boilerplate - -1. Depend on compat_resource - - - Descend resources from ChefCompat::Resource - - Set resource_name in the class instead of the constructor - -2. Convert Attributes to Properties - - - Rename attribute -> property - - Move set_or_return -> property - - Take kind_of/equal_to/regexes and make them types - - Use true/false/nil instead of TrueClass/FalseClass/NilClass - - Remove default: nil (it's the default) - -3. Convert Top-Level Providers to Actions - - - Create any resources that don't already exist (for example in multi-provider cases) and descend from the base resource - - Remove allowed_actions / @actions - - @action -> default_action - - Move `provides` and `action :x` to the resource - - Remove use_inline_resources and def whyrun_safe? - - Move other methods to `action_class.class_eval do` - -Now you have everything in a resource, are using properties, and have gotten rid of a bunch of boilerplate. Of course, this is just getting it _moved_. - -## Advanced Concepts - -1. Resource Inheritance -2. Resources That Are Different On Each OS? -3. Coercion: Handling User Input -4. Lazy Defaults -5. Using Load Current Resource -6. Using Converge If Changed -7. Defaults Are For Creation -8. Shared types: using a type multiple places diff --git a/cookbooks/compat_resource/Gemfile b/cookbooks/compat_resource/Gemfile deleted file mode 100644 index a0b2736d..00000000 --- a/cookbooks/compat_resource/Gemfile +++ /dev/null @@ -1,11 +0,0 @@ -source 'https://rubygems.org' -gem 'stove' -gem 'rack' # 2.0 requires Ruby 2.2+ -gem 'rspec' -gem 'rake' -gem 'tomlrb' -if ENV['GEMFILE_MOD'] - instance_eval(ENV['GEMFILE_MOD']) -else - gem 'chef' -end diff --git a/cookbooks/compat_resource/LICENSE b/cookbooks/compat_resource/LICENSE deleted file mode 100644 index 8f71f43f..00000000 --- a/cookbooks/compat_resource/LICENSE +++ /dev/null @@ -1,202 +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 {yyyy} {name of copyright owner} - - 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. - diff --git a/cookbooks/compat_resource/MAINTAINERS.md b/cookbooks/compat_resource/MAINTAINERS.md deleted file mode 100644 index 5ae0806c..00000000 --- a/cookbooks/compat_resource/MAINTAINERS.md +++ /dev/null @@ -1,16 +0,0 @@ - - -# 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) diff --git a/cookbooks/compat_resource/MAINTAINERS.toml b/cookbooks/compat_resource/MAINTAINERS.toml deleted file mode 100644 index d5811ad4..00000000 --- a/cookbooks/compat_resource/MAINTAINERS.toml +++ /dev/null @@ -1,43 +0,0 @@ -# -# This file is structured to be consumed by both humans and computers. -# It is a TOML document containing Markdown -# -[Preamble] - title = "Maintainers" - text = """ - -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. -""" - -[Org] - [Org.Components] - [Org.Components.Core] - title = "Project Maintainer" - - lieutenant = 'lamont-granquist' - - maintainers = [ - 'sigje', - 'tas50', - 'thommay', - 'lamont-granquist' - ] - -[people] - [people.sigje] - name = "Jennifer Davis" - github = "sigje" - - [people.tas50] - name = "Tim Smith" - github = "tas50" - - [people.thommay] - name = "Thom May" - github = "thommay" - - [people.lamont-granquist] - name = "Lamont Granquist" - github = "lamont-granquist" diff --git a/cookbooks/compat_resource/README.md b/cookbooks/compat_resource/README.md deleted file mode 100644 index f5c17e5a..00000000 --- a/cookbooks/compat_resource/README.md +++ /dev/null @@ -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: -- Slides: - -## 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. -``` diff --git a/cookbooks/compat_resource/Rakefile b/cookbooks/compat_resource/Rakefile deleted file mode 100644 index e92bee9e..00000000 --- a/cookbooks/compat_resource/Rakefile +++ /dev/null @@ -1,286 +0,0 @@ -require 'rspec/core/rake_task' -require 'stove/rake_task' -require_relative 'tasks/maintainers' -require 'fileutils' - -RSpec::Core::RakeTask.new(:spec) do |t| - t.pattern = FileList['spec/**/*_spec.rb'] -end - -Stove::RakeTask.new - -task default: :spec - -# -# "rake update" updates the copied_from_chef files so we can grab bugfixes or new features -# -GLOBAL_MONKEYPATCHES = %w( - chef/runner.rb - chef/run_context.rb - chef/recipe.rb -) - -CHEF_FILES = %w( - chef/constants.rb - chef/delayed_evaluator.rb - chef/dsl/core.rb - chef/dsl/declare_resource.rb - chef/dsl/platform_introspection.rb - chef/dsl/recipe.rb - chef/dsl/universal.rb - chef/mixin/lazy_module_include.rb - chef/mixin/notifying_block.rb - chef/mixin/params_validate.rb - chef/mixin/powershell_out.rb - chef/mixin/properties.rb - chef/property.rb - chef/provider.rb - chef/provider/support/yum_repo.erb - chef/provider/apt_update.rb - chef/provider/apt_repository.rb - chef/provider/noop.rb - chef/provider/systemd_unit.rb - chef/provider/yum_repository.rb - chef/resource.rb - chef/resource/action_class.rb - chef/resource/apt_update.rb - chef/resource/apt_repository.rb - chef/resource/systemd_unit.rb - chef/resource/yum_repository.rb - chef/resource_builder.rb -) -KEEP_FUNCTIONS = { - 'chef/resource.rb' => %w( - initialize - - name - - resource_name self.use_automatic_resource_name - - identity state state_for_resource_reporter property_is_set reset_property - resource_initializing resource_initializing= to_hash - self.properties self.state_properties self.state_attr - self.identity_properties self.identity_property self.identity_attrs - self.property self.property_type - self.lazy - - action allowed_actions self.allowed_actions self.default_action - self.action self.declare_action_class self.action_class - - load_current_value current_value_does_not_exist - self.load_current_value - ), - 'chef/provider.rb' => %w( - initialize - converge_if_changed - compile_and_converge_action - action - self.use_inline_resources - self.include_resource_dsl - self.include_resource_dsl_module - ), - 'chef/dsl/recipe.rb' => %w(), -} -KEEP_INCLUDES = { - 'chef/resource.rb' => %w(Chef::Mixin::ParamsValidate Chef::Mixin::Properties), - 'chef/provider.rb' => %w(Chef::DSL::Core), - 'chef/dsl/recipe.rb' => %w(Chef::DSL::Core Chef::DSL::Recipe Chef::Mixin::LazyModuleInclude), -} -KEEP_CLASSES = { - 'chef/provider.rb' => %w(Chef::Provider Chef::Provider::InlineResources Chef::Provider::InlineResources::ClassMethods) -} -SKIP_LINES = { - 'chef/dsl/recipe.rb' => [ /include Chef::Mixin::PowershellOut/ ] -} -PROCESS_LINES = { -} -# See chef_compat/resource for def. of resource_name and provider -# See chef_compat/monkeypatches/chef/resource for def. of current_value - -desc "Pull new files from the chef client this is bundled with and update this cookbook" -task :update do - # Copy files from chef to chef_compat/chef, with a few changes - target_path = File.expand_path("../files/lib/chef_compat/copied_from_chef", __FILE__) - chef_gem_path = Bundler.environment.specs['chef'].first.full_gem_path - CHEF_FILES.each do |file| - if file =~ /\.rb$/ - output = StringIO.new - output.puts "#" - output.puts "# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE" - output.puts "#" - output.puts "# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!" - output.puts "#" - output.puts "# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE" - output.puts "#" - output.puts "" - # First lets try to load the original file if it exists - output.puts "begin" - output.puts " require '#{file.sub(/.rb$/,"")}'" - output.puts "rescue LoadError; end" - output.puts "" - # Wrap the whole thing in a ChefCompat module - output.puts "require 'chef_compat/copied_from_chef'" - output.puts "class Chef" - output.puts "module ::ChefCompat" - output.puts "module CopiedFromChef" - - # Bring over the Chef file - chef_contents = IO.read(File.join(chef_gem_path, 'lib', "#{file}")) - skip_until = nil - keep_until = nil - in_class = [] - chef_contents.lines.each do |line| - if keep_until - keep_until = nil if keep_until === line - else - - if skip_until - skip_until = nil if skip_until === line - next - end - - # If this file only keeps certain functions, detect which function we are - # in and only keep those. Also strip comments outside functions - - case line - - # Skip modules and classes that aren't part of our list - when /\A(\s*)def\s+([A-Za-z0-9_.]+)/ - if KEEP_FUNCTIONS[file] && !KEEP_FUNCTIONS[file].include?($2) - skip_until = /\A#{$1}end\s*$/ - next - else - function = $2 - # Keep everything inside a function no matter what it is - keep_until = /\A#{$1}end\s*$/ - end - - # Skip comments and whitespace if we're narrowing the file (otherwise it - # looks super weird) - when /\A\s*#/, /\A\s*$/ - next if KEEP_CLASSES[file] || KEEP_FUNCTIONS[file] - - # Skip aliases/attrs/properties that we're not keeping - when /\A\s*(attr_reader|attr_writer|attr_accessor|property|alias)\s*:(\w+)/ - next if KEEP_FUNCTIONS[file] && !KEEP_FUNCTIONS[file].include?($2) - - # Skip includes and extends that we're not keeping - when /\A\s*(include|extend)\s*([A-Za-z0-9_:]+)/ - next if KEEP_INCLUDES[file] && !KEEP_INCLUDES[file].include?($2) - - end - - next if SKIP_LINES[file] && SKIP_LINES[file].any? { |skip| skip === line } - end - - # If we are at the end of a class, pop in_class - if in_class[-1] && in_class[-1][:until].match(line) - class_name = in_class.pop[:name] - # Don't bother printing classes/modules that we're not going to print anything under - next if KEEP_CLASSES[file] && !KEEP_CLASSES[file].any? { |c| c.start_with?(class_name) } - - # Detect class open - elsif line =~ /\A(\s*)(class|module)(\s+)([A-Za-z0-9_:]+)(\s*<\s*([A-Za-z0-9_:]+))?.*$/ - indent, type, space, class_name, _, superclass_name = $1, $2, $3, $4, $5, $6 - full_class_name = in_class[-1] ? "#{in_class[-1][:name]}::#{class_name}" : class_name - in_class << { name: full_class_name, until: /\A#{indent}end\s*$/ } - superclass_name ||= "Object" - - # Don't print the class open unless it contains stuff we'll keep - next if KEEP_CLASSES[file] && !KEEP_CLASSES[file].any? { |c| c.start_with?(full_class_name) } - - # Fix the class to extend from its parent - original_class = "::#{full_class_name}" - if type == 'class' - line = "#{indent}#{type}#{space}#{class_name} < (defined?(#{original_class}) ? #{original_class} : #{superclass_name})" - else - # Modules have a harder time of it because of self methods - line += "#{indent} CopiedFromChef.extend_chef_module(#{original_class}, self) if defined?(#{original_class})" - end - - # If we're not in a class we care about, don't print stuff - elsif KEEP_CLASSES[file] && in_class[-1] && !KEEP_CLASSES[file].any? { |c| c == in_class[-1][:name] } - next - end - - # Modify requires to overridden files to bring in the local version - if line =~ /\A(\s*require\s*['"])([^'"]+)(['"].*)/ - if CHEF_FILES.include?("#{$2}.rb") - line = "#{$1}chef_compat/copied_from_chef/#{$2}#{$3}" - else - next - end - end - - line = PROCESS_LINES[file].call(line) if PROCESS_LINES[file] - - output.puts line - - # If this was the header for an initialize function, write out "super" - if function == 'initialize' - output.puts "super if defined?(::#{in_class[-1][:name]})" - end - end - # Close the ChefCompat module declaration from the top - output.puts "end" - output.puts "end" - output.puts "end" - - # Write out the file in chef_compat - target_file = File.join(target_path, "#{file}") - if !File.exist?(target_file) || IO.read(target_file) != output.string - puts "Writing #{target_file} ..." - FileUtils.mkdir_p(File.dirname(target_file)) - File.open(target_file, "w") { |f| f.write(output.string) } - end - else # non-rb file so no mangling - target_file = File.join(target_path, "#{file}") - source_file = File.join(chef_gem_path, 'lib', "#{file}") - if !File.exist?(target_file) || IO.read(target_file) != IO.read(source_file) - puts "Writing #{target_file} ..." - FileUtils.mkdir_p(File.dirname(target_file)) - FileUtils.cp File.join(chef_gem_path, 'lib', "#{file}"), target_file - end - end - end - - target_path = File.expand_path("../files/lib/chef_compat/monkeypatches", __FILE__) - - chef_gemspec = Gem::Specification.find_by_name("chef") - - GLOBAL_MONKEYPATCHES.each do |file| - output = StringIO.new - output.puts "#" - output.puts "# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE" - output.puts "#" - output.puts "# THIS IS A FILE AUTOGENERATED BY 'rake update' DO NOT EDIT!!!!" - output.puts "#" - output.puts "# NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE NOTICE" - output.puts "#" - output.puts "" - output.puts "if Gem::Requirement.new('< #{chef_gemspec.version}').satisfied_by?(Gem::Version.new(Chef::VERSION))" - chef_contents = IO.read(File.join(chef_gem_path, 'lib', "#{file}")) - chef_contents.lines.each do |line| - # we're probably going to want to mangle this stuff at some point i suspect - output.puts line - end - output.puts "end" - - # Write out the file in chef_compat - target_file = File.join(target_path, "#{file}") - if !File.exist?(target_file) || IO.read(target_file) != output.string - puts "Writing #{target_file} ..." - FileUtils.mkdir_p(File.dirname(target_file)) - File.open(target_file, "w") { |f| f.write(output.string) } - end - end - - # spit out the version somewhere we can easily slurp it up from - File.open(File.expand_path("files/lib/chef_upstream_version.rb", File.dirname(__FILE__)), "w") do |f| - f.write <<-EOF - module ChefCompat - CHEF_UPSTREAM_VERSION="#{chef_gemspec.version}" - end - EOF - end -end diff --git a/cookbooks/compat_resource/TESTING.md b/cookbooks/compat_resource/TESTING.md deleted file mode 100644 index ca524abe..00000000 --- a/cookbooks/compat_resource/TESTING.md +++ /dev/null @@ -1,2 +0,0 @@ -Please refer to -https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/TESTING.MD diff --git a/cookbooks/compat_resource/chefignore b/cookbooks/compat_resource/chefignore deleted file mode 100644 index a9769175..00000000 --- a/cookbooks/compat_resource/chefignore +++ /dev/null @@ -1,102 +0,0 @@ -# Put files/directories that should be ignored in this file when uploading -# to a chef-server or supermarket. -# Lines that start with '# ' are comments. - -# OS generated files # -###################### -.DS_Store -Icon? -nohup.out -ehthumbs.db -Thumbs.db - -# SASS # -######## -.sass-cache - -# EDITORS # -########### -\#* -.#* -*~ -*.sw[a-z] -*.bak -REVISION -TAGS* -tmtags -*_flymake.* -*_flymake -*.tmproj -.project -.settings -mkmf.log - -## COMPILED ## -############## -a.out -*.o -*.pyc -*.so -*.com -*.class -*.dll -*.exe -*/rdoc/ - -# Testing # -########### -.watchr -.rspec -spec/* -spec/fixtures/* -test/* -features/* -examples/* -Guardfile -Procfile -.kitchen* -.rubocop.yml -spec/* -Rakefile -.travis.yml -.foodcritic -.codeclimate.yml - -# SCM # -####### -.git -*/.git -.gitignore -.gitmodules -.gitconfig -.gitattributes -.svn -*/.bzr/* -*/.hg/* -*/.svn/* - -# Berkshelf # -############# -Berksfile -Berksfile.lock -cookbooks/* -tmp - -# Cookbooks # -############# -CONTRIBUTING* -CHANGELOG* -TESTING* -MAINTAINERS.toml - -# Strainer # -############ -Colanderfile -Strainerfile -.colander -.strainer - -# Vagrant # -########### -.vagrant -Vagrantfile diff --git a/cookbooks/compat_resource/ci/chefspec/Gemfile b/cookbooks/compat_resource/ci/chefspec/Gemfile deleted file mode 100644 index ef22a725..00000000 --- a/cookbooks/compat_resource/ci/chefspec/Gemfile +++ /dev/null @@ -1,5 +0,0 @@ -source 'https://rubygems.org' - -gem "chef" -gem "chefspec" -gem "berkshelf" diff --git a/cookbooks/compat_resource/ci/chefspec/metadata.rb b/cookbooks/compat_resource/ci/chefspec/metadata.rb deleted file mode 100644 index 4445f06d..00000000 --- a/cookbooks/compat_resource/ci/chefspec/metadata.rb +++ /dev/null @@ -1,9 +0,0 @@ -name 'test' -maintainer 'The Authors' -maintainer_email 'you@example.com' -license 'all_rights' -description 'Installs/Configures sk_test' -long_description 'Installs/Configures sk_test' -version '0.0.1' - -depends "compat_resource" diff --git a/cookbooks/compat_resource/ci/chefspec/recipes/default.rb b/cookbooks/compat_resource/ci/chefspec/recipes/default.rb deleted file mode 100644 index bf6ad331..00000000 --- a/cookbooks/compat_resource/ci/chefspec/recipes/default.rb +++ /dev/null @@ -1,2 +0,0 @@ - -file "/tmp/foo.xyz" diff --git a/cookbooks/compat_resource/ci/chefspec/spec/default_spec.rb b/cookbooks/compat_resource/ci/chefspec/spec/default_spec.rb deleted file mode 100644 index b56c7f2e..00000000 --- a/cookbooks/compat_resource/ci/chefspec/spec/default_spec.rb +++ /dev/null @@ -1,24 +0,0 @@ -# -# Cookbook:: sk_test -# Spec:: default -# -# Copyright:: 2016, The Authors, All Rights Reserved. - -require 'spec_helper' - -describe 'test::default' do - context 'basic flame tests' do - let(:chef_run) do - runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') - runner.converge(described_recipe) - end - - it 'converges successfully' do - expect { chef_run }.to_not raise_error - end - - it 'has a resource in the run' do - expect(chef_run).to create_file('/tmp/foo.xyz') - end - end -end diff --git a/cookbooks/compat_resource/ci/chefspec/spec/spec_helper.rb b/cookbooks/compat_resource/ci/chefspec/spec/spec_helper.rb deleted file mode 100644 index 1dd5126b..00000000 --- a/cookbooks/compat_resource/ci/chefspec/spec/spec_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'chefspec' -require 'chefspec/berkshelf' diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef.rb deleted file mode 100644 index 219b05b4..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef.rb +++ /dev/null @@ -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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/constants.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/constants.rb deleted file mode 100644 index 4acd742b..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/constants.rb +++ /dev/null @@ -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 -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/delayed_evaluator.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/delayed_evaluator.rb deleted file mode 100644 index 4fb687e1..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/delayed_evaluator.rb +++ /dev/null @@ -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 -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/core.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/core.rb deleted file mode 100644 index 8e30d304..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/core.rb +++ /dev/null @@ -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 () -# 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. -# - -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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/declare_resource.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/declare_resource.rb deleted file mode 100644 index 45e69dc3..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/declare_resource.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/platform_introspection.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/platform_introspection.rb deleted file mode 100644 index 78860004..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/platform_introspection.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/recipe.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/recipe.rb deleted file mode 100644 index f896ec7c..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/recipe.rb +++ /dev/null @@ -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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/universal.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/universal.rb deleted file mode 100644 index 7f529f1c..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/dsl/universal.rb +++ /dev/null @@ -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 () -# 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. -# - -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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/lazy_module_include.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/lazy_module_include.rb deleted file mode 100644 index a6b52441..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/lazy_module_include.rb +++ /dev/null @@ -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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/notifying_block.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/notifying_block.rb deleted file mode 100644 index 0b90e276..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/notifying_block.rb +++ /dev/null @@ -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 -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/params_validate.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/params_validate.rb deleted file mode 100644 index 0a16147d..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/params_validate.rb +++ /dev/null @@ -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 () -# 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] 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] :regex An object, or - # list of objects, that must match the value with `regex.match(value)`. - # (See #_pv_regex) - # @option opts [Class,Array] :kind_of A class, or - # list of classes, that the value must be an instance of. (See - # #_pv_kind_of.) - # @option opts [Hash] :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] :respond_to A method - # name, or list of method names, the value must respond to. (See - # #_pv_respond_to.) - # @option opts [Symbol,Array] :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.?` All responses must be false for the value to be - # valid. - # Values which do not respond to ? 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 "`. - # - # @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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/powershell_out.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/powershell_out.rb deleted file mode 100644 index b6b56f9a..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/powershell_out.rb +++ /dev/null @@ -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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/properties.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/properties.rb deleted file mode 100644 index bdf9f7e4..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/mixin/properties.rb +++ /dev/null @@ -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] 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] The type(s) of this property. - # If present, this is prepended to the `is` validation option. - # @param options [Hash] 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] :regex An object, or - # list of objects, that must match the value with `regex.match(value)`. - # @option options [Class,Array] :kind_of A class, or - # list of classes, that the value must be an instance of. - # @option options [Hash] :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] :respond_to A method - # name, or list of method names, the value must respond to. - # @option options [Symbol,Array] :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] 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] A list of property names to set as desired - # state. - # - # @return [Array] 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] A list of property names to set as the identity. - # - # @return [Array] 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/property.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/property.rb deleted file mode 100644 index 33995968..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/property.rb +++ /dev/null @@ -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 -# 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] 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] 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 `@`. - # `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 || ""}#{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 `@` - # - # @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] - # - 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] 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider.rb deleted file mode 100644 index 7ccf87bf..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider.rb +++ /dev/null @@ -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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/apt_repository.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/apt_repository.rb deleted file mode 100644 index ccc07c43..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/apt_repository.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/apt_update.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/apt_update.rb deleted file mode 100644 index 677cb577..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/apt_update.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/noop.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/noop.rb deleted file mode 100644 index 87c34e66..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/noop.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/support/yum_repo.erb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/support/yum_repo.erb deleted file mode 100644 index 6f132557..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/support/yum_repo.erb +++ /dev/null @@ -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 -%> diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/systemd_unit.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/systemd_unit.rb deleted file mode 100644 index 1024cb82..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/systemd_unit.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/yum_repository.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/yum_repository.rb deleted file mode 100644 index 51453d2c..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/provider/yum_repository.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource.rb deleted file mode 100644 index e5c9a146..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource.rb +++ /dev/null @@ -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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/action_class.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/action_class.rb deleted file mode 100644 index 20ff8e5c..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/action_class.rb +++ /dev/null @@ -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 ("} action #{action ? action.inspect : ""}" - 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/apt_repository.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/apt_repository.rb deleted file mode 100644 index bedfd3ec..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/apt_repository.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/apt_update.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/apt_update.rb deleted file mode 100644 index 9acd9ae9..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/apt_update.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/systemd_unit.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/systemd_unit.rb deleted file mode 100644 index 5f9f458c..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/systemd_unit.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/yum_repository.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/yum_repository.rb deleted file mode 100644 index 97cf23a5..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource/yum_repository.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource_builder.rb b/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource_builder.rb deleted file mode 100644 index 688e856e..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/copied_from_chef/chef/resource_builder.rb +++ /dev/null @@ -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 () -# 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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/mixin/properties.rb b/cookbooks/compat_resource/files/lib/chef_compat/mixin/properties.rb deleted file mode 100644 index a3920d1a..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/mixin/properties.rb +++ /dev/null @@ -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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches.rb deleted file mode 100644 index 9ac83e84..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches.rb +++ /dev/null @@ -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 diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef.rb deleted file mode 100644 index 9669f6af..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef.rb +++ /dev/null @@ -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<= 12.5 && Chef::VERSION.to_f <= 12.8 - require 'chef/mixin/params_validate' - class Chef - module Mixin - module ParamsValidate - class SetOrReturnProperty < Chef::Property - # 12.9 introduced a new optional parameter to `get()` to avoid a nil-set warning. - # When their method gets called with 2 args, we need to ignore and call with 1. - alias_method :_original_get2, :get - def get(resource, *args) - _original_get2(resource) - end - end - end - end - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/node.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/node.rb deleted file mode 100644 index 93379b07..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/node.rb +++ /dev/null @@ -1,9 +0,0 @@ -class Chef - class Node - unless method_defined?(:set_cookbook_attribute) - def set_cookbook_attribute - # this implementation deliberately left blank - we don't need to do anything we just need to not fail - end - end - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/property.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/property.rb deleted file mode 100644 index 2308d329..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/property.rb +++ /dev/null @@ -1,15 +0,0 @@ -# 12.9 introduced a new optional parameter to `get()` to avoid a nil-set warning. -# We need to mimick it here. -if Chef::VERSION.to_f >= 12.5 && Chef::VERSION.to_f <= 12.8 - require 'chef/property' - class Chef - class Property - # 12.9 introduced a new optional parameter to `get()` to avoid a nil-set warning. - # When their method gets called with 2 args, we need to ignore and call with 1. - alias_method :_original_get, :get - def get(resource, *args) - _original_get(resource) - end - end - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/provider.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/provider.rb deleted file mode 100644 index 591cedb3..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/provider.rb +++ /dev/null @@ -1,65 +0,0 @@ -require 'chef/provider' -require 'chef/provider/lwrp_base' - -class Chef::Provider - if !defined?(InlineResources) - InlineResources = Chef::Provider::LWRPBase::InlineResources - end - module InlineResources - require 'chef/dsl/recipe' - require 'chef/dsl/platform_introspection' - require 'chef/dsl/data_query' - require 'chef/dsl/include_recipe' - include Chef::DSL::Recipe - include Chef::DSL::PlatformIntrospection - include Chef::DSL::DataQuery - include Chef::DSL::IncludeRecipe - - unless Chef::Provider::InlineResources::ClassMethods.instance_method(:action).source_location[0] =~ /chefspec/ - # Don't override action if chefspec is doing its thing - module ::ChefCompat - module Monkeypatches - module InlineResources - module ClassMethods - def action(name, &block) - super(name) { send("compile_action_#{name}") } - # We put the action in its own method so that super() works. - define_method("compile_action_#{name}", &block) - end - end - end - end - end - module ClassMethods - prepend ChefCompat::Monkeypatches::InlineResources::ClassMethods - end - end - end -end - - -class Chef - class Provider - class LWRPBase < Provider - if defined?(InlineResources) - module InlineResources - # since we upgrade the Chef::Runner and Chef::RunContext globally to >= 12.14 style classes, we need to also - # fix the use_inline_resources LWRPBase wrapper that creates a sub-resource collection with the ugpraded code - # from the Chef::Provider subclasses that do similar things in post-12.5 chef. - def recipe_eval_with_update_check(&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 - end - end - end - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/recipe.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/recipe.rb deleted file mode 100644 index 7c4c8bef..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/recipe.rb +++ /dev/null @@ -1,118 +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 -# - -if Gem::Requirement.new('< 12.16.42').satisfied_by?(Gem::Version.new(Chef::VERSION)) -#-- -# Author:: Adam Jacob () -# 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. -# - -require "chef/dsl/recipe" -require "chef/mixin/from_file" -require "chef/mixin/deprecation" - -class Chef - # == Chef::Recipe - # A Recipe object is the context in which Chef recipes are evaluated. - class Recipe - attr_accessor :cookbook_name, :recipe_name, :recipe, :params, :run_context - - include Chef::DSL::Recipe - - include Chef::Mixin::FromFile - include Chef::Mixin::Deprecation - - # Parses a potentially fully-qualified recipe name into its - # cookbook name and recipe short name. - # - # For example: - # "aws::elastic_ip" returns [:aws, "elastic_ip"] - # "aws" returns [:aws, "default"] - # "::elastic_ip" returns [ current_cookbook, "elastic_ip" ] - #-- - # TODO: Duplicates functionality of RunListItem - def self.parse_recipe_name(recipe_name, current_cookbook: nil) - case recipe_name - when /(.+?)::(.+)/ - [ $1.to_sym, $2 ] - when /^::(.+)/ - raise "current_cookbook is nil, cannot resolve #{recipe_name}" if current_cookbook.nil? - [ current_cookbook.to_sym, $1 ] - else - [ recipe_name.to_sym, "default" ] - end - end - - def initialize(cookbook_name, recipe_name, run_context) - @cookbook_name = cookbook_name - @recipe_name = recipe_name - @run_context = run_context - # TODO: 5/19/2010 cw/tim: determine whether this can be removed - @params = Hash.new - end - - # Used in DSL mixins - def node - run_context.node - end - - # Used by the DSL to look up resources when executing in the context of a - # recipe. - def resources(*args) - run_context.resource_collection.find(*args) - end - - # This was moved to Chef::Node#tag, redirecting here for compatibility - def tag(*tags) - run_context.node.tag(*tags) - end - - # Returns true if the node is tagged with *all* of the supplied +tags+. - # - # === Parameters - # tags:: A list of tags - # - # === Returns - # true:: If all the parameters are present - # false:: If any of the parameters are missing - def tagged?(*tags) - tags.each do |tag| - return false unless run_context.node.tags.include?(tag) - end - true - end - - # Removes the list of tags from the node. - # - # === Parameters - # tags:: A list of tags - # - # === Returns - # tags:: The current list of run_context.node.tags - def untag(*tags) - tags.each do |tag| - run_context.node.tags.delete(tag) - end - end - end -end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/recipe_hook.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/recipe_hook.rb deleted file mode 100644 index 24aa20f8..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/recipe_hook.rb +++ /dev/null @@ -1,20 +0,0 @@ -require 'chef/recipe' -require 'chef_compat/recipe' - -class Chef::Recipe - # If the cookbook depends on compat_resource, create a ChefCompat::Recipe object - # instead of Chef::Recipe, for the extra goodies. - def self.new(cookbook_name, recipe_name, run_context) - if run_context && - cookbook_name && - recipe_name && - run_context.cookbook_collection && - run_context.cookbook_collection[cookbook_name] && - run_context.cookbook_collection[cookbook_name].metadata.dependencies.has_key?('compat_resource') && - self != ::ChefCompat::Recipe - ::ChefCompat::Recipe.new(cookbook_name, recipe_name, run_context) - else - super - end - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource.rb deleted file mode 100644 index d61b60ba..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource.rb +++ /dev/null @@ -1,156 +0,0 @@ -# this is NOT an AUTOGENERATED file - -require 'chef/resource' - -class Chef - class Resource - - class UnresolvedSubscribes < self - # The full key ise given as the name in {Resource#subscribes} - alias_method :to_s, :name - alias_method :declared_key, :name - end - - # - # Force a delayed notification into this resource's run_context. - # - # This should most likely be paired with action :nothing - # - # @param arg [Array[Symbol], Symbol] A list of actions (e.g. `:create`) - # - def delayed_action(arg) - arg = Array(arg).map(&:to_sym) - arg.map do |action| - validate( - { action: action }, - { action: { kind_of: Symbol, equal_to: allowed_actions } } - ) - # the resource effectively sends a delayed notification to itself - run_context.add_delayed_action(Notification.new(self, action, self)) - end - end - - def subscribes(action, resources, timing = :delayed) - resources = [resources].flatten - resources.each do |resource| - if resource.is_a?(String) - resource = UnresolvedSubscribes.new(resource, run_context) - end - if resource.run_context.nil? - resource.run_context = run_context - end - resource.notifies(action, self, timing) - end - true - end - - def notifies(action, resource_spec, timing = :delayed) - # when using old-style resources(:template => "/foo.txt") style, you - # could end up with multiple resources. - validate_resource_spec!(resource_spec) - - resources = [ resource_spec ].flatten - resources.each do |resource| - - case timing.to_s - when "delayed" - notifies_delayed(action, resource) - when "immediate", "immediately" - notifies_immediately(action, resource) - when "before" - notifies_before(action, resource) - else - raise ArgumentError, "invalid timing: #{timing} for notifies(#{action}, #{resources.inspect}, #{timing}) resource #{self} "\ - "Valid timings are: :delayed, :immediate, :immediately, :before" - end - end - - true - end - - # - # Iterates over all immediate and delayed notifications, calling - # resolve_resource_reference on each in turn, causing them to - # resolve lazy/forward references. - def resolve_notification_references - run_context.before_notifications(self).each { |n| - n.resolve_resource_reference(run_context.resource_collection) - } - run_context.immediate_notifications(self).each { |n| - n.resolve_resource_reference(run_context.resource_collection) - } - run_context.delayed_notifications(self).each {|n| - n.resolve_resource_reference(run_context.resource_collection) - } - end - - # Helper for #notifies - def notifies_before(action, resource_spec) - run_context.notifies_before(Notification.new(resource_spec, action, self)) - end - - # Helper for #notifies - def notifies_immediately(action, resource_spec) - run_context.notifies_immediately(Notification.new(resource_spec, action, self)) - end - - # Helper for #notifies - def notifies_delayed(action, resource_spec) - run_context.notifies_delayed(Notification.new(resource_spec, action, self)) - end - - # - # Get the current actual value of this resource. - # - # This does not cache--a new value will be returned each time. - # - # @return A new copy of the resource, with values filled in from the actual - # current value. - # - def current_value - provider = provider_for_action(Array(action).first) - if provider.whyrun_mode? && !provider.whyrun_supported? - raise "Cannot retrieve #{self.class.current_resource} in why-run mode: #{provider} does not support why-run" - end - provider.load_current_resource - provider.current_resource - end - - # These methods are necessary for new resources to initialize old ones properly - attr_reader :resource_initializing - def resource_initializing=(value) - if value - @resource_initializing = value - else - remove_instance_variable(:@resource_initializing) - end - end - - if !respond_to?(:resource_name) - def self.resource_name(name=Chef::NOT_PASSED) - # Setter - if name != Chef::NOT_PASSED - # remove_canonical_dsl - - # Set the resource_name and call provides - if name - name = name.to_sym - # If our class is not already providing this name, provide it. - # Commented out: use of resource_name and provides will need to be - # mutually exclusive in this world, generally. - # if !Chef::ResourceResolver.includes_handler?(name, self) - provides name#, canonical: true - # end - @resource_name = name - else - @resource_name = nil - end - end - @resource_name - end - def self.resource_name=(name) - resource_name(name) - end - end - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource/lwrp_base.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource/lwrp_base.rb deleted file mode 100644 index 5f098fda..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource/lwrp_base.rb +++ /dev/null @@ -1,60 +0,0 @@ -require 'chef_compat/resource/lwrp_base' -require 'chef/resource/lwrp_base' - -module ChefCompat - module Monkeypatches - # - # NOTE: LOTS OF METAPROGRAMMING HERE. NOT FOR FAINT OF HEART. - # - - # Add an empty module to Class so we can temporarily override it in build_from_file - module Class - end - class<<::Class - prepend(ChefCompat::Monkeypatches::Class) - end - - module Chef - module Resource - module LWRPBase - def build_from_file(cookbook_name, filename, run_context) - # If the cookbook this LWRP is from depends on compat_resource, fix its LWRPs up real good - if run_context.cookbook_collection[cookbook_name].metadata.dependencies.has_key?('compat_resource') - # All cookbooks do Class.new(Chef::Resource::LWRPBase). Change Class.new - # temporarily to translate Chef::Resource::LWRPBase to ChefCompat::Resource - ChefCompat::Monkeypatches::Class.module_eval do - def new(*args, &block) - # Trick it! Use ChefCompat::Resource instead of Chef::Resource::LWRPBase - if args == [ ::Chef::Resource::LWRPBase ] - ChefCompat::Monkeypatches::Class.module_eval do - remove_method(:new) if method_defined?(:new) - end - args = [ ChefCompat::Resource::LWRPBase ] - end - super(*args, &block) - end - end - - begin - - # Call the actual build_from_file - super - - ensure - class<) -# 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. -# - -# XXX: we now have two copies of this file in the compat_resource cookbook. I'm uncertain if this is a -# bug or a feature, and I suspect it is actually a feature. The point of this file is that for all -# resources and cookbooks the global Chef::ResourceBuilder class must be upgraded to at least the -# 12.10.24 version. The point of the other copy is that for compat_resource cookbooks all their -# resources should be using the lastest version that has been sync'd. So these two files should -# diverge as times goes on. I believe that is the correct behavior and that we want to have both -# files in this cookbook. - -# NOTE: this was extracted from the Recipe DSL mixin, relevant specs are in spec/unit/recipe_spec.rb - -if Gem::Requirement.new("< 12.10.24").satisfied_by?(Gem::Version.new(Chef::VERSION)) - begin - require 'chef/resource_builder' - # we use the LoadError this creates on early 12.x to not monkeypatch chef client versions that don't have Chef::ResourceBuilder - # (it is lazily included and doesn't appear until compile time so we can't resolve the symbol during library loading) - - class Chef - class ResourceBuilder - 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) - @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) - identicalish_resources?(resource_class.new(name, run_context), 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 - Chef::Log.warn("Cloning resource attributes for #{resource} from prior resource (CHEF-3694)") - Chef::Log.warn("Previous #{prior_resource}: #{prior_resource.source_line}") if prior_resource.source_line - Chef::Log.warn("Current #{resource}: #{resource.source_line}") if resource.source_line - 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 - rescue LoadError - # cool we're just on early chef 12.x, nothing to do -- we don't have to worry because there's also not parent_run_context pointer, so we don't have to - # use lookup_local to avoid resource cloning shit out of the parent run_context. the resource collection's lookup() method will always use lookup_local - # over lookup_recursive. - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource_collection.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource_collection.rb deleted file mode 100644 index 4f074898..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource_collection.rb +++ /dev/null @@ -1,103 +0,0 @@ -# -# Author:: Adam Jacob () -# 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. -# - -require "chef/resource_collection/resource_set" -require "chef/resource_collection/resource_list" -require "chef/resource_collection" -require "chef/exceptions" - -module ChefCompat - module Monkeypatches - module Chef - module ResourceCollection - module RecursiveNotificationLookup - # - # Copied verbatim from Chef 12.10.24 - # - attr_accessor :run_context - - def initialize(run_context = nil) - super() - @run_context = run_context - end - - def lookup_local(key) - resource_set.lookup(key) - end - - def find_local(*args) - resource_set.find(*args) - end - - def lookup(key) - if run_context.nil? - lookup_local(key) - else - lookup_recursive(run_context, key) - end - end - - def find(*args) - if run_context.nil? - find_local(*args) - else - find_recursive(run_context, *args) - end - end - - private - - def lookup_recursive(rc, key) - rc.resource_collection.send(:resource_set).lookup(key) - rescue ::Chef::Exceptions::ResourceNotFound - raise if !rc.respond_to?(:parent_run_context) || rc.parent_run_context.nil? - lookup_recursive(rc.parent_run_context, key) - end - - def find_recursive(rc, *args) - rc.resource_collection.send(:resource_set).find(*args) - rescue ::Chef::Exceptions::ResourceNotFound - raise if !rc.respond_to?(:parent_run_context) || rc.parent_run_context.nil? - find_recursive(rc.parent_run_context, *args) - end - end - - module DeleteResources - # - # Copied verbatim from Chef 12.10.24 - # - def delete(key) - resource_list.delete(key) - resource_set.delete(key) - end - end - end - end - end -end - - -class Chef::ResourceCollection - unless method_defined?(:lookup_local) - prepend ChefCompat::Monkeypatches::Chef::ResourceCollection::RecursiveNotificationLookup - end - unless method_defined?(:delete) - prepend ChefCompat::Monkeypatches::Chef::ResourceCollection::DeleteResources - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource_collection/resource_list.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource_collection/resource_list.rb deleted file mode 100644 index dfbd442d..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource_collection/resource_list.rb +++ /dev/null @@ -1,49 +0,0 @@ -# -# Author:: Tyler Ball () -# Copyright:: Copyright 2014-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/resource_collection/resource_list" -require "chef/exceptions" - -module ChefCompat - module Monkeypatches - module Chef - module ResourceCollection - module ResourceList - module DeleteResource - # Copied verbatim from Chef 12.10.4 - def delete(key) - raise ArgumentError, "Must pass a Chef::Resource or String to delete" unless key.is_a?(String) || key.is_a?(Chef::Resource) - key = key.to_s - ret = @resources.reject! { |r| r.to_s == key } - if ret.nil? - raise ::Chef::Exceptions::ResourceNotFound, "Cannot find a resource matching #{key} (did you define it first?)" - end - ret - end - end - end - end - end - end -end - -class Chef::ResourceCollection::ResourceList - unless method_defined?(:delete) - prepend ChefCompat::Monkeypatches::Chef::ResourceCollection::ResourceList::DeleteResource - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource_collection/resource_set.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource_collection/resource_set.rb deleted file mode 100644 index bcead102..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/resource_collection/resource_set.rb +++ /dev/null @@ -1,49 +0,0 @@ -# -# Author:: Tyler Ball () -# Copyright:: Copyright 2014-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/resource_collection/resource_list" -require "chef/exceptions" - -module ChefCompat - module Monkeypatches - module Chef - module ResourceCollection - module ResourceSet - module DeleteResource - def delete(key) - raise ArgumentError, "Must pass a Chef::Resource or String to delete" unless key.is_a?(String) || key.is_a?(Chef::Resource) - key = key.to_s - res = @resources_by_key.delete(key) - - if res == @resources_by_key.default - raise Chef::Exceptions::ResourceNotFound, "Cannot find a resource matching #{key} (did you define it first?)" - end - res - end - end - end - end - end - end -end - -class Chef::ResourceCollection::ResourceSet - unless method_defined?(:delete) - prepend ChefCompat::Monkeypatches::Chef::ResourceCollection::ResourceSet::DeleteResource - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/run_context.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/run_context.rb deleted file mode 100644 index 03c9d60e..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/run_context.rb +++ /dev/null @@ -1,691 +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 -# - -if Gem::Requirement.new('< 12.16.42').satisfied_by?(Gem::Version.new(Chef::VERSION)) -# -# Author:: Adam Jacob () -# Author:: Christopher Walters () -# Author:: Tim Hinderliter () -# 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/resource_collection" -require "chef/cookbook_version" -require "chef/node" -require "chef/role" -require "chef/log" -require "chef/recipe" -require "chef/run_context/cookbook_compiler" -require "chef/event_dispatch/events_output_stream" -require "forwardable" - -class Chef - - # == Chef::RunContext - # Value object that loads and tracks the context of a Chef run - class RunContext - # - # Global state - # - - # - # The node for this run - # - # @return [Chef::Node] - # - attr_reader :node - - # - # The set of cookbooks involved in this run - # - # @return [Chef::CookbookCollection] - # - attr_reader :cookbook_collection - - # - # Resource Definitions for this run. Populated when the files in - # +definitions/+ are evaluated (this is triggered by #load). - # - # @return [Array[Chef::ResourceDefinition]] - # - attr_reader :definitions - - # - # Event dispatcher for this run. - # - # @return [Chef::EventDispatch::Dispatcher] - # - attr_reader :events - - # - # Hash of factoids for a reboot request. - # - # @return [Hash] - # - attr_accessor :reboot_info - - # - # Scoped state - # - - # - # The parent run context. - # - # @return [Chef::RunContext] The parent run context, or `nil` if this is the - # root context. - # - attr_reader :parent_run_context - - # - # The root run context. - # - # @return [Chef::RunContext] The root run context. - # - def root_run_context - rc = self - rc = rc.parent_run_context until rc.parent_run_context.nil? - rc - end - - # - # The collection of resources intended to be converged (and able to be - # notified). - # - # @return [Chef::ResourceCollection] - # - # @see CookbookCompiler - # - attr_reader :resource_collection - - # - # The list of control groups to execute during the audit phase - # - attr_reader :audits - - # - # Notification handling - # - - # - # A Hash containing the before notifications triggered by resources - # during the converge phase of the chef run. - # - # @return [Hash[String, Array[Chef::Resource::Notification]]] A hash from - # => - # - attr_reader :before_notification_collection - - # - # A Hash containing the immediate notifications triggered by resources - # during the converge phase of the chef run. - # - # @return [Hash[String, Array[Chef::Resource::Notification]]] A hash from - # => - # - attr_reader :immediate_notification_collection - - # - # A Hash containing the delayed (end of run) notifications triggered by - # resources during the converge phase of the chef run. - # - # @return [Hash[String, Array[Chef::Resource::Notification]]] A hash from - # => - # - attr_reader :delayed_notification_collection - - # - # An Array containing the delayed (end of run) notifications triggered by - # resources during the converge phase of the chef run. - # - # @return [Array[Chef::Resource::Notification]] An array of notification objects - # - attr_reader :delayed_actions - - # Creates a new Chef::RunContext object and populates its fields. This object gets - # used by the Chef Server to generate a fully compiled recipe list for a node. - # - # @param node [Chef::Node] The node to run against. - # @param cookbook_collection [Chef::CookbookCollection] The cookbooks - # involved in this run. - # @param events [EventDispatch::Dispatcher] The event dispatcher for this - # run. - # - def initialize(node, cookbook_collection, events) - @node = node - @cookbook_collection = cookbook_collection - @events = events - - node.run_context = self - node.set_cookbook_attribute - - @definitions = Hash.new - @loaded_recipes_hash = {} - @loaded_attributes_hash = {} - @reboot_info = {} - @cookbook_compiler = nil - @delayed_actions = [] - - initialize_child_state - end - - # - # Triggers the compile phase of the chef run. - # - # @param run_list_expansion [Chef::RunList::RunListExpansion] The run list. - # @see Chef::RunContext::CookbookCompiler - # - def load(run_list_expansion) - @cookbook_compiler = CookbookCompiler.new(self, run_list_expansion, events) - cookbook_compiler.compile - end - - # - # Initialize state that applies to both Chef::RunContext and Chef::ChildRunContext - # - def initialize_child_state - @audits = {} - @resource_collection = Chef::ResourceCollection.new(self) - @before_notification_collection = Hash.new { |h, k| h[k] = [] } - @immediate_notification_collection = Hash.new { |h, k| h[k] = [] } - @delayed_notification_collection = Hash.new { |h, k| h[k] = [] } - @delayed_actions = [] - end - - # - # Adds an before notification to the +before_notification_collection+. - # - # @param [Chef::Resource::Notification] The notification to add. - # - def notifies_before(notification) - # Note for the future, notification.notifying_resource may be an instance - # of Chef::Resource::UnresolvedSubscribes when calling {Resource#subscribes} - # with a string value. - before_notification_collection[notification.notifying_resource.declared_key] << notification - end - - # - # Adds an immediate notification to the +immediate_notification_collection+. - # - # @param [Chef::Resource::Notification] The notification to add. - # - def notifies_immediately(notification) - # Note for the future, notification.notifying_resource may be an instance - # of Chef::Resource::UnresolvedSubscribes when calling {Resource#subscribes} - # with a string value. - immediate_notification_collection[notification.notifying_resource.declared_key] << notification - end - - # - # Adds a delayed notification to the +delayed_notification_collection+. - # - # @param [Chef::Resource::Notification] The notification to add. - # - def notifies_delayed(notification) - # Note for the future, notification.notifying_resource may be an instance - # of Chef::Resource::UnresolvedSubscribes when calling {Resource#subscribes} - # with a string value. - delayed_notification_collection[notification.notifying_resource.declared_key] << notification - end - - # - # Adds a delayed action to the +delayed_actions+. - # - def add_delayed_action(notification) - if delayed_actions.any? { |existing_notification| existing_notification.duplicates?(notification) } - Chef::Log.info( "#{notification.notifying_resource} not queuing delayed action #{notification.action} on #{notification.resource}"\ - " (delayed), as it's already been queued") - else - delayed_actions << notification - end - end - - # - # Get the list of before notifications sent by the given resource. - # - # @return [Array[Notification]] - # - def before_notifications(resource) - return before_notification_collection[resource.declared_key] - end - - # - # Get the list of immediate notifications sent by the given resource. - # - # @return [Array[Notification]] - # - def immediate_notifications(resource) - return immediate_notification_collection[resource.declared_key] - end - - # - # Get the list of delayed (end of run) notifications sent by the given - # resource. - # - # @return [Array[Notification]] - # - def delayed_notifications(resource) - return delayed_notification_collection[resource.declared_key] - end - - # - # Cookbook and recipe loading - # - - # - # Evaluates the recipes +recipe_names+. Used by DSL::IncludeRecipe - # - # @param recipe_names [Array[String]] The list of recipe names (e.g. - # 'my_cookbook' or 'my_cookbook::my_resource'). - # @param current_cookbook The cookbook we are currently running in. - # - # @see DSL::IncludeRecipe#include_recipe - # - def include_recipe(*recipe_names, current_cookbook: nil) - result_recipes = Array.new - recipe_names.flatten.each do |recipe_name| - if result = load_recipe(recipe_name, current_cookbook: current_cookbook) - result_recipes << result - end - end - result_recipes - end - - # - # Evaluates the recipe +recipe_name+. Used by DSL::IncludeRecipe - # - # TODO I am sort of confused why we have both this and include_recipe ... - # I don't see anything different beyond accepting and returning an - # array of recipes. - # - # @param recipe_names [Array[String]] The recipe name (e.g 'my_cookbook' or - # 'my_cookbook::my_resource'). - # @param current_cookbook The cookbook we are currently running in. - # - # @return A truthy value if the load occurred; `false` if already loaded. - # - # @see DSL::IncludeRecipe#load_recipe - # - def load_recipe(recipe_name, current_cookbook: nil) - Chef::Log.debug("Loading recipe #{recipe_name} via include_recipe") - - cookbook_name, recipe_short_name = Chef::Recipe.parse_recipe_name(recipe_name, current_cookbook: current_cookbook) - - if unreachable_cookbook?(cookbook_name) # CHEF-4367 - Chef::Log.warn(<<-ERROR_MESSAGE) -MissingCookbookDependency: -Recipe `#{recipe_name}` is not in the run_list, and cookbook '#{cookbook_name}' -is not a dependency of any cookbook in the run_list. To load this recipe, -first add a dependency on cookbook '#{cookbook_name}' in the cookbook you're -including it from in that cookbook's metadata. -ERROR_MESSAGE - end - - if loaded_fully_qualified_recipe?(cookbook_name, recipe_short_name) - Chef::Log.debug("I am not loading #{recipe_name}, because I have already seen it.") - false - else - loaded_recipe(cookbook_name, recipe_short_name) - node.loaded_recipe(cookbook_name, recipe_short_name) - cookbook = cookbook_collection[cookbook_name] - cookbook.load_recipe(recipe_short_name, self) - end - end - - # - # Load the given recipe from a filename. - # - # @param recipe_file [String] The recipe filename. - # - # @return [Chef::Recipe] The loaded recipe. - # - # @raise [Chef::Exceptions::RecipeNotFound] If the file does not exist. - # - def load_recipe_file(recipe_file) - if !File.exist?(recipe_file) - raise Chef::Exceptions::RecipeNotFound, "could not find recipe file #{recipe_file}" - end - - Chef::Log.debug("Loading recipe file #{recipe_file}") - recipe = Chef::Recipe.new("@recipe_files", recipe_file, self) - recipe.from_file(recipe_file) - recipe - end - - # - # Look up an attribute filename. - # - # @param cookbook_name [String] The cookbook name of the attribute file. - # @param attr_file_name [String] The attribute file's name (not path). - # - # @return [String] The filename. - # - # @see DSL::IncludeAttribute#include_attribute - # - # @raise [Chef::Exceptions::CookbookNotFound] If the cookbook could not be found. - # @raise [Chef::Exceptions::AttributeNotFound] If the attribute file could not be found. - # - def resolve_attribute(cookbook_name, attr_file_name) - cookbook = cookbook_collection[cookbook_name] - raise Chef::Exceptions::CookbookNotFound, "could not find cookbook #{cookbook_name} while loading attribute #{name}" unless cookbook - - attribute_filename = cookbook.attribute_filenames_by_short_filename[attr_file_name] - raise Chef::Exceptions::AttributeNotFound, "could not find filename for attribute #{attr_file_name} in cookbook #{cookbook_name}" unless attribute_filename - - attribute_filename - end - - # - # A list of all recipes that have been loaded. - # - # This is stored internally as a Hash, so ordering is predictable. - # - # TODO is the above statement true in a 1.9+ ruby world? Is it relevant? - # - # @return [Array[String]] A list of recipes in fully qualified form, e.g. - # the recipe "nginx" will be given as "nginx::default". - # - # @see #loaded_recipe? To determine if a particular recipe has been loaded. - # - def loaded_recipes - loaded_recipes_hash.keys - end - - # - # A list of all attributes files that have been loaded. - # - # Stored internally using a Hash, so order is predictable. - # - # TODO is the above statement true in a 1.9+ ruby world? Is it relevant? - # - # @return [Array[String]] A list of attribute file names in fully qualified - # form, e.g. the "nginx" will be given as "nginx::default". - # - def loaded_attributes - loaded_attributes_hash.keys - end - - # - # Find out if a given recipe has been loaded. - # - # @param cookbook [String] Cookbook name. - # @param recipe [String] Recipe name. - # - # @return [Boolean] `true` if the recipe has been loaded, `false` otherwise. - # - def loaded_fully_qualified_recipe?(cookbook, recipe) - loaded_recipes_hash.has_key?("#{cookbook}::#{recipe}") - end - - # - # Find out if a given recipe has been loaded. - # - # @param recipe [String] Recipe name. "nginx" and "nginx::default" yield - # the same results. - # - # @return [Boolean] `true` if the recipe has been loaded, `false` otherwise. - # - def loaded_recipe?(recipe) - cookbook, recipe_name = Chef::Recipe.parse_recipe_name(recipe) - loaded_fully_qualified_recipe?(cookbook, recipe_name) - end - - # - # Mark a given recipe as having been loaded. - # - # @param cookbook [String] Cookbook name. - # @param recipe [String] Recipe name. - # - def loaded_recipe(cookbook, recipe) - loaded_recipes_hash["#{cookbook}::#{recipe}"] = true - end - - # - # Find out if a given attribute file has been loaded. - # - # @param cookbook [String] Cookbook name. - # @param attribute_file [String] Attribute file name. - # - # @return [Boolean] `true` if the recipe has been loaded, `false` otherwise. - # - def loaded_fully_qualified_attribute?(cookbook, attribute_file) - loaded_attributes_hash.has_key?("#{cookbook}::#{attribute_file}") - end - - # - # Mark a given attribute file as having been loaded. - # - # @param cookbook [String] Cookbook name. - # @param attribute_file [String] Attribute file name. - # - def loaded_attribute(cookbook, attribute_file) - loaded_attributes_hash["#{cookbook}::#{attribute_file}"] = true - end - - ## - # Cookbook File Introspection - - # - # Find out if the cookbook has the given template. - # - # @param cookbook [String] Cookbook name. - # @param template_name [String] Template name. - # - # @return [Boolean] `true` if the template is in the cookbook, `false` - # otherwise. - # @see Chef::CookbookVersion#has_template_for_node? - # - def has_template_in_cookbook?(cookbook, template_name) - cookbook = cookbook_collection[cookbook] - cookbook.has_template_for_node?(node, template_name) - end - - # - # Find out if the cookbook has the given file. - # - # @param cookbook [String] Cookbook name. - # @param cb_file_name [String] File name. - # - # @return [Boolean] `true` if the file is in the cookbook, `false` - # otherwise. - # @see Chef::CookbookVersion#has_cookbook_file_for_node? - # - def has_cookbook_file_in_cookbook?(cookbook, cb_file_name) - cookbook = cookbook_collection[cookbook] - cookbook.has_cookbook_file_for_node?(node, cb_file_name) - end - - # - # Find out whether the given cookbook is in the cookbook dependency graph. - # - # @param cookbook_name [String] Cookbook name. - # - # @return [Boolean] `true` if the cookbook is reachable, `false` otherwise. - # - # @see Chef::CookbookCompiler#unreachable_cookbook? - def unreachable_cookbook?(cookbook_name) - cookbook_compiler.unreachable_cookbook?(cookbook_name) - end - - # - # Open a stream object that can be printed into and will dispatch to events - # - # @param name [String] The name of the stream. - # @param options [Hash] Other options for the stream. - # - # @return [EventDispatch::EventsOutputStream] The created stream. - # - # @yield If a block is passed, it will be run and the stream will be closed - # afterwards. - # @yieldparam stream [EventDispatch::EventsOutputStream] The created stream. - # - def open_stream(name: nil, **options) - stream = EventDispatch::EventsOutputStream.new(events, name: name, **options) - if block_given? - begin - yield stream - ensure - stream.close - end - else - stream - end - end - - # there are options for how to handle multiple calls to these functions: - # 1. first call always wins (never change reboot_info once set). - # 2. last call always wins (happily change reboot_info whenever). - # 3. raise an exception on the first conflict. - # 4. disable reboot after this run if anyone ever calls :cancel. - # 5. raise an exception on any second call. - # 6. ? - def request_reboot(reboot_info) - Chef::Log.info "Changing reboot status from #{self.reboot_info.inspect} to #{reboot_info.inspect}" - @reboot_info = reboot_info - end - - def cancel_reboot - Chef::Log.info "Changing reboot status from #{reboot_info.inspect} to {}" - @reboot_info = {} - end - - def reboot_requested? - reboot_info.size > 0 - end - - # - # Create a child RunContext. - # - def create_child - ChildRunContext.new(self) - end - - # @api private - attr_writer :resource_collection - - protected - - attr_reader :cookbook_compiler - attr_reader :loaded_attributes_hash - attr_reader :loaded_recipes_hash - - module Deprecated - ### - # These need to be settable so deploy can run a resource_collection - # independent of any cookbooks via +recipe_eval+ - def audits=(value) - Chef.log_deprecation("Setting run_context.audits will be removed in a future Chef. Use run_context.create_child to create a new RunContext instead.") - @audits = value - end - - def immediate_notification_collection=(value) - Chef.log_deprecation("Setting run_context.immediate_notification_collection will be removed in a future Chef. Use run_context.create_child to create a new RunContext instead.") - @immediate_notification_collection = value - end - - def delayed_notification_collection=(value) - Chef.log_deprecation("Setting run_context.delayed_notification_collection will be removed in a future Chef. Use run_context.create_child to create a new RunContext instead.") - @delayed_notification_collection = value - end - end - prepend Deprecated - - # - # A child run context. Delegates all root context calls to its parent. - # - # @api private - # - class ChildRunContext < RunContext - extend Forwardable - def_delegators :parent_run_context, *%w{ - cancel_reboot - config - cookbook_collection - cookbook_compiler - definitions - events - has_cookbook_file_in_cookbook? - has_template_in_cookbook? - load - loaded_attribute - loaded_attributes - loaded_attributes_hash - loaded_fully_qualified_attribute? - loaded_fully_qualified_recipe? - loaded_recipe - loaded_recipe? - loaded_recipes - loaded_recipes_hash - node - open_stream - reboot_info - reboot_info= - reboot_requested? - request_reboot - resolve_attribute - unreachable_cookbook? - } - - def initialize(parent_run_context) - @parent_run_context = parent_run_context - - # We don't call super, because we don't bother initializing stuff we're - # going to delegate to the parent anyway. Just initialize things that - # every instance needs. - initialize_child_state - end - - CHILD_STATE = %w{ - audits - audits= - create_child - add_delayed_action - delayed_actions - delayed_notification_collection - delayed_notification_collection= - delayed_notifications - immediate_notification_collection - immediate_notification_collection= - immediate_notifications - before_notification_collection - before_notifications - include_recipe - initialize_child_state - load_recipe - load_recipe_file - notifies_before - notifies_immediately - notifies_delayed - parent_run_context - root_run_context - resource_collection - resource_collection= - }.map { |x| x.to_sym } - - # Verify that we didn't miss any methods - unless @__skip_method_checking # hook specifically for compat_resource - missing_methods = superclass.instance_methods(false) - instance_methods(false) - CHILD_STATE - if !missing_methods.empty? - raise "ERROR: not all methods of RunContext accounted for in ChildRunContext! All methods must be marked as child methods with CHILD_STATE or delegated to the parent_run_context. Missing #{missing_methods.join(", ")}." - end - end - end - end -end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/runner.rb b/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/runner.rb deleted file mode 100644 index 9add7a8b..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/monkeypatches/chef/runner.rb +++ /dev/null @@ -1,153 +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 -# - -if Gem::Requirement.new('< 12.16.42').satisfied_by?(Gem::Version.new(Chef::VERSION)) -#-- -# Author:: Adam Jacob () -# Author:: Christopher Walters () -# Author:: Tim Hinderliter () -# 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/exceptions" -require "chef/mixin/params_validate" -require "chef/node" -require "chef/resource_collection" - -class Chef - # == Chef::Runner - # This class is responsible for executing the steps in a Chef run. - class Runner - - attr_reader :run_context - - include Chef::Mixin::ParamsValidate - - def initialize(run_context) - @run_context = run_context - end - - def delayed_actions - @run_context.delayed_actions - end - - def events - @run_context.events - end - - # Determine the appropriate provider for the given resource, then - # execute it. - def run_action(resource, action, notification_type = nil, notifying_resource = nil) - # If there are any before notifications, why-run the resource - # and notify anyone who needs notifying - before_notifications = run_context.before_notifications(resource) || [] - unless before_notifications.empty? - forced_why_run do - Chef::Log.info("#{resource} running why-run #{action} action to support before action") - resource.run_action(action, notification_type, notifying_resource) - end - - if resource.updated_by_last_action? - before_notifications.each do |notification| - Chef::Log.info("#{resource} sending #{notification.action} action to #{notification.resource} (before)") - run_action(notification.resource, notification.action, :before, resource) - end - resource.updated_by_last_action(false) - end - end - - # Actually run the action for realsies - resource.run_action(action, notification_type, notifying_resource) - - # Execute any immediate and queue up any delayed notifications - # associated with the resource, but only if it was updated *this time* - # we ran an action on it. - if resource.updated_by_last_action? - run_context.immediate_notifications(resource).each do |notification| - Chef::Log.info("#{resource} sending #{notification.action} action to #{notification.resource} (immediate)") - run_action(notification.resource, notification.action, :immediate, resource) - end - - run_context.delayed_notifications(resource).each do |notification| - # send the notification to the run_context of the receiving resource - notification.resource.run_context.add_delayed_action(notification) - end - end - end - - # Iterates over the +resource_collection+ in the +run_context+ calling - # +run_action+ for each resource in turn. - def converge - # Resolve all lazy/forward references in notifications - run_context.resource_collection.each do |resource| - resource.resolve_notification_references - end - - # Execute each resource. - run_context.resource_collection.execute_each_resource do |resource| - Array(resource.action).each { |action| run_action(resource, action) } - end - - rescue Exception => e - Chef::Log.info "Running queued delayed notifications before re-raising exception" - run_delayed_notifications(e) - else - run_delayed_notifications(nil) - true - end - - private - - # Run all our :delayed actions - def run_delayed_notifications(error = nil) - collected_failures = Exceptions::MultipleFailures.new - collected_failures.client_run_failure(error) unless error.nil? - delayed_actions.each do |notification| - result = run_delayed_notification(notification) - if result.kind_of?(Exception) - collected_failures.notification_failure(result) - end - end - collected_failures.raise! - end - - def run_delayed_notification(notification) - Chef::Log.info( "#{notification.notifying_resource} sending #{notification.action}"\ - " action to #{notification.resource} (delayed)") - # Struct of resource/action to call - run_action(notification.resource, notification.action, :delayed) - true - rescue Exception => e - e - end - - # helper to run a block of code with why_run forced to true and then restore it correctly - def forced_why_run - saved = Chef::Config[:why_run] - Chef::Config[:why_run] = true - yield - ensure - Chef::Config[:why_run] = saved - end - - end -end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/property.rb b/cookbooks/compat_resource/files/lib/chef_compat/property.rb deleted file mode 100644 index be211135..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/property.rb +++ /dev/null @@ -1,6 +0,0 @@ -require 'chef_compat/copied_from_chef/chef/property' - -module ChefCompat - class Property < ChefCompat::CopiedFromChef::Chef::Property - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/recipe.rb b/cookbooks/compat_resource/files/lib/chef_compat/recipe.rb deleted file mode 100644 index 86e39d97..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/recipe.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'chef/recipe' -require 'chef_compat/copied_from_chef/chef/dsl/recipe' - -module ChefCompat - class Recipe < Chef::Recipe - include ChefCompat::CopiedFromChef::Chef::DSL::Recipe::FullDSL - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/resource.rb b/cookbooks/compat_resource/files/lib/chef_compat/resource.rb deleted file mode 100644 index bcf0fdb2..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/resource.rb +++ /dev/null @@ -1,56 +0,0 @@ -require 'chef_compat/monkeypatches' -require 'chef_compat/copied_from_chef/chef/resource' - -# We do NOT want action defined if chefspec is engaged -if Chef::Provider::InlineResources::ClassMethods.instance_method(:action).source_location[0] =~ /chefspec/ - ChefCompat::CopiedFromChef::Chef::Provider::InlineResources::ClassMethods.instance_eval do - remove_method(:action) - end -end - -module ChefCompat - class Resource < ChefCompat::CopiedFromChef::Chef::Resource - def initialize(*args, &block) - super - # @resource_name is used in earlier Chef versions - @resource_name = self.class.resource_name - end - # Things we'll need to define ourselves: - # 1. provider - # 2. resource_name - - def provider(*args, &block) - super || self.class.action_class - end - def provider=(arg) - provider(arg) - end - - if !respond_to?(:resource_name) - def self.resource_name(name=Chef::NOT_PASSED) - # Setter - if name != Chef::NOT_PASSED - # remove_canonical_dsl - - # Set the resource_name and call provides - if name - name = name.to_sym - # If our class is not already providing this name, provide it. - # Commented out: use of resource_name and provides will need to be - # mutually exclusive in this world, generally. - # if !Chef::ResourceResolver.includes_handler?(name, self) - provides name#, canonical: true - # end - @resource_name = name - else - @resource_name = nil - end - end - @resource_name - end - def self.resource_name=(name) - resource_name(name) - end - end - end -end diff --git a/cookbooks/compat_resource/files/lib/chef_compat/resource/lwrp_base.rb b/cookbooks/compat_resource/files/lib/chef_compat/resource/lwrp_base.rb deleted file mode 100644 index 2ebb98fd..00000000 --- a/cookbooks/compat_resource/files/lib/chef_compat/resource/lwrp_base.rb +++ /dev/null @@ -1,44 +0,0 @@ -require 'chef_compat/resource' -require 'chef_compat/copied_from_chef/chef/resource' -require 'chef/mixin/convert_to_class_name' -require 'chef/mixin/from_file' - -module ChefCompat - class Resource < ChefCompat::CopiedFromChef::Chef::Resource - class LWRPBase < ChefCompat::Resource - class<= 12.0").satisfied_by?(Gem::Version.new(Chef::VERSION)) - - require 'chef_compat/resource' - require 'chef_compat/property' - require 'chef_compat/mixin/properties' - - resources_dir = File.expand_path("chef_compat/copied_from_chef/chef/resource", File.dirname(__FILE__)) - providers_dir = File.expand_path("chef_compat/copied_from_chef/chef/provider", File.dirname(__FILE__)) - Dir["#{resources_dir}/*.rb"].each {|file| require file } - Dir["#{providers_dir}/*.rb"].each {|file| require file } -else - - class Chef - class Resource - def self.property(args, &block) - raise_chef_11_error - end - - def self.resource_name(args, &block) - raise_chef_11_error - end - - def self.action(args, &block) - raise_chef_11_error - end - - def self.raise_chef_11_error - raise "This resource is written with Chef 12.5 custom resources, and requires at least Chef 12.0 used with the compat_resource cookbook, it will not work with Chef 11.x clients, and those users must pin their cookbooks to older versions or upgrade." - end - end - end - -end diff --git a/cookbooks/compat_resource/libraries/autoload.rb b/cookbooks/compat_resource/libraries/autoload.rb deleted file mode 100644 index db52cfc6..00000000 --- a/cookbooks/compat_resource/libraries/autoload.rb +++ /dev/null @@ -1,31 +0,0 @@ -unless Gem::Requirement.new(">= 12.0").satisfied_by?(Gem::Version.new(Chef::VERSION)) - raise "This resource is written with Chef 12.5 custom resources, and requires at least Chef 12.0 used with the compat_resource cookbook, it will not work with Chef 11.x clients, and those users must pin their cookbooks to older versions or upgrade." -end - -# If users are on old verisons of ChefDK which activates an (old) gem via cheffish before this cookbook loads, then -# we just try to monkeypatch over the top of a monkeypatch. Its possible that we have checks in this cookbook which -# will defeat that purpose and fail to monkeypatch on top of monkeypatches -- in which case those checks should be -# removed -- this cookbook needs to win when it gets into a fight with the old gem versions. -if Gem.loaded_specs["compat_resource"] - Chef.log_deprecation "using compat_resource as a gem is deprecated; please update cheffish and chef-provisioning gems (or use the latest Chef/ChefDK packages) or else manually pin your compat_resource cookbook version to the same version as the gem you are using to remove this warning" -end - -# we want to not pollute the libpath with our files until after we've done the version check -require_relative '../files/lib/chef_upstream_version' - -# on any chef client later than the one we were based off of we just turn into a no-op -if Gem::Requirement.new("< #{ChefCompat::CHEF_UPSTREAM_VERSION}").satisfied_by?(Gem::Version.new(Chef::VERSION)) - Chef::Log.debug "loading compat_resource based on chef-version #{ChefCompat::CHEF_UPSTREAM_VERSION} over chef version #{Gem::Version.new(Chef::VERSION)}" - $LOAD_PATH.unshift(File.expand_path("../files/lib", File.dirname(__FILE__))) - require 'compat_resource' -else - Chef::Log.debug "NOT LOADING compat_resource based on chef-version #{ChefCompat::CHEF_UPSTREAM_VERSION} over chef version #{Gem::Version.new(Chef::VERSION)}" - unless defined?(ChefCompat::Resource) && defined?(ChefCompat::Mixin::Properties) - module ChefCompat - Resource = Chef::Resource - module Mixin - Properties = Chef::Mixin::Properties - end - end - end -end diff --git a/cookbooks/compat_resource/metadata.rb b/cookbooks/compat_resource/metadata.rb deleted file mode 100644 index 645f8e73..00000000 --- a/cookbooks/compat_resource/metadata.rb +++ /dev/null @@ -1,12 +0,0 @@ -name 'compat_resource' -maintainer 'Lamont Granquist' -maintainer_email 'lamont@chef.io' -license 'Apache 2.0' -description 'Backports functionality introduced in the latest chef-client releases to any chef-client from 12.1 onwards' -long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) - -version '12.19.0' - -chef_version '>= 12.1' if respond_to?(:chef_version) -source_url 'https://github.com/chef-cookbooks/compat_resource' -issues_url 'https://github.com/chef-cookbooks/compat_resource/issues' diff --git a/cookbooks/compat_resource/run_all.rb b/cookbooks/compat_resource/run_all.rb deleted file mode 100644 index 2875b8f0..00000000 --- a/cookbooks/compat_resource/run_all.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'yaml' -travis = YAML.load(IO.read('.travis.yml')) -env = Array(travis['env']) + travis['matrix']['include'].map { |x| Array(x['env']) }.flatten -env.each do |env| - puts("bash -c \"export #{env}; bundle update && bundle exec rake spec\"") - system("export #{env} && bundle update && bundle exec rake spec") -end diff --git a/cookbooks/compat_resource/spec/cookbook_spec.rb b/cookbooks/compat_resource/spec/cookbook_spec.rb deleted file mode 100644 index b9100df0..00000000 --- a/cookbooks/compat_resource/spec/cookbook_spec.rb +++ /dev/null @@ -1,112 +0,0 @@ -require 'tmpdir' -require 'chef/version' - -describe "compat_resource cookbook" do - let(:chef_repo_path) { Dir.mktmpdir } - let(:cookbooks_path) { path = File.join(chef_repo_path, 'cookbooks'); Dir.mkdir(path); path } - before do - File.symlink(File.expand_path('../data/config.rb', __FILE__), - File.join(chef_repo_path, 'config.rb')) - File.symlink(File.expand_path('../..', __FILE__), - File.join(cookbooks_path, 'compat_resource')) - File.symlink(File.expand_path('../data/cookbooks/test', __FILE__), - File.join(cookbooks_path, 'test')) - File.symlink(File.expand_path('../data/cookbooks/future', __FILE__), - File.join(cookbooks_path, 'future')) - File.symlink(File.expand_path('../data/cookbooks/normal', __FILE__), - File.join(cookbooks_path, 'normal')) - File.symlink(File.expand_path('../data/cookbooks/hybrid', __FILE__), - File.join(cookbooks_path, 'hybrid')) - File.symlink(File.expand_path('../data/cookbooks/notifications', __FILE__), - File.join(cookbooks_path, 'notifications')) - File.symlink(File.expand_path('../data/cookbooks/strange_notifications', __FILE__), - File.join(cookbooks_path, 'strange_notifications')) - File.symlink(File.expand_path('../data/cookbooks/before', __FILE__), - File.join(cookbooks_path, 'before')) - File.symlink(File.expand_path('../data/cookbooks/cloning', __FILE__), - File.join(cookbooks_path, 'cloning')) - File.symlink(File.expand_path('../data/cookbooks/unmodified', __FILE__), - File.join(cookbooks_path, 'unmodified')) - end - - require 'chef/mixin/shell_out' - include Chef::Mixin::ShellOut - before :all do - FileUtils.rm_f(File.expand_path('../data/Gemfile.lock', __FILE__)) - Bundler.with_clean_env do - shell_out!("bundle install --gemfile #{File.expand_path('../data/Gemfile', __FILE__)}") - end - end - - def run_chef(args) - Bundler.with_clean_env do - shell_out!("bundle exec chef-client -c #{File.join(chef_repo_path, 'config.rb')} -F doc #{args}", - environment: { 'BUNDLE_GEMFILE' => File.expand_path('../data/Gemfile', __FILE__) }) - end - end - - it "should work with before notifications" do - result = run_chef("-o before") - expect(result.stdout).to match(/.*INFO: log\[the notify\] running why-run write action to support before action.*INFO: the notify.*INFO: before.*INFO: the notify.*/m) - end - - it "should handle new-style recursive notifications" do - result = run_chef("-o notifications") - end - - it "should fix https://github.com/chef-cookbooks/compat_resource/issues/99" do - result = run_chef("-o strange_notifications::one") - expect(result.stdout).to match(/INFO: Processing log\[it worked\] action write/) - end - - it "should fix https://github.com/chef-cookbooks/compat_resource/issues/87" do - result = run_chef("-o strange_notifications::two") - expect(result.stdout.scan("INFO: Processing log\[two\] action write").size).to eq(1) # appears once - end - - it "should definitely run a bunch of resources if we don't depend on compat_resource" do - result = run_chef("-o unmodified") - end - - it "should run a bunch of resources in a mixed-run" do - result = run_chef("-o unmodified,test") - end - - it "should not clone resources from the outer run context" do - result = run_chef("-o future::declare_resource,cloning::default") - expect(result.stdout).not_to match(/3694/) - end - - it "when chef-client runs the test recipe, it succeeds" do - result = run_chef("-o test::test,test") -# expect(result.stdout).to match(/ -# Recipe: test::test -# \* future_resource\[sets neither x nor y\] action create \(up to date\) -# \* future_resource\[sets both x and y\] action create -# - update sets both x and y -# - set x to "hi" \(was "initial_x"\) -# - set y to 10 \(was 2\) -# \* future_resource\[sets neither x nor y explicitly\] action create \(up to date\) -# \* future_resource\[sets only y\] action create -# - update sets only y -# - set y to 20 (was 10) -# \* future_resource\[deletes resource\] action delete \(up to date\) -# \* future_resource\[sets x and y via creation\] action create -# - create sets x and y via creation -# - set x to "hi" -# - set y to 20 -# \* future_resource\[deletes resource again\] action delete \(up to date\) -# \* future_resource\[sets x and y to their defaults via creation\] action create -# - create sets x and y to their defaults via creation -# - set x to "16" \(default value\) -# - set y to 4 \(default value\) -# /) - end - if Gem::Requirement.new("< 12.6").satisfied_by?(Gem::Version.new(Chef::VERSION)) - it "when chef-client tries to declare_resource with extra parameters, it fails" do - expect { - run_chef("-o normal::declare_resource") - }.to raise_error(Mixlib::ShellOut::ShellCommandFailed) - end - end -end diff --git a/cookbooks/compat_resource/spec/data/Gemfile b/cookbooks/compat_resource/spec/data/Gemfile deleted file mode 100644 index 35a217ad..00000000 --- a/cookbooks/compat_resource/spec/data/Gemfile +++ /dev/null @@ -1,18 +0,0 @@ -source 'https://rubygems.org' - -gem 'rack' # 2.0 requires Ruby 2.2+ - -# these are included to surface interactions between these gems and chef and -# compat_resource, particularly before 12.6.x when these gems will eagerly -# be loaded before compat_resource. -# -# FIXME: we should probably be using the versions that shipped with omnibus-chef -# at the time. We should probably use TK to just install omnibus-chef. -gem 'chef-provisioning' -gem 'cheffish' - -if ENV['GEMFILE_MOD'] - instance_eval(ENV['GEMFILE_MOD']) -else - gem 'chef' -end diff --git a/cookbooks/compat_resource/spec/data/config.rb b/cookbooks/compat_resource/spec/data/config.rb deleted file mode 100644 index 13b9524b..00000000 --- a/cookbooks/compat_resource/spec/data/config.rb +++ /dev/null @@ -1,3 +0,0 @@ -local_mode true -chef_repo_path File.dirname(__FILE__) -#log_level :debug diff --git a/cookbooks/compat_resource/spec/data/cookbooks/before/metadata.rb b/cookbooks/compat_resource/spec/data/cookbooks/before/metadata.rb deleted file mode 100644 index 61081b2f..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/before/metadata.rb +++ /dev/null @@ -1,4 +0,0 @@ -name "before" -description "cookbook that depends on compat_resource" -version "1.0.0" -depends "compat_resource" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/before/recipes/default.rb b/cookbooks/compat_resource/spec/data/cookbooks/before/recipes/default.rb deleted file mode 100644 index abaaae2c..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/before/recipes/default.rb +++ /dev/null @@ -1,7 +0,0 @@ -log "the notify" do - notifies :write, "log[before]", :before -end - -log "before" do - action :nothing -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/cloning/metadata.rb b/cookbooks/compat_resource/spec/data/cookbooks/cloning/metadata.rb deleted file mode 100644 index 08ec1821..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/cloning/metadata.rb +++ /dev/null @@ -1,3 +0,0 @@ -name "cloning" -description "cookbook that DOES NOT depend on compat_resource" -version "1.0.0" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/cloning/providers/resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/cloning/providers/resource.rb deleted file mode 100644 index 5c2c95e6..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/cloning/providers/resource.rb +++ /dev/null @@ -1,9 +0,0 @@ -provides :resource - -use_inline_resources - -action :create do - log "stuff" do - only_if { true } - end -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/cloning/recipes/default.rb b/cookbooks/compat_resource/spec/data/cookbooks/cloning/recipes/default.rb deleted file mode 100644 index 1e44ad0c..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/cloning/recipes/default.rb +++ /dev/null @@ -1,3 +0,0 @@ -log "stuff" - -resource "doit" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/cloning/resources/resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/cloning/resources/resource.rb deleted file mode 100644 index 29d30a35..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/cloning/resources/resource.rb +++ /dev/null @@ -1,2 +0,0 @@ -provides :resource -resource_name :resource diff --git a/cookbooks/compat_resource/spec/data/cookbooks/future/libraries/future_custom_resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/future/libraries/future_custom_resource.rb deleted file mode 100644 index 83b9011e..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/future/libraries/future_custom_resource.rb +++ /dev/null @@ -1,12 +0,0 @@ -class FutureCustomResource < ChefCompat::Resource - resource_name :future_custom_resource - property :x - action :create do - converge_if_changed do - end - future_custom_resource 'hi' do - x x # test that a warning is emitted properly (and no crashey) - action :nothing - end - end -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/future/libraries/super_properties.rb b/cookbooks/compat_resource/spec/data/cookbooks/future/libraries/super_properties.rb deleted file mode 100644 index 4f981d24..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/future/libraries/super_properties.rb +++ /dev/null @@ -1,8 +0,0 @@ -module FutureCookbook - module SuperProperties - include ChefCompat::Mixin::Properties - - property :x, default: 10 - property :y, default: 20 - end -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/future/metadata.rb b/cookbooks/compat_resource/spec/data/cookbooks/future/metadata.rb deleted file mode 100644 index f23eb992..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/future/metadata.rb +++ /dev/null @@ -1,4 +0,0 @@ -name "future" -description "cookbook that depends on compat_resource" -version "1.0.0" -depends "compat_resource" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/future/recipes/declare_resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/future/recipes/declare_resource.rb deleted file mode 100644 index b75b8edf..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/future/recipes/declare_resource.rb +++ /dev/null @@ -1,3 +0,0 @@ -declare_resource(:ruby_block, 'y', caller[0], create_if_missing: true) do - block { puts 'hi' } -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/future/resources/resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/future/resources/resource.rb deleted file mode 100644 index 0eed1ef4..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/future/resources/resource.rb +++ /dev/null @@ -1,54 +0,0 @@ -# Make sure and emit a property that triggers deprecation -property :n, name_property: true, default: 5 -property :x, String, coerce: proc { |x| x.to_s }, default: lazy { y*y } -property :y, Integer, default: 4 - -class ::Globals - @@exists = true - def self.exists - @@exists - end - def self.exists=(value) - @@exists = value - end - - @@global_x = 'initial_x' - def self.global_x - @@global_x - end - def self.global_x=(value) - @@global_x = value - end - - @@global_y = 2 - def self.global_y - @@global_y - end - def self.global_y=(value) - @@global_y = value - end -end - -load_current_value do - current_value_does_not_exist! if !Globals.exists - - x Globals.global_x - y Globals.global_y -end - -action :create do - converge_if_changed do - Globals.exists = true - Globals.global_x = x - Globals.global_y = y - end - file ::File.expand_path('~/x.txt') do - content 'hi' - end - # return is how people exit from 12.5 actions. Test that it works across versions. - return -end - -action :delete do - Globals.exists = false -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/future/resources/super_resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/future/resources/super_resource.rb deleted file mode 100644 index 32df07f6..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/future/resources/super_resource.rb +++ /dev/null @@ -1,7 +0,0 @@ -include FutureCookbook::SuperProperties - -action :create do - file ::File.expand_path('~/y.txt') do - content "#{x}#{y}" - end -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/hybrid/libraries/normal_hwrp.rb b/cookbooks/compat_resource/spec/data/cookbooks/hybrid/libraries/normal_hwrp.rb deleted file mode 100644 index b61a3ee9..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/hybrid/libraries/normal_hwrp.rb +++ /dev/null @@ -1,24 +0,0 @@ -class Chef::Resource::NormalHwrp < Chef::Resource - def initialize(*args) - super - @resource_name = :normal_hwrp - @allowed_actions = [ :create ] - @action = :create - end - - provides :normal_hwrp - - def x(arg=nil) - set_or_return(:x, arg, {}) - end - -end - -class Chef::Provider::NormalHwrp < Chef::Resource - provides :normal_hwrp - def load_current_resource - end - def action_create - new_resource.updated_by_last_resource(true) - end -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/hybrid/metadata.rb b/cookbooks/compat_resource/spec/data/cookbooks/hybrid/metadata.rb deleted file mode 100644 index 73fc5ee6..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/hybrid/metadata.rb +++ /dev/null @@ -1,4 +0,0 @@ -name "hybrid" -description "cookbook that depends on compat_resource, but has LWRPs" -version "1.0.0" -depends "compat_resource" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/hybrid/providers/resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/hybrid/providers/resource.rb deleted file mode 100644 index 847aa758..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/hybrid/providers/resource.rb +++ /dev/null @@ -1,4 +0,0 @@ -action :create do - converge_by "update!" do - end -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/hybrid/resources/resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/hybrid/resources/resource.rb deleted file mode 100644 index 9697e32b..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/hybrid/resources/resource.rb +++ /dev/null @@ -1,5 +0,0 @@ - -actions :create -default_action :create - -attribute :x, kind_of: [ String ], name_attribute: true diff --git a/cookbooks/compat_resource/spec/data/cookbooks/normal/libraries/normal_hwrp.rb b/cookbooks/compat_resource/spec/data/cookbooks/normal/libraries/normal_hwrp.rb deleted file mode 100644 index b61a3ee9..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/normal/libraries/normal_hwrp.rb +++ /dev/null @@ -1,24 +0,0 @@ -class Chef::Resource::NormalHwrp < Chef::Resource - def initialize(*args) - super - @resource_name = :normal_hwrp - @allowed_actions = [ :create ] - @action = :create - end - - provides :normal_hwrp - - def x(arg=nil) - set_or_return(:x, arg, {}) - end - -end - -class Chef::Provider::NormalHwrp < Chef::Resource - provides :normal_hwrp - def load_current_resource - end - def action_create - new_resource.updated_by_last_resource(true) - end -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/normal/metadata.rb b/cookbooks/compat_resource/spec/data/cookbooks/normal/metadata.rb deleted file mode 100644 index be59f714..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/normal/metadata.rb +++ /dev/null @@ -1,3 +0,0 @@ -name "normal" -description "cookbook that does not depend on compat_resource" -version "1.0.0" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/normal/providers/resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/normal/providers/resource.rb deleted file mode 100644 index 35aa4dcd..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/normal/providers/resource.rb +++ /dev/null @@ -1,6 +0,0 @@ -action :create do - converge_by "update!" do - end - # next is how people generally exit from actions in traditional providers - next -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/normal/recipes/declare_resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/normal/recipes/declare_resource.rb deleted file mode 100644 index b75b8edf..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/normal/recipes/declare_resource.rb +++ /dev/null @@ -1,3 +0,0 @@ -declare_resource(:ruby_block, 'y', caller[0], create_if_missing: true) do - block { puts 'hi' } -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/normal/resources/resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/normal/resources/resource.rb deleted file mode 100644 index 91b8b4df..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/normal/resources/resource.rb +++ /dev/null @@ -1,4 +0,0 @@ -actions :create -default_action :create - -attribute :x, kind_of: [ String ], name_attribute: true diff --git a/cookbooks/compat_resource/spec/data/cookbooks/notifications/metadata.rb b/cookbooks/compat_resource/spec/data/cookbooks/notifications/metadata.rb deleted file mode 100644 index 07a3c5af..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/notifications/metadata.rb +++ /dev/null @@ -1,4 +0,0 @@ -name "notifications" -description "cookbook that depends on compat_resource" -version "1.0.0" -depends "compat_resource" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/notifications/recipes/default.rb b/cookbooks/compat_resource/spec/data/cookbooks/notifications/recipes/default.rb deleted file mode 100644 index 8d12b2a6..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/notifications/recipes/default.rb +++ /dev/null @@ -1,5 +0,0 @@ -log "recipe" do - action :nothing -end - -resource "doit" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/notifications/resources/resource.rb b/cookbooks/compat_resource/spec/data/cookbooks/notifications/resources/resource.rb deleted file mode 100644 index 01ce62f3..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/notifications/resources/resource.rb +++ /dev/null @@ -1,8 +0,0 @@ -provides :resource -resource_name :resource - -action :create do - log "resource" do - notifies :write, "log[recipe]" - end -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/files/file b/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/files/file deleted file mode 100644 index d95f3ad1..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/files/file +++ /dev/null @@ -1 +0,0 @@ -content diff --git a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/metadata.rb b/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/metadata.rb deleted file mode 100644 index 80e36156..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/metadata.rb +++ /dev/null @@ -1,4 +0,0 @@ -name "strange_notifications" -description "cookbook that depends on compat_resource" -version "1.0.0" -depends "compat_resource" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/providers/an_lwrp_provider.rb b/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/providers/an_lwrp_provider.rb deleted file mode 100644 index 98276059..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/providers/an_lwrp_provider.rb +++ /dev/null @@ -1,4 +0,0 @@ -use_inline_resources - -action :run do -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/recipes/one.rb b/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/recipes/one.rb deleted file mode 100644 index 8a15aaf4..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/recipes/one.rb +++ /dev/null @@ -1,14 +0,0 @@ -filename = "/tmp/lksjdfkASDFASdlkfl.out" - -file filename do - action :delete -end - -cookbook_file filename do - source "file" -end - -log "it worked" do - subscribes :write, "cookbook_file[#{filename}]", :immediately - action :nothing -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/recipes/two.rb b/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/recipes/two.rb deleted file mode 100644 index 781a32da..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/recipes/two.rb +++ /dev/null @@ -1,15 +0,0 @@ - - -log "one" do - notifies :write, 'log[two]', :delayed -end - -# this is legitimately testing a 'strange' notification bug -# where calling an LWRP provider that did use_inline_resources -# (but not calling a custom resource) caused delayed notifications -# to double-fire. -an_lwrp_provider "foo" - -log "two" do - action :nothing -end diff --git a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/resources/an_lwrp_provider.rb b/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/resources/an_lwrp_provider.rb deleted file mode 100644 index 2740bcbb..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/strange_notifications/resources/an_lwrp_provider.rb +++ /dev/null @@ -1,4 +0,0 @@ -provides :an_lwrp_provider - -actions :run -default_action :run diff --git a/cookbooks/compat_resource/spec/data/cookbooks/test/metadata.rb b/cookbooks/compat_resource/spec/data/cookbooks/test/metadata.rb deleted file mode 100644 index e76cb384..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/test/metadata.rb +++ /dev/null @@ -1,6 +0,0 @@ -name "test" -description "le test cookbook" -version "1.0.0" -depends "normal" -depends "future" -# depends "hybrid" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/test/recipes/default.rb b/cookbooks/compat_resource/spec/data/cookbooks/test/recipes/default.rb deleted file mode 100644 index 218d855e..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/test/recipes/default.rb +++ /dev/null @@ -1,13 +0,0 @@ -normal_resource 'blah' do - x 'hi' -end -# normal_hwrp 'blah2' do -# x 'hi2' -# end -future_resource 'blah3' do - x 'hi3' -end -future_custom_resource 'blah4' do - x 'hi4' -end -include_recipe 'future::declare_resource' diff --git a/cookbooks/compat_resource/spec/data/cookbooks/test/recipes/test.rb b/cookbooks/compat_resource/spec/data/cookbooks/test/recipes/test.rb deleted file mode 100644 index 12bee341..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/test/recipes/test.rb +++ /dev/null @@ -1,41 +0,0 @@ -future_resource 'sets neither x nor y' do -end - -future_resource 'sets both x and y' do - x 'hi' - y 10 -end - -future_resource 'sets neither x nor y explicitly' do - x 'hi' - y 10 -end - -future_resource 'sets only y' do - y 20 -end - -future_resource 'deletes resource' do - action :delete -end - -future_resource 'sets x and y via creation' do - x 'hi' - y 20 -end - -future_resource 'deletes resource again' do - action :delete -end - -future_resource 'sets x and y to their defaults via creation' do -end - -future_super_resource 'brings in its defaults' do -end -future_super_resource 'lets you set x and y' do - x 100 - y 200 -end - -Chef.log_deprecation "hi there" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/unmodified/metadata.rb b/cookbooks/compat_resource/spec/data/cookbooks/unmodified/metadata.rb deleted file mode 100644 index d1a9632b..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/unmodified/metadata.rb +++ /dev/null @@ -1,3 +0,0 @@ -name "unmodified" -description "does not depend on compat_resource directly" -version "1.0.0" diff --git a/cookbooks/compat_resource/spec/data/cookbooks/unmodified/recipes/default.rb b/cookbooks/compat_resource/spec/data/cookbooks/unmodified/recipes/default.rb deleted file mode 100644 index d410def5..00000000 --- a/cookbooks/compat_resource/spec/data/cookbooks/unmodified/recipes/default.rb +++ /dev/null @@ -1,13 +0,0 @@ - -file "/tmp/foo.xy" do - action :delete -end - -file "/tmp/foo.xy" do - content "some stuff" - notifies :run, 'execute[true]', :immediately -end - -execute "true" do - not_if "false" -end diff --git a/cookbooks/compat_resource/spec/data/nodes/ettores-mbp.lan.json b/cookbooks/compat_resource/spec/data/nodes/ettores-mbp.lan.json deleted file mode 100644 index b1a7d0b5..00000000 --- a/cookbooks/compat_resource/spec/data/nodes/ettores-mbp.lan.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "name": "ettores-mbp.lan" -} \ No newline at end of file diff --git a/cookbooks/compat_resource/spec/spec_helper.rb b/cookbooks/compat_resource/spec/spec_helper.rb deleted file mode 100644 index ac53786b..00000000 --- a/cookbooks/compat_resource/spec/spec_helper.rb +++ /dev/null @@ -1,10 +0,0 @@ -require 'cheffish/rspec' - -RSpec.configure do |config| - config.filter_run :focus => true - config.run_all_when_everything_filtered = true - - config.before :each do - Chef::Config.reset - end -end diff --git a/cookbooks/compat_resource/tasks/maintainers.rb b/cookbooks/compat_resource/tasks/maintainers.rb deleted file mode 100644 index de461337..00000000 --- a/cookbooks/compat_resource/tasks/maintainers.rb +++ /dev/null @@ -1,76 +0,0 @@ -# -# 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 'rake' - -SOURCE = File.join(File.dirname(__FILE__), '..', 'MAINTAINERS.toml') -TARGET = File.join(File.dirname(__FILE__), '..', 'MAINTAINERS.md') - -begin - require 'tomlrb' - task default: 'maintainers:generate' - - namespace :maintainers do - desc 'Generate MarkDown version of MAINTAINERS file' - task :generate do - @toml = Tomlrb.load_file SOURCE - out = "\n\n" - - out << preamble - out << project_lieutenant - out << all_maintainers - - File.open(TARGET, 'w') do |fn| - fn.write out - end - end - end - -rescue LoadError - STDERR.puts "\n*** TomlRb not available. Skipping the Maintainers Rake task\n\n" -end - -private - -def preamble - <<-EOL -# #{@toml['Preamble']['title']} -#{@toml['Preamble']['text']} -EOL -end - -def project_lieutenant - <<-EOL -# #{@toml['Org']['Components']['Core']['title']} -#{github_link(@toml['Org']['Components']['Core']['lieutenant'])} - -EOL -end - -def all_maintainers - text = "# Maintainers\n" - @toml['Org']['Components']['Core']['maintainers'].each do |m| - text << "#{github_link(m)}\n" - end - text -end - -def github_link(person) - name = @toml['people'][person]['name'] - github = @toml['people'][person]['github'] - "* [#{name}](https://github.com/#{github})" -end