diff --git a/modules/apt/CHANGELOG.md b/modules/apt/CHANGELOG.md new file mode 100644 index 0000000..bf8553d --- /dev/null +++ b/modules/apt/CHANGELOG.md @@ -0,0 +1,248 @@ +##2014-06-04 - Release 1.5.0 +###Summary + +This release adds support for Ubuntu 14.04. It also includes many new features +and important bugfixes. One huge change is that apt::key was replaced with +apt_key, which allows you to use puppet resource apt_key to inventory keys on +your system. + +Special thanks to daenney, our intrepid unofficial apt maintainer! + +####Features +- Add support for Ubuntu Trusty! +- Add apt::hold define +- Generate valid *.pref files in apt::pin +- Made pin_priority configurable for apt::backports +- Add apt_key type and provider +- Rename "${apt_conf_d}/proxy" to "${apt_conf_d}/01proxy" +- apt::key rewritten to use apt_key type +- Add support for update_tries to apt::update + +####Bugfixes +- Typo fixes +- Fix unattended upgrades +- Removed bogus line when using purge_preferences +- Fix apt::force to upgrade allow packages to be upgraded to the pacakge from the specified release + +##2014-03-04 - Supported Release 1.4.2 +###Summary + +This is a supported release. This release tidies up 1.4.1 and re-enables +support for Ubuntu 10.04 + +####Features + +####Bugfixes +- Fix apt:ppa to include the -y Ubuntu 10.04 requires. +- Documentation changes. +- Test fixups. + +####Known Bugs + +* No known issues. + + + +##2014-02-13 1.4.1 +###Summary +This is a bugfix release. + +####Bugfixes +- Fix apt::force unable to upgrade packages from releases other than its original +- Removed a few refeneces to aptitude instead of apt-get for portability +- Removed call to getparam() due to stdlib dependency +- Correct apt::source template when architecture is provided +- Retry package installs if apt is locked +- Use root to exec in apt::ppa +- Updated tests and converted acceptance tests to beaker + +##2013-10-08 - Release 1.4.0 + +###Summary + +Minor bugfix and allow the timeout to be adjusted. + +####Features +- Add an `updates_timeout` to apt::params + +####Bugfixes +- Ensure apt::ppa can read a ppa removed by hand. + + +##2013-10-08 - Release 1.3.0 +###Summary + +This major feature in this release is the new apt::unattended_upgrades class, +allowing you to handle Ubuntu's unattended feature. This allows you to select +specific packages to automatically upgrade without any further user +involvement. + +In addition we extend our Wheezy support, add proxy support to apt:ppa and do +various cleanups and tweaks. + +####Features +- Add apt::unattended_upgrades support for Ubuntu. +- Add wheezy backports support. +- Use the geoDNS http.debian.net instead of the main debian ftp server. +- Add `options` parameter to apt::ppa in order to pass options to apt-add-repository command. +- Add proxy support for apt::ppa (uses proxy_host and proxy_port from apt). + +####Bugfixes +- Fix regsubst() calls to quote single letters (for future parser). +- Fix lint warnings and other misc cleanup. + + +##2013-07-03 - Release 1.2.0 + +####Features +- Add geppetto `.project` natures +- Add GH auto-release +- Add `apt::key::key_options` parameter +- Add complex pin support using distribution properties for `apt::pin` via new properties: + - `apt::pin::codename` + - `apt::pin::release_version` + - `apt::pin::component` + - `apt::pin::originator` + - `apt::pin::label` +- Add source architecture support to `apt::source::architecture` + +####Bugfixes +- Use apt-get instead of aptitude in apt::force +- Update default backports location +- Add dependency for required packages before apt-get update + + +##2013-06-02 - Release 1.1.1 +###Summary + +This is a bug fix release that resolves a number of issues: + +* By changing template variable usage, we remove the deprecation warnings + for Puppet 3.2.x +* Fixed proxy file removal, when proxy absent + +Some documentation, style and whitespaces changes were also merged. This +release also introduced proper rspec-puppet unit testing on Travis-CI to help +reduce regression. + +Thanks to all the community contributors below that made this patch possible. + +#### Detail Changes + +* fix minor comment type (Chris Rutter) +* whitespace fixes (Michael Moll) +* Update travis config file (William Van Hevelingen) +* Build all branches on travis (William Van Hevelingen) +* Standardize travis.yml on pattern introduced in stdlib (William Van Hevelingen) +* Updated content to conform to README best practices template (Lauren Rother) +* Fix apt::release example in readme (Brian Galey) +* add @ to variables in template (Peter Hoeg) +* Remove deprecation warnings for pin.pref.erb as well (Ken Barber) +* Update travis.yml to latest versions of puppet (Ken Barber) +* Fix proxy file removal (Scott Barber) +* Add spec test for removing proxy configuration (Dean Reilly) +* Fix apt::key listing longer than 8 chars (Benjamin Knofe) + + + + +## Release 1.1.0 +###Summary + +This release includes Ubuntu 12.10 (Quantal) support for PPAs. + +--- + +##2012-05-25 - Puppet Labs - Release 0.0.4 +###Summary + + * Fix ppa list filename when there is a period in the PPA name + * Add .pref extension to apt preferences files + * Allow preferences to be purged + * Extend pin support + + +##2012-05-04 - Puppet Labs - Release 0.0.3 +###Summary + + * only invoke apt-get update once + * only install python-software-properties if a ppa is added + * support 'ensure => absent' for all defined types + * add apt::conf + * add apt::backports + * fixed Modulefile for module tool dependency resolution + * configure proxy before doing apt-get update + * use apt-get update instead of aptitude for apt::ppa + * add support to pin release + + +##2012-03-26 - Puppet Labs - Release 0.0.2 +###Summary + +* 41cedbb (#13261) Add real examples to smoke tests. +* d159a78 (#13261) Add key.pp smoke test +* 7116c7a (#13261) Replace foo source with puppetlabs source +* 1ead0bf Ignore pkg directory. +* 9c13872 (#13289) Fix some more style violations +* 0ea4ffa (#13289) Change test scaffolding to use a module & manifest dir fixture path +* a758247 (#13289) Clean up style violations and fix corresponding tests +* 99c3fd3 (#13289) Add puppet lint tests to Rakefile +* 5148cbf (#13125) Apt keys should be case insensitive +* b9607a4 Convert apt::key to use anchors + + +##2012-03-07 - Puppet Labs - Release 0.0.1 +###Summary + +* d4fec56 Modify apt::source release parameter test +* 1132a07 (#12917) Add contributors to README +* 8cdaf85 (#12823) Add apt::key defined type and modify apt::source to use it +* 7c0d10b (#12809) $release should use $lsbdistcodename and fall back to manual input +* be2cc3e (#12522) Adjust spec test for splitting purge +* 7dc60ae (#12522) Split purge option to spare sources.list +* 9059c4e Fix source specs to test all key permutations +* 8acb202 Add test for python-software-properties package +* a4af11f Check if python-software-properties is defined before attempting to define it. +* 1dcbf3d Add tests for required_packages change +* f3735d2 Allow duplicate $required_packages +* 74c8371 (#12430) Add tests for changes to apt module +* 97ebb2d Test two sources with the same key +* 1160bcd (#12526) Add ability to reverse apt { disable_keys => true } +* 2842d73 Add Modulefile to puppet-apt +* c657742 Allow the use of the same key in multiple sources +* 8c27963 (#12522) Adding purge option to apt class +* 997c9fd (#12529) Add unit test for apt proxy settings +* 50f3cca (#12529) Add parameter to support setting a proxy for apt +* d522877 (#12094) Replace chained .with_* with a hash +* 8cf1bd0 (#12094) Remove deprecated spec.opts file +* 2d688f4 (#12094) Add rspec-puppet tests for apt +* 0fb5f78 (#12094) Replace name with path in file resources +* f759bc0 (#11953) Apt::force passes $version to aptitude +* f71db53 (#11413) Add spec test for apt::force to verify changes to unless +* 2f5d317 (#11413) Update dpkg query used by apt::force +* cf6caa1 (#10451) Add test coverage to apt::ppa +* 0dd697d include_src parameter in example; Whitespace cleanup +* b662eb8 fix typos in "repositories" +* 1be7457 Fix (#10451) - apt::ppa fails to "apt-get update" when new PPA source is added +* 864302a Set the pin priority before adding the source (Fix #10449) +* 1de4e0a Refactored as per mlitteken +* 1af9a13 Added some crazy bash madness to check if the ppa is installed already. Otherwise the manifest tries to add it on every run! +* 52ca73e (#8720) Replace Apt::Ppa with Apt::Builddep +* 5c05fa0 added builddep command. +* a11af50 added the ability to specify the content of a key +* c42db0f Fixes ppa test. +* 77d2b0d reformatted whitespace to match recommended style of 2 space indentation. +* 27ebdfc ignore swap files. +* 377d58a added smoke tests for module. +* 18f614b reformatted apt::ppa according to recommended style. +* d8a1e4e Created a params class to hold global data. +* 636ae85 Added two params for apt class +* 148fc73 Update LICENSE. +* ed2d19e Support ability to add more than one PPA +* 420d537 Add call to apt-update after add-apt-repository in apt::ppa +* 945be77 Add package definition for python-software-properties +* 71fc425 Abs paths for all commands +* 9d51cd1 Adding LICENSE +* 71796e3 Heading fix in README +* 87777d8 Typo in README +* f848bac First commit diff --git a/modules/apt/Gemfile b/modules/apt/Gemfile new file mode 100644 index 0000000..1af60fc --- /dev/null +++ b/modules/apt/Gemfile @@ -0,0 +1,18 @@ +source ENV['GEM_SOURCE'] || 'https://rubygems.org' + +group :development, :test do + gem 'rake', '10.1.1', :require => false + gem 'pry', :require => false + gem 'rspec-puppet', :require => false + gem 'puppet-lint', :require => false + gem 'puppetlabs_spec_helper', :require => false + gem 'serverspec', :require => false + gem 'beaker', :require => false + gem 'beaker-rspec', :require => false +end + +if puppetversion = ENV['PUPPET_GEM_VERSION'] + gem 'puppet', puppetversion, :require => false +else + gem 'puppet', :require => false +end diff --git a/modules/apt/Gemfile.lock b/modules/apt/Gemfile.lock new file mode 100644 index 0000000..e96f32d --- /dev/null +++ b/modules/apt/Gemfile.lock @@ -0,0 +1,152 @@ +GEM + remote: https://rubygems.org/ + specs: + CFPropertyList (2.2.7) + addressable (2.3.6) + autoparse (0.3.3) + addressable (>= 2.3.1) + extlib (>= 0.9.15) + multi_json (>= 1.0.0) + aws-sdk (1.39.0) + json (~> 1.4) + nokogiri (>= 1.4.4) + beaker (1.10.0) + aws-sdk (~> 1.38) + blimpy (~> 0.6) + fission (~> 0.4) + google-api-client (~> 0.6.4) + inifile (~> 2.0) + json (~> 1.8) + mime-types (~> 1.25) + net-scp (~> 1.1) + net-ssh (~> 2.6) + nokogiri (= 1.5.10) + rbvmomi (= 1.8.1) + unf (~> 0.1) + beaker-rspec (2.2.3) + beaker (~> 1.10.0) + rspec (~> 2.14) + serverspec (~> 1.0.0) + specinfra (~> 1.0.0) + blimpy (0.6.7) + fog + minitar + thor + builder (3.2.2) + coderay (1.1.0) + diff-lcs (1.2.5) + excon (0.31.0) + extlib (0.9.16) + facter (2.0.1) + CFPropertyList (~> 2.2.6) + faraday (0.8.9) + multipart-post (~> 1.2.0) + fission (0.5.0) + CFPropertyList (~> 2.2) + fog (1.19.0) + builder + excon (~> 0.31.0) + formatador (~> 0.2.0) + mime-types + multi_json (~> 1.0) + net-scp (~> 1.1) + net-ssh (>= 2.1.3) + nokogiri (~> 1.5) + ruby-hmac + formatador (0.2.4) + google-api-client (0.6.4) + addressable (>= 2.3.2) + autoparse (>= 0.3.3) + extlib (>= 0.9.15) + faraday (~> 0.8.4) + jwt (>= 0.1.5) + launchy (>= 2.1.1) + multi_json (>= 1.0.0) + signet (~> 0.4.5) + uuidtools (>= 2.1.0) + hiera (1.3.2) + json_pure + highline (1.6.21) + inifile (2.0.2) + json (1.8.1) + json_pure (1.8.1) + jwt (0.1.11) + multi_json (>= 1.5) + launchy (2.4.2) + addressable (~> 2.3) + metaclass (0.0.4) + method_source (0.8.2) + mime-types (1.25.1) + minitar (0.5.4) + mocha (1.0.0) + metaclass (~> 0.0.1) + multi_json (1.9.3) + multipart-post (1.2.0) + net-scp (1.2.1) + net-ssh (>= 2.6.5) + net-ssh (2.9.0) + nokogiri (1.5.10) + pry (0.9.12.6) + coderay (~> 1.0) + method_source (~> 0.8) + slop (~> 3.4) + puppet (3.5.1) + facter (> 1.6, < 3) + hiera (~> 1.0) + json_pure + rgen (~> 0.6.5) + puppet-lint (0.3.2) + puppetlabs_spec_helper (0.4.1) + mocha (>= 0.10.5) + rake + rspec (>= 2.9.0) + rspec-puppet (>= 0.1.1) + rake (10.1.1) + rbvmomi (1.8.1) + builder + nokogiri (>= 1.4.1) + trollop + rgen (0.6.6) + rspec (2.14.1) + rspec-core (~> 2.14.0) + rspec-expectations (~> 2.14.0) + rspec-mocks (~> 2.14.0) + rspec-core (2.14.8) + rspec-expectations (2.14.5) + diff-lcs (>= 1.1.3, < 2.0) + rspec-mocks (2.14.6) + rspec-puppet (1.0.1) + rspec + ruby-hmac (0.4.0) + serverspec (1.0.0) + highline + net-ssh + rspec (~> 2.13) + specinfra (>= 1.0.0) + signet (0.4.5) + addressable (>= 2.2.3) + faraday (~> 0.8.1) + jwt (>= 0.1.5) + multi_json (>= 1.0.0) + slop (3.5.0) + specinfra (1.0.5) + thor (0.19.1) + trollop (2.0) + unf (0.1.4) + unf_ext + unf_ext (0.0.6) + uuidtools (2.1.4) + +PLATFORMS + ruby + +DEPENDENCIES + beaker + beaker-rspec + pry + puppet + puppet-lint + puppetlabs_spec_helper + rake (= 10.1.1) + rspec-puppet + serverspec diff --git a/modules/apt/LICENSE b/modules/apt/LICENSE new file mode 100644 index 0000000..30ce036 --- /dev/null +++ b/modules/apt/LICENSE @@ -0,0 +1,34 @@ +Copyright (c) 2011 Evolving Web Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +Copyright 2014 Puppet Labs + +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/modules/apt/Modulefile b/modules/apt/Modulefile new file mode 100644 index 0000000..45169b3 --- /dev/null +++ b/modules/apt/Modulefile @@ -0,0 +1,14 @@ +name 'puppetlabs-apt' +version '1.5.0' +source 'https://github.com/puppetlabs/puppetlabs-apt' +author 'Evolving Web / Puppet Labs' +license 'Apache License 2.0' +summary 'Puppet Labs Apt Module' +description 'APT Module for Puppet' +project_page 'https://github.com/puppetlabs/puppetlabs-apt' + +## Add dependencies, if any: +#dependency 'puppetlabs/stdlib', '2.x' +# The dependency should be written as above but librarian-puppet +# does not support the expression as the PMT does. +dependency 'puppetlabs/stdlib', '>= 2.2.1' diff --git a/modules/apt/README.md b/modules/apt/README.md new file mode 100644 index 0000000..9443cd5 --- /dev/null +++ b/modules/apt/README.md @@ -0,0 +1,323 @@ +apt +=== + +[![Build Status](https://travis-ci.org/puppetlabs/puppetlabs-apt.png?branch=master)](https://travis-ci.org/puppetlabs/puppetlabs-apt) + +Overview +-------- + +The APT module provides a simple interface for managing APT source, key, and definitions with Puppet. + +Module Description +------------------ + +APT automates obtaining and installing software packages on \*nix systems. + +***Note:** While this module allows the use of short keys, we STRONGLY RECOMMEND that you DO NOT USE short keys, as they pose a serious security issue in that they open you up to collision attacks.* + +Setup +----- + +**What APT affects:** + +* package/service/configuration files for APT + * NOTE: Setting the `purge_preferences` or `purge_preferences_d` parameters to 'true' will destroy any existing configuration that was not declared with puppet. The default for these parameters is 'false'. +* your system's `sources.list` file and `sources.list.d` directory + * NOTE: Setting the `purge_sources_list` and `purge_sources_list_d` parameters to 'true' will destroy any existing content that was not declared with Puppet. The default for these parameters is 'false'. +* system repositories +* authentication keys + +### Beginning with APT + +To begin using the APT module with default parameters, declare the class + + include apt + +Puppet code that uses anything from the APT module requires that the core apt class be declared/\s\+$//e + +Usage +----- + +Using the APT module consists predominantly in declaring classes that provide desired functionality and features. + +### apt + +`apt` provides a number of common resources and options that are shared by the various defined types in this module, so you MUST always include this class in your manifests. + +The parameters for `apt` are not required in general and are predominantly for development environment use-cases. + + class { 'apt': + always_apt_update => false, + disable_keys => undef, + proxy_host => false, + proxy_port => '8080', + purge_sources_list => false, + purge_sources_list_d => false, + purge_preferences_d => false, + update_timeout => undef + } + +Puppet will manage your system's `sources.list` file and `sources.list.d` directory but will do its best to respect existing content. + +If you declare your apt class with `purge_sources_list`, `purge_sources_list_d`, `purge_preferences` and `purge_preferences_d` set to 'true', Puppet will unapologetically purge any existing content it finds that wasn't declared with Puppet. + +### apt::builddep + +Installs the build depends of a specified package. + + apt::builddep { 'glusterfs-server': } + +### apt::force + +Forces a package to be installed from a specific release. This class is particularly useful when using repositories, like Debian, that are unstable in Ubuntu. + + apt::force { 'glusterfs-server': + release => 'unstable', + version => '3.0.3', + require => Apt::Source['debian_unstable'], + } + +### apt_key + +A native Puppet type and provider for managing GPG keys for APT is provided by +this module. + + apt_key { 'puppetlabs': + ensure => 'present', + id => '4BD6EC30', + } + +You can additionally set the following attributes: + + * `source`: HTTP, HTTPS or FTP location of a GPG key or path to a file on the + target host; + * `content`: Instead of pointing to a file, pass the key in as a string; + * `server`: The GPG key server to use. It defaults to *keyserver.ubuntu.com*; + * `keyserver_options`: Additional options to pass to `--keyserver`. + +Because it is a native type it can be used in and queried for with MCollective. + +### apt::key + +Adds a key to the list of keys used by APT to authenticate packages. This type +uses the aforementioned `apt_key` native type. As such it no longer requires +the wget command that the old implementation depended on. + + apt::key { 'puppetlabs': + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + } + + apt::key { 'jenkins': + key => 'D50582E6', + key_source => 'http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key', + } + +### apt::pin + +Adds an apt pin for a certain release. + + apt::pin { 'karmic': priority => 700 } + apt::pin { 'karmic-updates': priority => 700 } + apt::pin { 'karmic-security': priority => 700 } + +Note you can also specifying more complex pins using distribution properties. + + apt::pin { 'stable': + priority => -10, + originator => 'Debian', + release_version => '3.0', + component => 'main', + label => 'Debian' + } + +If you wish to pin a number of packages you may specify the packages as a space +delimited string using the `packages` attribute or pass in an array of package +names. + +### apt::hold + +When you wish to hold a package in Puppet is should be done by passing in +'held' as the ensure attribute to the package resource. However, a lot of +public modules do not take this into account and generally do not work well +with an ensure of 'held'. + +There is an additional issue that when Puppet is told to hold a package, it +will hold it at the current version installed, there is no way to tell it in +one go to install a specific version and then hold that version without using +an exec resource that wraps `dpkg --set-selections` or `apt-mark`. + +At first glance this could also be solved by just passing the version required +to the ensure attribute but that only means that Puppet will install that +version once it processes that package. It does not inform apt that we want +this package to be held. In other words; if another package somehow wants to +upgrade this one (because of a version requirement in a dependency), apt +should not allow it. + +In order to solve this you can use apt::hold. It's implemented by creating +a preferences file with a priority of 1001, meaning that under normal +circumstances this preference will always win. Because the priority is > 1000 +apt will interpret this as 'this should be the version installed and I am +allowed to downgrade the current package if needed'. + +With this you can now set a package's ensure attribute to 'latest' but still +get the version specified by apt::hold. You can do it like this: + + apt::hold { 'vim': + version => '2:7.3.547-7', + } + +Since you might just want to hold Vim at version 7.3 and not care about the +rest you can also pass in a version with a glob: + + apt::hold { 'vim': + version => '2:7.3.*', + } + +### apt::ppa + +Adds a ppa repository using `add-apt-repository`. + + apt::ppa { 'ppa:drizzle-developers/ppa': } + +### apt::release + +Sets the default apt release. This class is particularly useful when using repositories, like Debian, that are unstable in Ubuntu. + + class { 'apt::release': + release_id => 'precise', + } + +### apt::source + +Adds an apt source to `/etc/apt/sources.list.d/`. + + apt::source { 'debian_unstable': + location => 'http://debian.mirror.iweb.ca/debian/', + release => 'unstable', + repos => 'main contrib non-free', + required_packages => 'debian-keyring debian-archive-keyring', + key => '46925553', + key_server => 'subkeys.pgp.net', + pin => '-10', + include_src => true + } + +If you would like to configure your system so the source is the Puppet Labs APT repository + + apt::source { 'puppetlabs': + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + } + + +#### Hiera example +
+apt::sources:
+  'debian_unstable':
+      location: 'http://debian.mirror.iweb.ca/debian/'
+      release: 'unstable'
+      repos: 'main contrib non-free'
+      required_packages: 'debian-keyring debian-archive-keyring'
+      key: '55BE302B'
+      key_server: 'subkeys.pgp.net'
+      pin: '-10'
+      include_src: 'true'
+
+  'puppetlabs':
+      location: 'http://apt.puppetlabs.com'
+      repos: 'main'
+      key: '4BD6EC30'
+      key_server: 'pgp.mit.edu'
+
+ +### Testing + +The APT module is mostly a collection of defined resource types, which provide reusable logic that can be leveraged to manage APT. It does provide smoke tests for testing functionality on a target system, as well as spec tests for checking a compiled catalog against an expected set of resources. + +#### Example Test + +This test will set up a Puppet Labs apt repository. Start by creating a new smoke test in the apt module's test folder. Call it puppetlabs-apt.pp. Inside, declare a single resource representing the Puppet Labs APT source and gpg key + + apt::source { 'puppetlabs': + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + } + +This resource creates an apt source named puppetlabs and gives Puppet information about the repository's location and key used to sign its packages. Puppet leverages Facter to determine the appropriate release, but you can set it directly by adding the release type. + +Check your smoke test for syntax errors + + $ puppet parser validate tests/puppetlabs-apt.pp + +If you receive no output from that command, it means nothing is wrong. Then apply the code + + $ puppet apply --verbose tests/puppetlabs-apt.pp + notice: /Stage[main]//Apt::Source[puppetlabs]/File[puppetlabs.list]/ensure: defined content as '{md5}3be1da4923fb910f1102a233b77e982e' + info: /Stage[main]//Apt::Source[puppetlabs]/File[puppetlabs.list]: Scheduling refresh of Exec[puppetlabs apt update] + notice: /Stage[main]//Apt::Source[puppetlabs]/Exec[puppetlabs apt update]: Triggered 'refresh' from 1 events> + +The above example used a smoke test to easily lay out a resource declaration and apply it on your system. In production, you may want to declare your APT sources inside the classes where they’re needed. + +Implementation +-------------- + +### apt::backports + +Adds the necessary components to get backports for Ubuntu and Debian. The release name defaults to `$lsbdistcodename`. Setting this manually can cause undefined behavior (read: universe exploding). + +By default this class drops a Pin-file for Backports pinning it to a priority of 200, lower than the normal Debian archive which gets a priority of 500 to ensure your packages with `ensure => latest` don't get magically upgraded from Backports without your explicit say-so. + +If you raise the priority through the `pin_priority` parameter to *500*, identical to the rest of the Debian mirrors, normal policy goes into effect and the newest version wins/becomes the candidate apt will want to install or upgrade to. This means that if a package is available from Backports it and its dependencies will be pulled in from Backports unless you explicitly set the `ensure` attribute of the `package` resource to `installed`/`present` or a specific version. + +Limitations +----------- + +This module should work across all versions of Debian/Ubuntu and support all major APT repository management features. + +Development +------------ + +Puppet Labs modules on the Puppet Forge are open projects, and community contributions are essential for keeping them great. We can’t access the huge number of platforms and myriad of hardware, software, and deployment configurations that Puppet is intended to serve. + +We want to keep it as easy as possible to contribute changes so that our modules work in your environment. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. + +You can read the complete module contribution guide [on the Puppet Labs wiki.](http://projects.puppetlabs.com/projects/module-site/wiki/Module_contributing) + +License +------- + +The original code for this module comes from Evolving Web and was licensed under the MIT license. Code added since the fork of this module is licensed under the Apache 2.0 License like the rest of the Puppet Labs products. + +The LICENSE contains both licenses. + +Contributors +------------ + +A lot of great people have contributed to this module. A somewhat current list follows: + +* Ben Godfrey +* Branan Purvine-Riley +* Christian G. Warden +* Dan Bode +* Daniel Tremblay +* Garrett Honeycutt +* Jeff Wallace +* Ken Barber +* Matthaus Litteken +* Matthias Pigulla +* Monty Taylor +* Peter Drake +* Reid Vandewiele +* Robert Navarro +* Ryan Coleman +* Scott McLeod +* Spencer Krum +* William Van Hevelingen +* Zach Leslie +* Daniele Sluijters +* Daniel Paulus diff --git a/modules/apt/Rakefile b/modules/apt/Rakefile new file mode 100644 index 0000000..5868545 --- /dev/null +++ b/modules/apt/Rakefile @@ -0,0 +1,10 @@ +require 'puppetlabs_spec_helper/rake_tasks' +require 'puppet-lint/tasks/puppet-lint' + +PuppetLint.configuration.fail_on_warnings +PuppetLint.configuration.send('disable_80chars') +PuppetLint.configuration.send('disable_class_inherits_from_params_class') +PuppetLint.configuration.send('disable_class_parameter_defaults') +PuppetLint.configuration.send('disable_documentation') +PuppetLint.configuration.send('disable_single_quote_string_with_variables') +PuppetLint.configuration.ignore_paths = ["spec/**/*.pp", "pkg/**/*.pp"] diff --git a/modules/apt/checksums.json b/modules/apt/checksums.json new file mode 100644 index 0000000..92fea70 --- /dev/null +++ b/modules/apt/checksums.json @@ -0,0 +1,84 @@ +{ + "CHANGELOG.md": "2edd771d2aa653812ac9f58ddb8a8dd6", + "Gemfile": "0d209c30c4451b1cdce50967b396a8cb", + "Gemfile.lock": "3cc280f2c4a11d8e1a3c010a5e503b24", + "LICENSE": "c236a08bf88c5c8e480957038c869ed1", + "Modulefile": "e2ddc834592f3bd9dc229c3b7edda549", + "README.md": "0047d76fa8c10a673d556f5c099a1113", + "Rakefile": "de8eeacfe1fbbc6a6f4d89adfc98bcaf", + "lib/puppet/provider/apt_key/apt_key.rb": "7c1517b4ec04c5574f078b1651ed3c5c", + "lib/puppet/type/apt_key.rb": "e638201e7e299a5061c39e1045396887", + "lib/puppet_x/apt_key/patch_openuri.rb": "951bad007a3b5db035be069c1d1c9c09", + "manifests/backports.pp": "75523c9a3573830d5c364dba918a0511", + "manifests/builddep.pp": "4f313b5140c84aa7d5793b5a073c30dd", + "manifests/conf.pp": "5ddf258195d414d93284dfd281a8d6e3", + "manifests/debian/testing.pp": "1d7b2a7dfafa08eb47982cbf03cac5b9", + "manifests/debian/unstable.pp": "cf5a4e7ecadb34856bb6fed17e58c822", + "manifests/force.pp": "2e75773abb485ee64c6ebb8b284cce6d", + "manifests/hold.pp": "817999daec857e6305b22b4894da81aa", + "manifests/init.pp": "7a676234a6d693f88a91fac986490b6b", + "manifests/key.pp": "e1427a4d902b64a296dd16fbaa2063ef", + "manifests/params.pp": "4ed486272bafc452e506b98abe0f1149", + "manifests/pin.pp": "4bb5f0e75987fb69d1e617130412a6a3", + "manifests/ppa.pp": "1252cdd4d5fad97e0d94e9556f038db1", + "manifests/release.pp": "427f3ee70a6a1e55fa291e58655bd5d9", + "manifests/source.pp": "9f36b03fde5b1148d01c89677eee6b0e", + "manifests/unattended_upgrades.pp": "aaf5e4c350800d2d77faac0430c4c598", + "manifests/update.pp": "2950af6e8e4a4b30ecdf2921d7f01fee", + "metadata.json": "9e77b5b32cd0c0379601b3c6f15c4f7c", + "spec/acceptance/apt_builddep_spec.rb": "fb7ede528790507df42032d77eb74211", + "spec/acceptance/apt_key_provider_spec.rb": "bfc96c53af3e7ea1e1f3694466a40e86", + "spec/acceptance/apt_key_spec.rb": "5a5a6586db3010a0876dfa4ee29e3155", + "spec/acceptance/apt_ppa_spec.rb": "65efac5d8fa1baaed823ecd9548565c3", + "spec/acceptance/apt_source_spec.rb": "dc47437fa48d7cc82900ceba4d6d1f26", + "spec/acceptance/apt_spec.rb": "242e16421f4aaeddb57666fa6c685eaf", + "spec/acceptance/backports_spec.rb": "e2e4ba8091f1e3e168b6be376d22b961", + "spec/acceptance/class_spec.rb": "7efb1890650fea7a303ed74f3fa6fff1", + "spec/acceptance/conf_spec.rb": "ce961c5ace4de40df1b131a7e600e704", + "spec/acceptance/force_spec.rb": "e504f250caf7614099d9c1bb71125d63", + "spec/acceptance/nodesets/debian-70rc1-x64.yml": "715f798e696d3582c66d13f0e8e5f009", + "spec/acceptance/nodesets/debian-73-x64.yml": "b44b7146a828c37482c06879862fb5d9", + "spec/acceptance/nodesets/default.yml": "e27bb4d7526ad3c7a1c4aeb87decec15", + "spec/acceptance/nodesets/ubuntu-server-10044-x64.yml": "edd30a624fabfcae11b876ec3167383d", + "spec/acceptance/nodesets/ubuntu-server-12042-x64.yml": "344002a1813eb994a0d854981692ea5b", + "spec/acceptance/nodesets/ubuntu-server-1404-x64.yml": "5f0aed10098ac5b78e4217bb27c7aaf0", + "spec/acceptance/pin_spec.rb": "b91328114476900d1707f60953e86807", + "spec/acceptance/release_spec.rb": "171c6a92d12c47fffc255cbd41e53f88", + "spec/acceptance/unattended_upgrade_spec.rb": "2f24ec935bc070964f8eb231d2e7885d", + "spec/acceptance/unsupported_spec.rb": "a791d7f6fdeb4cc6dc8e32cfad88f4c1", + "spec/classes/apt_spec.rb": "93443e5cbe858e0a77cb94fe54bf7e78", + "spec/classes/backports_spec.rb": "fe8d8f03cacaed1134cd8b612f7ee139", + "spec/classes/debian_testing_spec.rb": "939bc900d8d9bc82e6c378b21b56035a", + "spec/classes/debian_unstable_spec.rb": "ac7e6a5bd599fd54ddc91a20c9777a90", + "spec/classes/init_spec.rb": "c08cdc9c025b1b343911d87ce4838bd2", + "spec/classes/params_spec.rb": "d5e4ef728174328113c75fbf6de85692", + "spec/classes/release_spec.rb": "bc3cce54aca2fef36a60fdfa0ae24488", + "spec/classes/unattended_upgrades_spec.rb": "686780f08979420bfe34495227fe284b", + "spec/defines/builddep_spec.rb": "99370325f64faa5034b79d113b2ef962", + "spec/defines/conf_spec.rb": "9c8fce10a10bb4b607d926ebfd6a6dcc", + "spec/defines/force_spec.rb": "12dce7d0903d1af82bba97a5d0bfa0b5", + "spec/defines/hold_spec.rb": "dd0863c74fff804900c8b390e820bdab", + "spec/defines/key_spec.rb": "6ba8391d8fac22fb6d265cea56c7d823", + "spec/defines/pin_spec.rb": "74e280e91fdfa7099d8e834dcc1ef14f", + "spec/defines/ppa_spec.rb": "aaa2c1e762fe14d2b78d63133e04501c", + "spec/defines/source_spec.rb": "054028467c44ec1002e3a4de9cf563d6", + "spec/spec_helper.rb": "0db89c9a486df193c0e40095422e19dc", + "spec/spec_helper_acceptance.rb": "fc4a89c45d1812b03459bd70139ce2c7", + "spec/unit/puppet/type/apt_key_spec.rb": "61ac4b1a237a7666acd517598bbc8667", + "templates/10periodic.erb": "2aeea866a39f19a62254abbb4f1bc59d", + "templates/50unattended-upgrades.erb": "78ff1ebf80099450fc989de20ea7153f", + "templates/pin.pref.erb": "50ad71970336e20e2f0fb017034af453", + "templates/source.list.erb": "7df942e41d3cefff84ef9410e6fdd626", + "tests/builddep.pp": "4773f57072111e58f2ed833fa4489a88", + "tests/debian/testing.pp": "1cbee56baddd6a91d981db8fddec70fb", + "tests/debian/unstable.pp": "4b2a090afeb315752262386f4dbcd8ca", + "tests/force.pp": "896f0e2da2c3eebda56fbf5461b90991", + "tests/init.pp": "551138eb704e71ab3687932dda429a81", + "tests/key.pp": "371a695e1332d51a38e283a87be52798", + "tests/params.pp": "900db40f3fc84b0be173278df2ebff35", + "tests/pin.pp": "4b4c3612d75a19dba8eb7227070fa4ab", + "tests/ppa.pp": "b902cce8159128b5e8b21bed540743ff", + "tests/release.pp": "53ce5debe6fa5bee42821767599cc768", + "tests/source.pp": "123b6208bc80c80f887cac6d563c04f1", + "tests/unattended_upgrades.pp": "ae03b24ced8748887178d2357b4bdb53" +} \ No newline at end of file diff --git a/modules/apt/lib/puppet/provider/apt_key/apt_key.rb b/modules/apt/lib/puppet/provider/apt_key/apt_key.rb new file mode 100644 index 0000000..f8d4072 --- /dev/null +++ b/modules/apt/lib/puppet/provider/apt_key/apt_key.rb @@ -0,0 +1,179 @@ +require 'date' +require 'open-uri' +require 'net/ftp' +require 'tempfile' + +if RUBY_VERSION == '1.8.7' + # Mothers cry, puppies die and Ruby 1.8.7's open-uri needs to be + # monkeypatched to support passing in :ftp_passive_mode. + require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', + 'puppet_x', 'apt_key', 'patch_openuri.rb')) + OpenURI::Options.merge!({:ftp_active_mode => false,}) +end + +Puppet::Type.type(:apt_key).provide(:apt_key) do + + KEY_LINE = { + :date => '[0-9]{4}-[0-9]{2}-[0-9]{2}', + :key_type => '(R|D)', + :key_size => '\d{4}', + :key_id => '[0-9a-fA-F]+', + :expires => 'expire(d|s)', + } + + confine :osfamily => :debian + defaultfor :osfamily => :debian + commands :apt_key => 'apt-key' + + def self.instances + key_array = apt_key('list').split("\n").collect do |line| + line_hash = key_line_hash(line) + next unless line_hash + expired = false + + if line_hash[:key_expiry] + expired = Date.today > Date.parse(line_hash[:key_expiry]) + end + + new( + :name => line_hash[:key_id], + :id => line_hash[:key_id], + :ensure => :present, + :expired => expired, + :expiry => line_hash[:key_expiry], + :size => line_hash[:key_size], + :type => line_hash[:key_type] == 'R' ? :rsa : :dsa, + :created => line_hash[:key_created] + ) + end + key_array.compact! + end + + def self.prefetch(resources) + apt_keys = instances + resources.keys.each do |name| + if provider = apt_keys.find{ |key| key.name == name } + resources[name].provider = provider + end + end + end + + def self.key_line_hash(line) + line_array = line.match(key_line_regexp).to_a + return nil if line_array.length < 5 + + return_hash = { + :key_id => line_array[3], + :key_size => line_array[1], + :key_type => line_array[2], + :key_created => line_array[4], + :key_expiry => nil, + } + + return_hash[:key_expiry] = line_array[7] if line_array.length == 8 + return return_hash + end + + def self.key_line_regexp + # This regexp is trying to match the following output + # pub 4096R/4BD6EC30 2010-07-10 [expires: 2016-07-08] + # pub 1024D/CD2EFD2A 2009-12-15 + regexp = /\A + pub # match only the public key, not signatures + \s+ # bunch of spaces after that + (#{KEY_LINE[:key_size]}) # size of the key, usually a multiple of 1024 + #{KEY_LINE[:key_type]} # type of the key, usually R or D + \/ # separator between key_type and key_id + (#{KEY_LINE[:key_id]}) # hex id of the key + \s+ # bunch of spaces after that + (#{KEY_LINE[:date]}) # date the key was added to the keyring + # following an optional block which indicates if the key has an expiration + # date and if it has expired yet + ( + \s+ # again with thes paces + \[ # we open with a square bracket + #{KEY_LINE[:expires]} # expires or expired + \: # a colon + \s+ # more spaces + (#{KEY_LINE[:date]}) # date indicating key expiry + \] # we close with a square bracket + )? # end of the optional block + \Z/x + regexp + end + + def source_to_file(value) + if URI::parse(value).scheme.nil? + fail("The file #{value} does not exist") unless File.exists?(value) + value + else + begin + key = open(value, :ftp_active_mode => false).read + rescue OpenURI::HTTPError, Net::FTPPermError => e + fail("#{e.message} for #{resource[:source]}") + rescue SocketError + fail("could not resolve #{resource[:source]}") + else + tempfile(key) + end + end + end + + def tempfile(content) + file = Tempfile.new('apt_key') + file.write content + file.close + file.path + end + + def exists? + @property_hash[:ensure] == :present + end + + def create + command = [] + if resource[:source].nil? and resource[:content].nil? + # Breaking up the command like this is needed because it blows up + # if --recv-keys isn't the last argument. + command.push('adv', '--keyserver', resource[:server]) + unless resource[:keyserver_options].nil? + command.push('--keyserver-options', resource[:keyserver_options]) + end + command.push('--recv-keys', resource[:id]) + elsif resource[:content] + command.push('add', tempfile(resource[:content])) + elsif resource[:source] + command.push('add', source_to_file(resource[:source])) + # In case we really screwed up, better safe than sorry. + else + fail("an unexpected condition occurred while trying to add the key: #{resource[:id]}") + end + apt_key(command) + @property_hash[:ensure] = :present + end + + def destroy + apt_key('del', resource[:id]) + @property_hash.clear + end + + def read_only(value) + fail('This is a read-only property.') + end + + mk_resource_methods + + # Needed until PUP-1470 is fixed and we can drop support for Puppet versions + # before that. + def expired + @property_hash[:expired] + end + + # Alias the setters of read-only properties + # to the read_only function. + alias :created= :read_only + alias :expired= :read_only + alias :expiry= :read_only + alias :size= :read_only + alias :type= :read_only +end diff --git a/modules/apt/lib/puppet/type/apt_key.rb b/modules/apt/lib/puppet/type/apt_key.rb new file mode 100644 index 0000000..fa7b0c6 --- /dev/null +++ b/modules/apt/lib/puppet/type/apt_key.rb @@ -0,0 +1,112 @@ +require 'pathname' + +Puppet::Type.newtype(:apt_key) do + + @doc = <<-EOS + This type provides Puppet with the capabilities to manage GPG keys needed + by apt to perform package validation. Apt has it's own GPG keyring that can + be manipulated through the `apt-key` command. + + apt_key { '4BD6EC30': + source => 'http://apt.puppetlabs.com/pubkey.gpg' + } + + **Autorequires**: + + If Puppet is given the location of a key file which looks like an absolute + path this type will autorequire that file. + EOS + + ensurable + + validate do + if self[:content] and self[:source] + fail('The properties content and source are mutually exclusive.') + end + end + + newparam(:id, :namevar => true) do + desc 'The ID of the key you want to manage.' + # GPG key ID's should be either 32-bit (short) or 64-bit (long) key ID's + # and may start with the optional 0x + newvalues(/\A(0x)?[0-9a-fA-F]{8}\Z/, /\A(0x)?[0-9a-fA-F]{16}\Z/) + munge do |value| + if value.start_with?('0x') + id = value.partition('0x').last.upcase + else + id = value.upcase + end + if id.length == 16 + id[8..-1] + else + id + end + end + end + + newparam(:content) do + desc 'The content of, or string representing, a GPG key.' + end + + newparam(:source) do + desc 'Location of a GPG key file, /path/to/file, ftp://, http:// or https://' + newvalues(/\Ahttps?:\/\//, /\Aftp:\/\//, /\A\/\w+/) + end + + autorequire(:file) do + if self[:source] and Pathname.new(self[:source]).absolute? + self[:source] + end + end + + newparam(:server) do + desc 'The key server to fetch the key from based on the ID.' + defaultto :'keyserver.ubuntu.com' + # Need to validate this, preferably through stdlib is_fqdn + # but still working on getting to that. + end + + newparam(:keyserver_options) do + desc 'Additional options to pass to apt-key\'s --keyserver-options.' + end + + newproperty(:expired) do + desc <<-EOS + Indicates if the key has expired. + + This property is read-only. + EOS + end + + newproperty(:expiry) do + desc <<-EOS + The date the key will expire, or nil if it has no expiry date. + + This property is read-only. + EOS + end + + newproperty(:size) do + desc <<-EOS + The key size, usually a multiple of 1024. + + This property is read-only. + EOS + end + + newproperty(:type) do + desc <<-EOS + The key type, either RSA or DSA. + + This property is read-only. + EOS + end + + newproperty(:created) do + desc <<-EOS + Date the key was created. + + This property is read-only. + EOS + end +end diff --git a/modules/apt/lib/puppet_x/apt_key/patch_openuri.rb b/modules/apt/lib/puppet_x/apt_key/patch_openuri.rb new file mode 100644 index 0000000..722c7bd --- /dev/null +++ b/modules/apt/lib/puppet_x/apt_key/patch_openuri.rb @@ -0,0 +1,63 @@ +require 'uri' +require 'stringio' +require 'time' + +module URI + class FTP + def buffer_open(buf, proxy, options) # :nodoc: + if proxy + OpenURI.open_http(buf, self, proxy, options) + return + end + require 'net/ftp' + + directories = self.path.split(%r{/}, -1) + directories.shift if directories[0] == '' # strip a field before leading slash + directories.each {|d| + d.gsub!(/%([0-9A-Fa-f][0-9A-Fa-f])/) { [$1].pack("H2") } + } + unless filename = directories.pop + raise ArgumentError, "no filename: #{self.inspect}" + end + directories.each {|d| + if /[\r\n]/ =~ d + raise ArgumentError, "invalid directory: #{d.inspect}" + end + } + if /[\r\n]/ =~ filename + raise ArgumentError, "invalid filename: #{filename.inspect}" + end + typecode = self.typecode + if typecode && /\A[aid]\z/ !~ typecode + raise ArgumentError, "invalid typecode: #{typecode.inspect}" + end + + # The access sequence is defined by RFC 1738 + ftp = Net::FTP.open(self.host) + ftp.passive = true if !options[:ftp_active_mode] + # todo: extract user/passwd from .netrc. + user = 'anonymous' + passwd = nil + user, passwd = self.userinfo.split(/:/) if self.userinfo + ftp.login(user, passwd) + directories.each {|cwd| + ftp.voidcmd("CWD #{cwd}") + } + if typecode + # xxx: typecode D is not handled. + ftp.voidcmd("TYPE #{typecode.upcase}") + end + if options[:content_length_proc] + options[:content_length_proc].call(ftp.size(filename)) + end + ftp.retrbinary("RETR #{filename}", 4096) { |str| + buf << str + options[:progress_proc].call(buf.size) if options[:progress_proc] + } + ftp.close + buf.io.rewind + end + + include OpenURI::OpenRead + end +end diff --git a/modules/apt/manifests/backports.pp b/modules/apt/manifests/backports.pp new file mode 100644 index 0000000..eafa506 --- /dev/null +++ b/modules/apt/manifests/backports.pp @@ -0,0 +1,59 @@ +# This adds the necessary components to get backports for ubuntu and debian +# +# == Parameters +# +# [*release*] +# The ubuntu/debian release name. Defaults to $lsbdistcodename. Setting this +# manually can cause undefined behavior. (Read: universe exploding) +# +# [*pin_priority*] +# _default_: 200 +# +# The priority that should be awarded by default to all packages coming from +# the Debian Backports project. +# +# == Examples +# +# include apt::backports +# +# class { 'apt::backports': +# release => 'natty', +# } +# +# == Authors +# +# Ben Hughes, I think. At least blame him if this goes wrong. +# I just added puppet doc. +# +# == Copyright +# +# Copyright 2011 Puppet Labs Inc, unless otherwise noted. +class apt::backports( + $release = $::lsbdistcodename, + $location = $::apt::params::backports_location, + $pin_priority = 200, +) inherits apt::params { + + if ! is_integer($pin_priority) { + fail('$pin_priority must be an integer') + } + + $release_real = downcase($release) + $key = $::lsbdistid ? { + 'debian' => '46925553', + 'ubuntu' => '437D05B5', + } + $repos = $::lsbdistid ? { + 'debian' => 'main contrib non-free', + 'ubuntu' => 'main universe multiverse restricted', + } + + apt::source { 'backports': + location => $location, + release => "${release_real}-backports", + repos => $repos, + key => $key, + key_server => 'pgp.mit.edu', + pin => $pin_priority, + } +} diff --git a/modules/apt/manifests/builddep.pp b/modules/apt/manifests/builddep.pp new file mode 100644 index 0000000..3294f71 --- /dev/null +++ b/modules/apt/manifests/builddep.pp @@ -0,0 +1,16 @@ +# builddep.pp + +define apt::builddep() { + include apt::update + + exec { "apt-builddep-${name}": + command => "/usr/bin/apt-get -y --force-yes build-dep ${name}", + logoutput => 'on_failure', + notify => Exec['apt_update'], + } + + # Need anchor to provide containment for dependencies. + anchor { "apt::builddep::${name}": + require => Class['apt::update'], + } +} diff --git a/modules/apt/manifests/conf.pp b/modules/apt/manifests/conf.pp new file mode 100644 index 0000000..3c4cb19 --- /dev/null +++ b/modules/apt/manifests/conf.pp @@ -0,0 +1,18 @@ +define apt::conf ( + $content, + $ensure = present, + $priority = '50' +) { + + include apt::params + + $apt_conf_d = $apt::params::apt_conf_d + + file { "${apt_conf_d}/${priority}${name}": + ensure => $ensure, + content => $content, + owner => root, + group => root, + mode => '0644', + } +} diff --git a/modules/apt/manifests/debian/testing.pp b/modules/apt/manifests/debian/testing.pp new file mode 100644 index 0000000..3a82b4f --- /dev/null +++ b/modules/apt/manifests/debian/testing.pp @@ -0,0 +1,21 @@ +# testing.pp + +class apt::debian::testing { + include apt + + # deb http://debian.mirror.iweb.ca/debian/ testing main contrib non-free + # deb-src http://debian.mirror.iweb.ca/debian/ testing main contrib non-free + # Key: 46925553 Server: subkeys.pgp.net + # debian-keyring + # debian-archive-keyring + + apt::source { 'debian_testing': + location => 'http://debian.mirror.iweb.ca/debian/', + release => 'testing', + repos => 'main contrib non-free', + required_packages => 'debian-keyring debian-archive-keyring', + key => '46925553', + key_server => 'subkeys.pgp.net', + pin => '-10', + } +} diff --git a/modules/apt/manifests/debian/unstable.pp b/modules/apt/manifests/debian/unstable.pp new file mode 100644 index 0000000..77df94b --- /dev/null +++ b/modules/apt/manifests/debian/unstable.pp @@ -0,0 +1,21 @@ +# unstable.pp + +class apt::debian::unstable { + include apt + + # deb http://debian.mirror.iweb.ca/debian/ unstable main contrib non-free + # deb-src http://debian.mirror.iweb.ca/debian/ unstable main contrib non-free + # Key: 46925553 Server: subkeys.pgp.net + # debian-keyring + # debian-archive-keyring + + apt::source { 'debian_unstable': + location => 'http://debian.mirror.iweb.ca/debian/', + release => 'unstable', + repos => 'main contrib non-free', + required_packages => 'debian-keyring debian-archive-keyring', + key => '46925553', + key_server => 'subkeys.pgp.net', + pin => '-10', + } +} diff --git a/modules/apt/manifests/force.pp b/modules/apt/manifests/force.pp new file mode 100644 index 0000000..152bb67 --- /dev/null +++ b/modules/apt/manifests/force.pp @@ -0,0 +1,42 @@ +# force.pp +# force a package from a specific release + +define apt::force( + $release = false, + $version = false, + $timeout = 300 +) { + + $provider = $apt::params::provider + + $version_string = $version ? { + false => undef, + default => "=${version}", + } + + $release_string = $release ? { + false => undef, + default => "-t ${release}", + } + + if $version == false { + if $release == false { + $install_check = "/usr/bin/dpkg -s ${name} | grep -q 'Status: install'" + } else { + # If installed version and candidate version differ, this check returns 1 (false). + $install_check = "/usr/bin/test \$(/usr/bin/apt-cache policy -t ${release} ${name} | /bin/grep -E 'Installed|Candidate' | /usr/bin/uniq -s 14 | /usr/bin/wc -l) -eq 1" + } + } else { + if $release == false { + $install_check = "/usr/bin/dpkg -s ${name} | grep -q 'Version: ${version}'" + } else { + $install_check = "/usr/bin/apt-cache policy -t ${release} ${name} | /bin/grep -q 'Installed: ${version}'" + } + } + + exec { "${provider} -y ${release_string} install ${name}${version_string}": + unless => $install_check, + logoutput => 'on_failure', + timeout => $timeout, + } +} diff --git a/modules/apt/manifests/hold.pp b/modules/apt/manifests/hold.pp new file mode 100644 index 0000000..c4016c6 --- /dev/null +++ b/modules/apt/manifests/hold.pp @@ -0,0 +1,54 @@ +# == Define apt::hold +# +# This defined type allows you to hold a package based on the version you +# require. It's implemented by dropping an apt preferences file pinning the +# package to the version you require. +# +# === Parameters +# +# [*version*] +# The version at which you wish to pin a package. +# +# This can either be the full version, such as 4:2.11.8.1-5, or +# a partial version, such as 4:2.11.* +# +# [*package*] +# _default_: +$title+, the title/name of the resource. +# +# Name of the package that apt is to hold. +# +# [*priority*] +# _default_: +1001+ +# +# The default priority of 1001 causes this preference to always win. By +# setting the priority to a number greater than 1000 apt will always install +# this version even if it means downgrading the currently installed version. +define apt::hold( + $version, + $ensure = 'present', + $package = $title, + $priority = 1001, +){ + + validate_string($title) + validate_re($ensure, ['^present|absent',]) + validate_string($package) + validate_string($version) + + if ! is_integer($priority) { + fail('$priority must be an integer') + } + + if $ensure == 'present' { + ::apt::pin { "hold ${package} at ${version}": + packages => $package, + version => $version, + priority => $priority, + } + } else { + ::apt::pin { "hold ${package} at ${version}": + ensure => 'absent', + } + } + +} diff --git a/modules/apt/manifests/init.pp b/modules/apt/manifests/init.pp new file mode 100644 index 0000000..5f5d0ac --- /dev/null +++ b/modules/apt/manifests/init.pp @@ -0,0 +1,154 @@ +# Class: apt +# +# This module manages the initial configuration of apt. +# +# Parameters: +# The parameters listed here are not required in general and were +# added for use cases related to development environments. +# disable_keys - disables the requirement for all packages to be signed +# always_apt_update - rather apt should be updated on every run (intended +# for development environments where package updates are frequent) +# purge_sources_list - Accepts true or false. Defaults to false If set to +# true, Puppet will purge all unmanaged entries from sources.list +# purge_sources_list_d - Accepts true or false. Defaults to false. If set +# to true, Puppet will purge all unmanaged entries from sources.list.d +# update_timeout - Overrides the exec timeout in seconds for apt-get update. +# If not set defaults to Exec's default (300) +# update_tries - Number of times that `apt-get update` will be tried. Use this +# to work around transient DNS and HTTP errors. By default, the command +# will only be run once. +# +# Actions: +# +# Requires: +# puppetlabs/stdlib +# Sample Usage: +# class { 'apt': } + +class apt( + $always_apt_update = false, + $disable_keys = undef, + $proxy_host = undef, + $proxy_port = '8080', + $purge_sources_list = false, + $purge_sources_list_d = false, + $purge_preferences = false, + $purge_preferences_d = false, + $update_timeout = undef, + $update_tries = undef, + $sources = undef +) { + + if $::osfamily != 'Debian' { + fail('This module only works on Debian or derivatives like Ubuntu') + } + + include apt::params + include apt::update + + validate_bool($purge_sources_list, $purge_sources_list_d, + $purge_preferences, $purge_preferences_d) + + $sources_list_content = $purge_sources_list ? { + false => undef, + true => "# Repos managed by puppet.\n", + } + + if $always_apt_update == true { + Exec <| title=='apt_update' |> { + refreshonly => false, + } + } + + $root = $apt::params::root + $apt_conf_d = $apt::params::apt_conf_d + $sources_list_d = $apt::params::sources_list_d + $preferences_d = $apt::params::preferences_d + $provider = $apt::params::provider + + file { 'sources.list': + ensure => present, + path => "${root}/sources.list", + owner => root, + group => root, + mode => '0644', + content => $sources_list_content, + notify => Exec['apt_update'], + } + + file { 'sources.list.d': + ensure => directory, + path => $sources_list_d, + owner => root, + group => root, + purge => $purge_sources_list_d, + recurse => $purge_sources_list_d, + notify => Exec['apt_update'], + } + + if $purge_preferences { + file { 'apt-preferences': + ensure => absent, + path => "${root}/preferences", + } + } + + file { 'preferences.d': + ensure => directory, + path => $preferences_d, + owner => root, + group => root, + purge => $purge_preferences_d, + recurse => $purge_preferences_d, + } + + case $disable_keys { + true: { + file { '99unauth': + ensure => present, + content => "APT::Get::AllowUnauthenticated 1;\n", + path => "${apt_conf_d}/99unauth", + } + } + false: { + file { '99unauth': + ensure => absent, + path => "${apt_conf_d}/99unauth", + } + } + undef: { } # do nothing + default: { fail('Valid values for disable_keys are true or false') } + } + + $proxy_set = $proxy_host ? { + undef => absent, + default => present + } + + file { '01proxy': + ensure => $proxy_set, + path => "${apt_conf_d}/01proxy", + content => "Acquire::http::Proxy \"http://${proxy_host}:${proxy_port}\";\n", + notify => Exec['apt_update'], + mode => '0644', + owner => root, + group => root, + } + + file { 'old-proxy-file': + ensure => absent, + path => "${apt_conf_d}/proxy", + notify => Exec['apt_update'], + } + + # Need anchor to provide containment for dependencies. + anchor { 'apt::update': + require => Class['apt::update'], + } + + # manage sources if present + if $sources != undef { + validate_hash($sources) + create_resources('apt::source', $sources) + } +} diff --git a/modules/apt/manifests/key.pp b/modules/apt/manifests/key.pp new file mode 100644 index 0000000..9ccbfcb --- /dev/null +++ b/modules/apt/manifests/key.pp @@ -0,0 +1,121 @@ +# == Define: apt::key +# +# The apt::key defined type allows for keys to be added to apt's keyring +# which is used for package validation. This defined type uses the apt_key +# native type to manage keys. This is a simple wrapper around apt_key with +# a few safeguards in place. +# +# === Parameters +# +# [*key*] +# _default_: +$title+, the title/name of the resource +# +# Is a GPG key ID. This key ID is validated with a regex enforcing it +# to only contain valid hexadecimal characters, be precisely 8 or 16 +# characters long and optionally prefixed with 0x. +# +# [*ensure*] +# _default_: +present+ +# +# The state we want this key in, may be either one of: +# * +present+ +# * +absent+ +# +# [*key_content*] +# _default_: +undef+ +# +# This parameter can be used to pass in a GPG key as a +# string in case it cannot be fetched from a remote location +# and using a file resource is for other reasons inconvenient. +# +# [*key_source*] +# _default_: +undef+ +# +# This parameter can be used to pass in the location of a GPG +# key. This URI can take the form of a: +# * +URL+: ftp, http or https +# * +path+: absolute path to a file on the target system. +# +# [*key_server*] +# _default_: +undef+ +# +# The keyserver from where to fetch our GPG key. It defaults to +# undef which results in apt_key's default keyserver being used, +# currently +keyserver.ubuntu.com+. +# +# [*key_options*] +# _default_: +undef+ +# +# Additional options to pass on to `apt-key adv --keyserver-options`. +define apt::key ( + $key = $title, + $ensure = present, + $key_content = undef, + $key_source = undef, + $key_server = undef, + $key_options = undef, +) { + + validate_re($key, ['\A(0x)?[0-9a-fA-F]{8}\Z', '\A(0x)?[0-9a-fA-F]{16}\Z']) + validate_re($ensure, ['\Aabsent|present\Z',]) + + if $key_content { + validate_string($key_content) + } + + if $key_source { + validate_re($key_source, ['\Ahttps?:\/\/', '\Aftp:\/\/', '\A\/\w+']) + } + + if $key_server { + if !is_domain_name($key_server) { + fail('$key_server must be a valid domain name') + } + } + + if $key_options { + validate_string($key_options) + } + + case $ensure { + present: { + if defined(Anchor["apt_key ${key} absent"]){ + fail("key with id ${key} already ensured as absent") + } + + if !defined(Anchor["apt_key ${key} present"]) { + apt_key { $title: + ensure => $ensure, + id => $key, + source => $key_source, + content => $key_content, + server => $key_server, + keyserver_options => $key_options, + } -> + anchor { "apt_key ${key} present": } + } + } + + absent: { + if defined(Anchor["apt_key ${key} present"]){ + fail("key with id ${key} already ensured as present") + } + + if !defined(Anchor["apt_key ${key} absent"]){ + apt_key { $title: + ensure => $ensure, + id => $key, + source => $key_source, + content => $key_content, + server => $key_server, + keyserver_options => $key_options, + } -> + anchor { "apt_key ${key} absent": } + } + } + + default: { + fail "Invalid 'ensure' value '${ensure}' for apt::key" + } + } +} diff --git a/modules/apt/manifests/params.pp b/modules/apt/manifests/params.pp new file mode 100644 index 0000000..4e974ba --- /dev/null +++ b/modules/apt/manifests/params.pp @@ -0,0 +1,55 @@ +class apt::params { + $root = '/etc/apt' + $provider = '/usr/bin/apt-get' + $sources_list_d = "${root}/sources.list.d" + $apt_conf_d = "${root}/apt.conf.d" + $preferences_d = "${root}/preferences.d" + + case $::lsbdistid { + 'debian': { + case $::lsbdistcodename { + 'squeeze': { + $backports_location = 'http://backports.debian.org/debian-backports' + $legacy_origin = true + $origins = ['${distro_id} oldstable', + '${distro_id} ${distro_codename}-security'] + } + 'wheezy': { + $backports_location = 'http://ftp.debian.org/debian/' + $legacy_origin = false + $origins = ['origin=Debian,archive=stable,label=Debian-Security'] + } + default: { + $backports_location = 'http://http.debian.net/debian/' + $legacy_origin = false + $origins = ['origin=Debian,archive=stable,label=Debian-Security'] + } + } + } + 'ubuntu': { + case $::lsbdistcodename { + 'lucid': { + $backports_location = 'http://us.archive.ubuntu.com/ubuntu' + $ppa_options = undef + $legacy_origin = true + $origins = ['${distro_id} ${distro_codename}-security'] + } + 'precise', 'trusty': { + $backports_location = 'http://us.archive.ubuntu.com/ubuntu' + $ppa_options = '-y' + $legacy_origin = true + $origins = ['${distro_id}:${distro_codename}-security'] + } + default: { + $backports_location = 'http://old-releases.ubuntu.com/ubuntu' + $ppa_options = '-y' + $legacy_origin = true + $origins = ['${distro_id}:${distro_codename}-security'] + } + } + } + default: { + fail("Unsupported lsbdistid (${::lsbdistid})") + } + } +} diff --git a/modules/apt/manifests/pin.pp b/modules/apt/manifests/pin.pp new file mode 100644 index 0000000..2563fc4 --- /dev/null +++ b/modules/apt/manifests/pin.pp @@ -0,0 +1,89 @@ +# pin.pp +# pin a release in apt, useful for unstable repositories + +define apt::pin( + $ensure = present, + $explanation = "${caller_module_name}: ${name}", + $order = '', + $packages = '*', + $priority = 0, + $release = '', # a= + $origin = '', + $version = '', + $codename = '', # n= + $release_version = '', # v= + $component = '', # c= + $originator = '', # o= + $label = '' # l= +) { + + include apt::params + + $preferences_d = $apt::params::preferences_d + + if $order != '' and !is_integer($order) { + fail('Only integers are allowed in the apt::pin order param') + } + + $pin_release_array = [ + $release, + $codename, + $release_version, + $component, + $originator, + $label] + $pin_release = join($pin_release_array, '') + + # Read the manpage 'apt_preferences(5)', especially the chapter + # 'Thea Effect of APT Preferences' to understand the following logic + # and the difference between specific and general form + if is_array($packages) { + $packages_string = join($packages, ' ') + } else { + $packages_string = $packages + } + + if $packages_string != '*' { # specific form + + if ( $pin_release != '' and ( $origin != '' or $version != '' )) or + ( $origin != '' and ( $pin_release != '' or $version != '' )) or + ( $version != '' and ( $pin_release != '' or $origin != '' )) { + fail('parameters release, origin, and version are mutually exclusive') + } + + } else { # general form + + if $version != '' { + fail('parameter version cannot be used in general form') + } + + if ( $pin_release != '' and $origin != '' ) or + ( $origin != '' and $pin_release != '' ) { + fail('parmeters release and origin are mutually exclusive') + } + + } + + $path = $order ? { + '' => "${preferences_d}/${name}.pref", + default => "${preferences_d}/${order}-${name}.pref", + } + + # According to man 5 apt_preferences: + # The files have either no or "pref" as filename extension + # and only contain alphanumeric, hyphen (-), underscore (_) and period + # (.) characters. Otherwise APT will print a notice that it has ignored a + # file, unless that file matches a pattern in the + # Dir::Ignore-Files-Silently configuration list - in which case it will + # be silently ignored. + $file_name = regsubst($title, '[^0-9a-z\-_\.]', '_', 'IG') + + file { "${file_name}.pref": + ensure => $ensure, + path => $path, + owner => root, + group => root, + mode => '0644', + content => template('apt/pin.pref.erb'), + } +} diff --git a/modules/apt/manifests/ppa.pp b/modules/apt/manifests/ppa.pp new file mode 100644 index 0000000..a55e1e0 --- /dev/null +++ b/modules/apt/manifests/ppa.pp @@ -0,0 +1,81 @@ +# ppa.pp + +define apt::ppa( + $ensure = 'present', + $release = $::lsbdistcodename, + $options = $apt::params::ppa_options, +) { + include apt::params + include apt::update + + $sources_list_d = $apt::params::sources_list_d + + if ! $release { + fail('lsbdistcodename fact not available: release parameter required') + } + + if $::operatingsystem != 'Ubuntu' { + fail('apt::ppa is currently supported on Ubuntu only.') + } + + $filename_without_slashes = regsubst($name, '/', '-', 'G') + $filename_without_dots = regsubst($filename_without_slashes, '\.', '_', 'G') + $filename_without_ppa = regsubst($filename_without_dots, '^ppa:', '', 'G') + $sources_list_d_filename = "${filename_without_ppa}-${release}.list" + + if $ensure == 'present' { + $package = $::lsbdistrelease ? { + /^[1-9]\..*|1[01]\..*|12.04$/ => 'python-software-properties', + default => 'software-properties-common', + } + + if ! defined(Package[$package]) { + package { $package: } + } + + if defined(Class[apt]) { + $proxy_host = $apt::proxy_host + $proxy_port = $apt::proxy_port + case $proxy_host { + false, '': { + $proxy_env = [] + } + default: {$proxy_env = ["http_proxy=http://${proxy_host}:${proxy_port}", "https_proxy=http://${proxy_host}:${proxy_port}"]} + } + } else { + $proxy_env = [] + } + exec { "add-apt-repository-${name}": + environment => $proxy_env, + command => "/usr/bin/add-apt-repository ${options} ${name}", + unless => "/usr/bin/test -s ${sources_list_d}/${sources_list_d_filename}", + user => 'root', + logoutput => 'on_failure', + notify => Exec['apt_update'], + require => [ + File['sources.list.d'], + Package[$package], + ], + } + + file { "${sources_list_d}/${sources_list_d_filename}": + ensure => file, + require => Exec["add-apt-repository-${name}"], + } + } + else { + + file { "${sources_list_d}/${sources_list_d_filename}": + ensure => 'absent', + mode => '0644', + owner => 'root', + group => 'root', + notify => Exec['apt_update'], + } + } + + # Need anchor to provide containment for dependencies. + anchor { "apt::ppa::${name}": + require => Class['apt::update'], + } +} diff --git a/modules/apt/manifests/release.pp b/modules/apt/manifests/release.pp new file mode 100644 index 0000000..6e0a38f --- /dev/null +++ b/modules/apt/manifests/release.pp @@ -0,0 +1,17 @@ +# release.pp + +class apt::release ( + $release_id +) { + + include apt::params + + $root = $apt::params::root + + file { "${root}/apt.conf.d/01release": + owner => root, + group => root, + mode => '0644', + content => "APT::Default-Release \"${release_id}\";" + } +} diff --git a/modules/apt/manifests/source.pp b/modules/apt/manifests/source.pp new file mode 100644 index 0000000..196fc92 --- /dev/null +++ b/modules/apt/manifests/source.pp @@ -0,0 +1,87 @@ +# source.pp +# add an apt source + +define apt::source( + $ensure = present, + $location = '', + $release = 'UNDEF', + $repos = 'main', + $include_src = true, + $required_packages = false, + $key = undef, + $key_server = 'keyserver.ubuntu.com', + $key_content = undef, + $key_source = undef, + $pin = false, + $architecture = undef +) { + + include apt::params + include apt::update + + $sources_list_d = $apt::params::sources_list_d + $provider = $apt::params::provider + + if $release == 'UNDEF' { + if $::lsbdistcodename == undef { + fail('lsbdistcodename fact not available: release parameter required') + } else { + $release_real = $::lsbdistcodename + } + } else { + $release_real = $release + } + + file { "${name}.list": + ensure => $ensure, + path => "${sources_list_d}/${name}.list", + owner => root, + group => root, + mode => '0644', + content => template("${module_name}/source.list.erb"), + notify => Exec['apt_update'], + } + + + if ($pin != false) { + # Get the host portion out of the url so we can pin to origin + $url_split = split($location, '/') + $host = $url_split[2] + + apt::pin { $name: + ensure => $ensure, + priority => $pin, + before => File["${name}.list"], + origin => $host, + } + } + + if ($required_packages != false) and ($ensure == 'present') { + exec { "Required packages: '${required_packages}' for ${name}": + command => "${provider} -y install ${required_packages}", + logoutput => 'on_failure', + refreshonly => true, + tries => 3, + try_sleep => 1, + subscribe => File["${name}.list"], + before => Exec['apt_update'], + } + } + + # We do not want to remove keys when the source is absent. + if $key and ($ensure == 'present') { + apt::key { "Add key: ${key} from Apt::Source ${title}": + ensure => present, + key => $key, + key_server => $key_server, + key_content => $key_content, + key_source => $key_source, + before => File["${name}.list"], + } + } + + # Need anchor to provide containment for dependencies. + anchor { "apt::source::${name}": + require => Class['apt::update'], + } +} diff --git a/modules/apt/manifests/unattended_upgrades.pp b/modules/apt/manifests/unattended_upgrades.pp new file mode 100644 index 0000000..7e3ccc4 --- /dev/null +++ b/modules/apt/manifests/unattended_upgrades.pp @@ -0,0 +1,69 @@ +# Class: apt::unattended_upgrades +# +# This class manages the unattended-upgrades package and related configuration +# files for ubuntu +# +# origins are the repositories to automatically upgrade included packages +# blacklist is a list of packages to not automatically upgrade +# update is how often to run "apt-get update" in days +# download is how often to run "apt-get upgrade --download-only" in days +# upgrade is how often to upgrade packages included in the origins list in days +# autoclean is how often to run "apt-get autoclean" in days +# +# information on the other options can be found in the 50unattended-upgrades +# file and in /etc/cron.daily/apt +# +class apt::unattended_upgrades ( + $origins = $::apt::params::origins, + $blacklist = [], + $update = '1', + $download = '1', + $upgrade = '1', + $autoclean = '7', + $auto_fix = true, + $minimal_steps = false, + $install_on_shutdown = false, + $mail_to = 'NONE', + $mail_only_on_error = false, + $remove_unused = true, + $auto_reboot = false, + $dl_limit = 'NONE', + $enable = '1', + $backup_interval = '0', + $backup_level = '3', + $max_age = '0', + $min_age = '0', + $max_size = '0', + $download_delta = '0', + $verbose = '0', +) inherits ::apt::params { + + validate_bool( + $auto_fix, + $minimal_steps, + $install_on_shutdown, + $mail_only_on_error, + $remove_unused, + $auto_reboot + ) + validate_array($origins) + + package { 'unattended-upgrades': + ensure => present, + } + + File { + ensure => file, + owner => 'root', + group => 'root', + mode => '0644', + require => Package['unattended-upgrades'], + } + + file { + '/etc/apt/apt.conf.d/50unattended-upgrades': + content => template('apt/50unattended-upgrades.erb'); + '/etc/apt/apt.conf.d/10periodic': + content => template('apt/10periodic.erb'); + } +} diff --git a/modules/apt/manifests/update.pp b/modules/apt/manifests/update.pp new file mode 100644 index 0000000..725bb3b --- /dev/null +++ b/modules/apt/manifests/update.pp @@ -0,0 +1,12 @@ +class apt::update { + include apt::params + + exec { 'apt_update': + command => "${apt::params::provider} update", + logoutput => 'on_failure', + refreshonly => true, + timeout => $apt::update_timeout, + tries => $apt::update_tries, + try_sleep => 1 + } +} diff --git a/modules/apt/metadata.json b/modules/apt/metadata.json new file mode 100644 index 0000000..66a6145 --- /dev/null +++ b/modules/apt/metadata.json @@ -0,0 +1,41 @@ +{ + "name": "puppetlabs-apt", + "version": "1.5.0", + "author": "Evolving Web / Puppet Labs", + "summary": "Puppet Labs Apt Module", + "license": "Apache License 2.0", + "source": "https://github.com/puppetlabs/puppetlabs-apt", + "project_page": "https://github.com/puppetlabs/puppetlabs-apt", + "issues_url": "https://github.com/puppetlabs/puppetlabs-apt/issues", + "operatingsystem_support": [ + { + "operatingsystem": "Debian", + "operatingsystemrelease": [ + "6", + "7" + ] + }, + { + "operatingsystem": "Ubuntu", + "operatingsystemrelease": [ + "10.04", + "12.04", + "14.04" + ] + } + ], + "requirements": [ + { + "name": "pe", + "version_requirement": ">= 3.2.0 < 3.4.0" + }, + { + "name": "puppet", + "version_requirement": "3.x" + } + ], + "description": "APT Module for Puppet", + "dependencies": [ + {"name":"puppetlabs/stdlib","version_requirement":">= 2.2.1"} + ] +} diff --git a/modules/apt/spec/acceptance/apt_builddep_spec.rb b/modules/apt/spec/acceptance/apt_builddep_spec.rb new file mode 100644 index 0000000..1e35e4a --- /dev/null +++ b/modules/apt/spec/acceptance/apt_builddep_spec.rb @@ -0,0 +1,36 @@ +require 'spec_helper_acceptance' + +describe 'apt::builddep', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + + context 'reset' do + it 'removes packages' do + shell('apt-get -y remove znc') + shell('apt-get -y remove g++') + end + end + + context 'apt::builddep' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::builddep { 'znc': } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe 'should install g++ as a dependency' do + describe package('g++') do + it { should be_installed } + end + end + end + + context 'reset' do + it 'removes packages' do + shell('apt-get -y remove znc') + shell('apt-get -y remove g++') + end + end + +end diff --git a/modules/apt/spec/acceptance/apt_key_provider_spec.rb b/modules/apt/spec/acceptance/apt_key_provider_spec.rb new file mode 100644 index 0000000..0a31495 --- /dev/null +++ b/modules/apt/spec/acceptance/apt_key_provider_spec.rb @@ -0,0 +1,446 @@ +require 'spec_helper_acceptance' + +PUPPETLABS_GPG_KEY_ID = '4BD6EC30' +PUPPETLABS_APT_URL = 'apt.puppetlabs.com' +PUPPETLABS_GPG_KEY_FILE = 'pubkey.gpg' +CENTOS_GPG_KEY_ID = 'C105B9DE' +CENTOS_REPO_URL = 'ftp.cvut.cz/centos' +CENTOS_GPG_KEY_FILE = 'RPM-GPG-KEY-CentOS-6' + +describe 'apt_key', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + before(:each) do + shell("apt-key del #{PUPPETLABS_GPG_KEY_ID}", + :acceptable_exit_codes => [0,1,2]) + end + + describe 'default options' do + key_versions = { + '32bit key id' => '4BD6EC30', + '64bit key id' => '1054B7A24BD6EC30', + '32bit lowercase key id' => '4bd6ec30', + '64bit lowercase key id' => '1054b7a24bd6ec30', + '0x formatted 32bit key id' => '0x4BD6EC30', + '0x formatted 64bit key id' => '0x1054B7A24BD6EC30', + '0x formatted 32bit lowercase key id' => '0x4bd6ec30', + '0x formatted 64bit lowercase key id' => '0x1054b7a24bd6ec30', + } + + key_versions.each do |key, value| + context "#{key}" do + it 'works' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{value}', + ensure => 'present', + } + EOS + + apply_manifest(pp, :catch_failures => true) + expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + shell("apt-key list | grep #{PUPPETLABS_GPG_KEY_ID}") + end + end + end + + context 'invalid length key id' do + it 'fails' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '4B7A24BD6EC30', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/Valid values match/) + end + end + end + end + + describe 'ensure =>' do + context 'absent' do + it 'is removed' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'absent', + } + EOS + + # Install the key first + shell("apt-key adv --keyserver keyserver.ubuntu.com \ + --recv-keys #{PUPPETLABS_GPG_KEY_ID}") + shell("apt-key list | grep #{PUPPETLABS_GPG_KEY_ID}") + + # Time to remove it using Puppet + apply_manifest(pp, :catch_failures => true) + expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + + shell("apt-key list | grep #{PUPPETLABS_GPG_KEY_ID}", + :acceptable_exit_codes => [1]) + end + end + end + + describe 'content =>' do + context 'puppetlabs gpg key' do + it 'works' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + content => "-----BEGIN PGP PUBLIC KEY BLOCK----- +Version: GnuPG v1.4.12 (GNU/Linux) +Comment: GPGTools - http://gpgtools.org + +mQINBEw3u0ABEAC1+aJQpU59fwZ4mxFjqNCgfZgDhONDSYQFMRnYC1dzBpJHzI6b +fUBQeaZ8rh6N4kZ+wq1eL86YDXkCt4sCvNTP0eF2XaOLbmxtV9bdpTIBep9bQiKg +5iZaz+brUZlFk/MyJ0Yz//VQ68N1uvXccmD6uxQsVO+gx7rnarg/BGuCNaVtGwy+ +S98g8Begwxs9JmGa8pMCcSxtC7fAfAEZ02cYyrw5KfBvFI3cHDdBqrEJQKwKeLKY +GHK3+H1TM4ZMxPsLuR/XKCbvTyl+OCPxU2OxPjufAxLlr8BWUzgJv6ztPe9imqpH +Ppp3KuLFNorjPqWY5jSgKl94W/CO2x591e++a1PhwUn7iVUwVVe+mOEWnK5+Fd0v +VMQebYCXS+3dNf6gxSvhz8etpw20T9Ytg4EdhLvCJRV/pYlqhcq+E9le1jFOHOc0 +Nc5FQweUtHGaNVyn8S1hvnvWJBMxpXq+Bezfk3X8PhPT/l9O2lLFOOO08jo0OYiI +wrjhMQQOOSZOb3vBRvBZNnnxPrcdjUUm/9cVB8VcgI5KFhG7hmMCwH70tpUWcZCN +NlI1wj/PJ7Tlxjy44f1o4CQ5FxuozkiITJvh9CTg+k3wEmiaGz65w9jRl9ny2gEl +f4CR5+ba+w2dpuDeMwiHJIs5JsGyJjmA5/0xytB7QvgMs2q25vWhygsmUQARAQAB +tEdQdXBwZXQgTGFicyBSZWxlYXNlIEtleSAoUHVwcGV0IExhYnMgUmVsZWFzZSBL +ZXkpIDxpbmZvQHB1cHBldGxhYnMuY29tPokCPgQTAQIAKAUCTDe7QAIbAwUJA8Jn +AAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQEFS3okvW7DAZaw//aLmE/eob +pXpIUVyCUWQxEvPtM/h/SAJsG3KoHN9u216ews+UHsL/7F91ceVXQQdD2e8CtYWF +eLNM0RSM9i/KM60g4CvIQlmNqdqhi1HsgGqInZ72/XLAXun0gabfC36rLww2kel+ +aMpRf58SrSuskY321NnMEJl4OsHV2hfNtAIgw2e/zm9RhoMpGKxoHZCvFhnP7u2M +2wMq7iNDDWb6dVsLpzdlVf242zCbubPCxxQXOpA56rzkUPuJ85mdVw4i19oPIFIZ +VL5owit1SxCOxBg4b8oaMS36hEl3qtZG834rtLfcqAmqjhx6aJuJLOAYN84QjDEU +3NI5IfNRMvluIeTcD4Dt5FCYahN045tW1Rc6s5GAR8RW45GYwQDzG+kkkeeGxwEh +qCW7nOHuwZIoVJufNhd28UFn83KGJHCQt4NBBr3K5TcY6bDQEIrpSplWSDBbd3p1 +IaoZY1WSDdP9OTVOSbsz0JiglWmUWGWCdd/CMSW/D7/3VUOJOYRDwptvtSYcjJc8 +1UV+1zB+rt5La/OWe4UOORD+jU1ATijQEaFYxBbqBBkFboAEXq9btRQyegqk+eVp +HhzacP5NYFTMThvHuTapNytcCso5au/cMywqCgY1DfcMJyjocu4bCtrAd6w4kGKN +MUdwNDYQulHZDI+UjJInhramyngdzZLjdeGJARwEEAECAAYFAkw3wEYACgkQIVr+ +UOQUcDKvEwgAoBuOPnPioBwYp8oHVPTo/69cJn1225kfraUYGebCcrRwuoKd8Iyh +R165nXYJmD8yrAFBk8ScUVKsQ/pSnqNrBCrlzQD6NQvuIWVFegIdjdasrWX6Szj+ +N1OllbzIJbkE5eo0WjCMEKJVI/GTY2AnTWUAm36PLQC5HnSATykqwxeZDsJ/s8Rc +kd7+QN5sBVytG3qb45Q7jLJpLcJO6KYH4rz9ZgN7LzyyGbu9DypPrulADG9OrL7e +lUnsGDG4E1M8Pkgk9Xv9MRKao1KjYLD5zxOoVtdeoKEQdnM+lWMJin1XvoqJY7FT +DJk6o+cVqqHkdKL+sgsscFVQljgCEd0EgIkCHAQQAQgABgUCTPlA6QAKCRBcE9bb +kwUuAxdYD/40FxAeNCYByxkr/XRT0gFT+NCjPuqPWCM5tf2NIhSapXtb2+32WbAf +DzVfqWjC0G0RnQBve+vcjpY4/rJu4VKIDGIT8CtnKOIyEcXTNFOehi65xO4ypaei +BPSb3ip3P0of1iZZDQrNHMW5VcyL1c+PWT/6exXSGsePtO/89tc6mupqZtC05f5Z +XG4jswMF0U6Q5s3S0tG7Y+oQhKNFJS4sH4rHe1o5CxKwNRSzqccA0hptKy3MHUZ2 ++zeHzuRdRWGjb2rUiVxnIvPPBGxF2JHhB4ERhGgbTxRZ6wZbdW06BOE8r7pGrUpU +fCw/WRT3gGXJHpGPOzFAvr3Xl7VcDUKTVmIajnpd3SoyD1t2XsvJlSQBOWbViucH +dvE4SIKQ77vBLRlZIoXXVb6Wu7Vq+eQs1ybjwGOhnnKjz8llXcMnLzzN86STpjN4 +qGTXQy/E9+dyUP1sXn3RRwb+ZkdI77m1YY95QRNgG/hqh77IuWWg1MtTSgQnP+F2 +7mfo0/522hObhdAe73VO3ttEPiriWy7tw3bS9daP2TAVbYyFqkvptkBb1OXRUSzq +UuWjBmZ35UlXjKQsGeUHlOiEh84aondF90A7gx0X/ktNIPRrfCGkHJcDu+HVnR7x +Kk+F0qb9+/pGLiT3rqeQTr8fYsb4xLHT7uEg1gVFB1g0kd+RQHzV74kCPgQTAQIA +KAIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AFAk/x5PoFCQtIMjoACgkQEFS3 +okvW7DAIKQ/9HvZyf+LHVSkCk92Kb6gckniin3+5ooz67hSr8miGBfK4eocqQ0H7 +bdtWjAILzR/IBY0xj6OHKhYP2k8TLc7QhQjt0dRpNkX+Iton2AZryV7vUADreYz4 +4B0bPmhiE+LL46ET5IThLKu/KfihzkEEBa9/t178+dO9zCM2xsXaiDhMOxVE32gX +vSZKP3hmvnK/FdylUY3nWtPedr+lHpBLoHGaPH7cjI+MEEugU3oAJ0jpq3V8n4w0 +jIq2V77wfmbD9byIV7dXcxApzciK+ekwpQNQMSaceuxLlTZKcdSqo0/qmS2A863Y +ZQ0ZBe+Xyf5OI33+y+Mry+vl6Lre2VfPm3udgR10E4tWXJ9Q2CmG+zNPWt73U1FD +7xBI7PPvOlyzCX4QJhy2Fn/fvzaNjHp4/FSiCw0HvX01epcersyun3xxPkRIjwwR +M9m5MJ0o4hhPfa97zibXSh8XXBnosBQxeg6nEnb26eorVQbqGx0ruu/W2m5/JpUf +REsFmNOBUbi8xlKNS5CZypH3Zh88EZiTFolOMEh+hT6s0l6znBAGGZ4m/Unacm5y +DHmg7unCk4JyVopQ2KHMoqG886elu+rm0ASkhyqBAk9sWKptMl3NHiYTRE/m9VAk +ugVIB2pi+8u84f+an4Hml4xlyijgYu05pqNvnLRyJDLd61hviLC8GYU= +=a34C +-----END PGP PUBLIC KEY BLOCK-----", + } + EOS + + apply_manifest(pp, :catch_failures => true) + expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + shell("apt-key list | grep #{PUPPETLABS_GPG_KEY_ID}") + end + end + + context 'bogus key' do + it 'fails' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + content => 'For posterity: such content, much bogus, wow', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/no valid OpenPGP data found/) + end + end + end + end + + describe 'server =>' do + context 'pgp.mit.edu' do + it 'works' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + server => 'pgp.mit.edu', + } + EOS + + apply_manifest(pp, :catch_failures => true) + expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + shell("apt-key list | grep #{PUPPETLABS_GPG_KEY_ID}") + end + end + + context 'nonexistant.key.server' do + it 'fails' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + server => 'nonexistant.key.server', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/(Host not found|Couldn't resolve host)/) + end + end + end + end + + describe 'source =>' do + context 'http://' do + it 'works' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + source => 'http://#{PUPPETLABS_APT_URL}/#{PUPPETLABS_GPG_KEY_FILE}', + } + EOS + + apply_manifest(pp, :catch_failures => true) + expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + shell("apt-key list | grep #{PUPPETLABS_GPG_KEY_ID}") + end + + it 'fails with a 404' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + source => 'http://#{PUPPETLABS_APT_URL}/herpderp.gpg', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/404 Not Found/) + end + end + + it 'fails with a socket error' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + source => 'http://apt.puppetlabss.com/herpderp.gpg', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/could not resolve/) + end + end + end + + context 'ftp://' do + before(:each) do + shell("apt-key del #{CENTOS_GPG_KEY_ID}", + :acceptable_exit_codes => [0,1,2]) + end + + it 'works' do + pp = <<-EOS + apt_key { 'CentOS 6': + id => '#{CENTOS_GPG_KEY_ID}', + ensure => 'present', + source => 'ftp://#{CENTOS_REPO_URL}/#{CENTOS_GPG_KEY_FILE}', + } + EOS + + apply_manifest(pp, :catch_failures => true) + expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + shell("apt-key list | grep #{CENTOS_GPG_KEY_ID}") + end + + it 'fails with a 550' do + pp = <<-EOS + apt_key { 'CentOS 6': + id => '#{CENTOS_GPG_KEY_ID}', + ensure => 'present', + source => 'ftp://#{CENTOS_REPO_URL}/herpderp.gpg', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/550 Failed to open/) + end + end + + it 'fails with a socket error' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + source => 'ftp://apt.puppetlabss.com/herpderp.gpg', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/could not resolve/) + end + end + end + + context 'https://' do + it 'works' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + source => 'https://#{PUPPETLABS_APT_URL}/#{PUPPETLABS_GPG_KEY_FILE}', + } + EOS + + apply_manifest(pp, :catch_failures => true) + expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + shell("apt-key list | grep #{PUPPETLABS_GPG_KEY_ID}") + end + + it 'fails with a 404' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '4BD6EC30', + ensure => 'present', + source => 'https://#{PUPPETLABS_APT_URL}/herpderp.gpg', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/404 Not Found/) + end + end + + it 'fails with a socket error' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '4BD6EC30', + ensure => 'present', + source => 'https://apt.puppetlabss.com/herpderp.gpg', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/could not resolve/) + end + end + end + + context '/path/that/exists' do + before(:each) do + shell("curl -o /tmp/puppetlabs-pubkey.gpg \ + http://#{PUPPETLABS_APT_URL}/#{PUPPETLABS_GPG_KEY_FILE}") + end + + after(:each) do + shell('rm /tmp/puppetlabs-pubkey.gpg') + end + + it 'works' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '4BD6EC30', + ensure => 'present', + source => '/tmp/puppetlabs-pubkey.gpg', + } + EOS + + apply_manifest(pp, :catch_failures => true) + expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + shell("apt-key list | grep #{PUPPETLABS_GPG_KEY_ID}") + end + end + + context '/path/that/does/not/exist' do + it 'fails' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + source => '/tmp/totally_bogus.file', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/does not exist/) + end + end + end + + context '/path/that/exists/with/bogus/content' do + before(:each) do + shell('echo "here be dragons" > /tmp/fake-key.gpg') + end + + after(:each) do + shell('rm /tmp/fake-key.gpg') + end + it 'fails' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + source => '/tmp/fake-key.gpg', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/no valid OpenPGP data found/) + end + end + end + end + + describe 'keyserver_options =>' do + context 'debug' do + it 'works' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + keyserver_options => 'debug', + } + EOS + + apply_manifest(pp, :catch_failures => true) + expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + shell("apt-key list | grep #{PUPPETLABS_GPG_KEY_ID}") + end + + it 'fails on invalid options' do + pp = <<-EOS + apt_key { 'puppetlabs': + id => '#{PUPPETLABS_GPG_KEY_ID}', + ensure => 'present', + keyserver_options => 'this is totally bonkers', + } + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/--keyserver-options this is totally/) + end + end + end + end +end diff --git a/modules/apt/spec/acceptance/apt_key_spec.rb b/modules/apt/spec/acceptance/apt_key_spec.rb new file mode 100644 index 0000000..9f2ba39 --- /dev/null +++ b/modules/apt/spec/acceptance/apt_key_spec.rb @@ -0,0 +1,200 @@ +require 'spec_helper_acceptance' + +describe 'apt::key', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + context 'apt::key' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::key { 'puppetlabs': + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + } + + apt::key { 'jenkins': + key => 'D50582E6', + key_source => 'http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key', + } + EOS + + shell('apt-key del 4BD6EC30', :acceptable_exit_codes => [0,1,2]) + shell('apt-key del D50582E6', :acceptable_exit_codes => [0,1,2]) + apply_manifest(pp, :catch_failures => true) + end + + describe 'keys should exist' do + it 'finds puppetlabs key' do + shell('apt-key list | grep 4BD6EC30') + end + it 'finds jenkins key' do + shell('apt-key list | grep D50582E6') + end + end + end + context 'ensure' do + context 'absent' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::key { 'puppetlabs': + ensure => absent, + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + } + + apt::key { 'jenkins': + ensure => absent, + key => 'D50582E6', + key_source => 'http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe 'keys shouldnt exist' do + it 'fails' do + shell('apt-key list | grep 4BD6EC30', :acceptable_exit_codes => [1]) + end + it 'fails' do + shell('apt-key list | grep D50582E6', :acceptable_exit_codes => [1]) + end + end + end + end + + context 'reset' do + it 'clean up keys' do + shell('apt-key del 4BD6EC30', :acceptable_exit_codes => [0,1,2]) + shell('apt-key del D50582E6', :acceptable_exit_codes => [0,1,2]) + end + end + + context 'key options' do + context 'key_content' do + + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::key { 'puppetlabs': + key => '4BD6EC30', + key_content => '-----BEGIN PGP PUBLIC KEY BLOCK----- + Version: GnuPG v1.4.12 (GNU/Linux) + Comment: GPGTools - http://gpgtools.org + + mQINBEw3u0ABEAC1+aJQpU59fwZ4mxFjqNCgfZgDhONDSYQFMRnYC1dzBpJHzI6b + fUBQeaZ8rh6N4kZ+wq1eL86YDXkCt4sCvNTP0eF2XaOLbmxtV9bdpTIBep9bQiKg + 5iZaz+brUZlFk/MyJ0Yz//VQ68N1uvXccmD6uxQsVO+gx7rnarg/BGuCNaVtGwy+ + S98g8Begwxs9JmGa8pMCcSxtC7fAfAEZ02cYyrw5KfBvFI3cHDdBqrEJQKwKeLKY + GHK3+H1TM4ZMxPsLuR/XKCbvTyl+OCPxU2OxPjufAxLlr8BWUzgJv6ztPe9imqpH + Ppp3KuLFNorjPqWY5jSgKl94W/CO2x591e++a1PhwUn7iVUwVVe+mOEWnK5+Fd0v + VMQebYCXS+3dNf6gxSvhz8etpw20T9Ytg4EdhLvCJRV/pYlqhcq+E9le1jFOHOc0 + Nc5FQweUtHGaNVyn8S1hvnvWJBMxpXq+Bezfk3X8PhPT/l9O2lLFOOO08jo0OYiI + wrjhMQQOOSZOb3vBRvBZNnnxPrcdjUUm/9cVB8VcgI5KFhG7hmMCwH70tpUWcZCN + NlI1wj/PJ7Tlxjy44f1o4CQ5FxuozkiITJvh9CTg+k3wEmiaGz65w9jRl9ny2gEl + f4CR5+ba+w2dpuDeMwiHJIs5JsGyJjmA5/0xytB7QvgMs2q25vWhygsmUQARAQAB + tEdQdXBwZXQgTGFicyBSZWxlYXNlIEtleSAoUHVwcGV0IExhYnMgUmVsZWFzZSBL + ZXkpIDxpbmZvQHB1cHBldGxhYnMuY29tPokCPgQTAQIAKAUCTDe7QAIbAwUJA8Jn + AAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQEFS3okvW7DAZaw//aLmE/eob + pXpIUVyCUWQxEvPtM/h/SAJsG3KoHN9u216ews+UHsL/7F91ceVXQQdD2e8CtYWF + eLNM0RSM9i/KM60g4CvIQlmNqdqhi1HsgGqInZ72/XLAXun0gabfC36rLww2kel+ + aMpRf58SrSuskY321NnMEJl4OsHV2hfNtAIgw2e/zm9RhoMpGKxoHZCvFhnP7u2M + 2wMq7iNDDWb6dVsLpzdlVf242zCbubPCxxQXOpA56rzkUPuJ85mdVw4i19oPIFIZ + VL5owit1SxCOxBg4b8oaMS36hEl3qtZG834rtLfcqAmqjhx6aJuJLOAYN84QjDEU + 3NI5IfNRMvluIeTcD4Dt5FCYahN045tW1Rc6s5GAR8RW45GYwQDzG+kkkeeGxwEh + qCW7nOHuwZIoVJufNhd28UFn83KGJHCQt4NBBr3K5TcY6bDQEIrpSplWSDBbd3p1 + IaoZY1WSDdP9OTVOSbsz0JiglWmUWGWCdd/CMSW/D7/3VUOJOYRDwptvtSYcjJc8 + 1UV+1zB+rt5La/OWe4UOORD+jU1ATijQEaFYxBbqBBkFboAEXq9btRQyegqk+eVp + HhzacP5NYFTMThvHuTapNytcCso5au/cMywqCgY1DfcMJyjocu4bCtrAd6w4kGKN + MUdwNDYQulHZDI+UjJInhramyngdzZLjdeGJARwEEAECAAYFAkw3wEYACgkQIVr+ + UOQUcDKvEwgAoBuOPnPioBwYp8oHVPTo/69cJn1225kfraUYGebCcrRwuoKd8Iyh + R165nXYJmD8yrAFBk8ScUVKsQ/pSnqNrBCrlzQD6NQvuIWVFegIdjdasrWX6Szj+ + N1OllbzIJbkE5eo0WjCMEKJVI/GTY2AnTWUAm36PLQC5HnSATykqwxeZDsJ/s8Rc + kd7+QN5sBVytG3qb45Q7jLJpLcJO6KYH4rz9ZgN7LzyyGbu9DypPrulADG9OrL7e + lUnsGDG4E1M8Pkgk9Xv9MRKao1KjYLD5zxOoVtdeoKEQdnM+lWMJin1XvoqJY7FT + DJk6o+cVqqHkdKL+sgsscFVQljgCEd0EgIkCHAQQAQgABgUCTPlA6QAKCRBcE9bb + kwUuAxdYD/40FxAeNCYByxkr/XRT0gFT+NCjPuqPWCM5tf2NIhSapXtb2+32WbAf + DzVfqWjC0G0RnQBve+vcjpY4/rJu4VKIDGIT8CtnKOIyEcXTNFOehi65xO4ypaei + BPSb3ip3P0of1iZZDQrNHMW5VcyL1c+PWT/6exXSGsePtO/89tc6mupqZtC05f5Z + XG4jswMF0U6Q5s3S0tG7Y+oQhKNFJS4sH4rHe1o5CxKwNRSzqccA0hptKy3MHUZ2 + +zeHzuRdRWGjb2rUiVxnIvPPBGxF2JHhB4ERhGgbTxRZ6wZbdW06BOE8r7pGrUpU + fCw/WRT3gGXJHpGPOzFAvr3Xl7VcDUKTVmIajnpd3SoyD1t2XsvJlSQBOWbViucH + dvE4SIKQ77vBLRlZIoXXVb6Wu7Vq+eQs1ybjwGOhnnKjz8llXcMnLzzN86STpjN4 + qGTXQy/E9+dyUP1sXn3RRwb+ZkdI77m1YY95QRNgG/hqh77IuWWg1MtTSgQnP+F2 + 7mfo0/522hObhdAe73VO3ttEPiriWy7tw3bS9daP2TAVbYyFqkvptkBb1OXRUSzq + UuWjBmZ35UlXjKQsGeUHlOiEh84aondF90A7gx0X/ktNIPRrfCGkHJcDu+HVnR7x + Kk+F0qb9+/pGLiT3rqeQTr8fYsb4xLHT7uEg1gVFB1g0kd+RQHzV74kCPgQTAQIA + KAIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AFAk/x5PoFCQtIMjoACgkQEFS3 + okvW7DAIKQ/9HvZyf+LHVSkCk92Kb6gckniin3+5ooz67hSr8miGBfK4eocqQ0H7 + bdtWjAILzR/IBY0xj6OHKhYP2k8TLc7QhQjt0dRpNkX+Iton2AZryV7vUADreYz4 + 4B0bPmhiE+LL46ET5IThLKu/KfihzkEEBa9/t178+dO9zCM2xsXaiDhMOxVE32gX + vSZKP3hmvnK/FdylUY3nWtPedr+lHpBLoHGaPH7cjI+MEEugU3oAJ0jpq3V8n4w0 + jIq2V77wfmbD9byIV7dXcxApzciK+ekwpQNQMSaceuxLlTZKcdSqo0/qmS2A863Y + ZQ0ZBe+Xyf5OI33+y+Mry+vl6Lre2VfPm3udgR10E4tWXJ9Q2CmG+zNPWt73U1FD + 7xBI7PPvOlyzCX4QJhy2Fn/fvzaNjHp4/FSiCw0HvX01epcersyun3xxPkRIjwwR + M9m5MJ0o4hhPfa97zibXSh8XXBnosBQxeg6nEnb26eorVQbqGx0ruu/W2m5/JpUf + REsFmNOBUbi8xlKNS5CZypH3Zh88EZiTFolOMEh+hT6s0l6znBAGGZ4m/Unacm5y + DHmg7unCk4JyVopQ2KHMoqG886elu+rm0ASkhyqBAk9sWKptMl3NHiYTRE/m9VAk + ugVIB2pi+8u84f+an4Hml4xlyijgYu05pqNvnLRyJDLd61hviLC8GYU= + =a34C + -----END PGP PUBLIC KEY BLOCK----- + ', + } + EOS + + shell('apt-key del 4BD6EC30', :acceptable_exit_codes => [0,1,2]) + apply_manifest(pp, :catch_failures => true) + end + end + describe 'keys should exist' do + it 'finds puppetlabs key' do + shell('apt-key list | grep 4BD6EC30') + end + end + + context 'key_source' do + + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::key { 'puppetlabs': + key => '4BD6EC30', + key_source => 'http://apt.puppetlabs.com/pubkey.gpg', + } + EOS + + shell('apt-key del 4BD6EC30', :acceptable_exit_codes => [0,1,2]) + apply_manifest(pp, :catch_failures => true) + end + + describe 'keys should exist' do + it 'finds puppetlabs key' do + shell('apt-key list | grep 4BD6EC30') + end + end + end + + context 'key_options' do + + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::key { 'puppetlabs': + key => '4BD6EC30', + key_source => 'http://apt.puppetlabs.com/pubkey.gpg', + key_options => 'debug' + } + EOS + + shell('apt-key del 4BD6EC30', :acceptable_exit_codes => [0,1,2]) + apply_manifest(pp, :catch_failures => true) + end + + describe 'keys should exist' do + it 'finds puppetlabs key' do + shell('apt-key list | grep 4BD6EC30') + end + end + end + end + +end diff --git a/modules/apt/spec/acceptance/apt_ppa_spec.rb b/modules/apt/spec/acceptance/apt_ppa_spec.rb new file mode 100644 index 0000000..b665c5c --- /dev/null +++ b/modules/apt/spec/acceptance/apt_ppa_spec.rb @@ -0,0 +1,138 @@ +require 'spec_helper_acceptance' + +if fact('operatingsystem') == 'Ubuntu' + describe 'apt::ppa', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + + context 'reset' do + it 'removes ppa' do + shell('rm /etc/apt/sources.list.d/canonical-kernel-team-ppa-*', :acceptable_exit_codes => [0,1,2]) + shell('rm /etc/apt/sources.list.d/raravena80-collectd5-*', :acceptable_exit_codes => [0,1,2]) + end + end + + context 'adding a ppa that doesnt exist' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::ppa { 'ppa:canonical-kernel-team/ppa': } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe 'contains the source file' do + it 'contains a kernel ppa source' do + shell('ls /etc/apt/sources.list.d/canonical-kernel-team-ppa-*', :acceptable_exit_codes => [0]) + end + end + end + + context 'reading a removed ppa.' do + it 'setup' do + # This leaves a blank file + shell('echo > /etc/apt/sources.list.d/raravena80-collectd5-$(lsb_release -c -s).list') + end + + it 'should read it successfully' do + pp = <<-EOS + include '::apt' + apt::ppa { 'ppa:raravena80/collectd5': } + EOS + + apply_manifest(pp, :catch_failures => true) + end + end + + context 'reset' do + it 'removes added ppas' do + shell('rm /etc/apt/sources.list.d/canonical-kernel-team-ppa-*') + shell('rm /etc/apt/sources.list.d/raravena80-collectd5-*') + end + end + + context 'ensure' do + context 'present' do + it 'works without failure' do + pp = <<-EOS + include '::apt' + apt::ppa { 'ppa:canonical-kernel-team/ppa': ensure => present } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe 'contains the source file' do + it 'contains a kernel ppa source' do + shell('ls /etc/apt/sources.list.d/canonical-kernel-team-ppa-*', :acceptable_exit_codes => [0]) + end + end + end + end + + context 'ensure' do + context 'absent' do + it 'works without failure' do + pp = <<-EOS + include '::apt' + apt::ppa { 'ppa:canonical-kernel-team/ppa': ensure => absent } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe 'doesnt contain the source file' do + it 'fails' do + shell('ls /etc/apt/sources.list.d/canonical-kernel-team-ppa-*', :acceptable_exit_codes => [2]) + end + end + end + end + + context 'release' do + context 'precise' do + it 'works without failure' do + pp = <<-EOS + include '::apt' + apt::ppa { 'ppa:canonical-kernel-team/ppa': + ensure => present, + release => precise, + } + EOS + + shell('rm -rf /etc/apt/sources.list.d/canonical-kernel-team-ppa*', :acceptable_exit_codes => [0,1,2]) + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/sources.list.d/canonical-kernel-team-ppa-precise.list') do + it { should be_file } + end + end + end + + context 'options' do + context '-y', :unless => default[:platform].match(/10\.04/) do + it 'works without failure' do + pp = <<-EOS + include '::apt' + apt::ppa { 'ppa:canonical-kernel-team/ppa': + ensure => present, + release => precise, + options => '-y', + } + EOS + + shell('rm -rf /etc/apt/sources.list.d/canonical-kernel-team-ppa*', :acceptable_exit_codes => [0,1,2]) + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/sources.list.d/canonical-kernel-team-ppa-precise.list') do + it { should be_file } + end + end + end + + context 'reset' do + it { shell('rm -rf /etc/apt/sources.list.d/canonical-kernel-team-ppa*', :acceptable_exit_codes => [0,1,2]) } + end + end +end diff --git a/modules/apt/spec/acceptance/apt_source_spec.rb b/modules/apt/spec/acceptance/apt_source_spec.rb new file mode 100644 index 0000000..c2d076c --- /dev/null +++ b/modules/apt/spec/acceptance/apt_source_spec.rb @@ -0,0 +1,326 @@ +require 'spec_helper_acceptance' + +describe 'apt::source', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + + context 'apt::source' do + context 'ensure => present' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::source { 'puppetlabs': + ensure => present, + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + } + EOS + + shell('apt-key del 4BD6EC30', :acceptable_exit_codes => [0,1,2]) + shell('rm /etc/apt/sources.list.d/puppetlabs.list', :acceptable_exit_codes => [0,1,2]) + apply_manifest(pp, :catch_failures => true) + end + + describe 'key should exist' do + it 'finds puppetlabs key' do + shell('apt-key list | grep 4BD6EC30', :acceptable_exit_codes => [0]) + end + end + + describe file('/etc/apt/sources.list.d/puppetlabs.list') do + it { should be_file } + end + end + + context 'ensure => absent' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::source { 'puppetlabs': + ensure => absent, + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + # The key should remain -we don't delete those when deleting a source. + describe 'key should exist' do + it 'finds puppetlabs key' do + shell('apt-key list | grep 4BD6EC30', :acceptable_exit_codes => [0]) + end + end + describe file('/etc/apt/sources.list.d/puppetlabs.list') do + it { should_not be_file } + end + end + + end + + context 'release' do + context 'test' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::source { 'puppetlabs': + ensure => present, + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + release => 'precise', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/sources.list.d/puppetlabs.list') do + it { should be_file } + it { should contain 'deb http://apt.puppetlabs.com precise main' } + end + end + end + + context 'include_src' do + context 'true' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::source { 'puppetlabs': + ensure => present, + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + include_src => true, + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/sources.list.d/puppetlabs.list') do + it { should be_file } + it { should contain 'deb-src http://apt.puppetlabs.com' } + end + end + + context 'false' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::source { 'puppetlabs': + ensure => present, + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + include_src => false, + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/sources.list.d/puppetlabs.list') do + it { should be_file } + it { should_not contain 'deb-src http://apt.puppetlabs.com' } + end + end + end + + context 'required_packages' do + context 'vim' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::source { 'puppetlabs': + ensure => present, + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + required_packages => 'vim', + } + EOS + + shell('apt-get -y remove vim') + apply_manifest(pp, :catch_failures => true) + end + + describe package('vim') do + it { should be_installed } + end + end + end + + context 'key content' do + context 'giant key' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::source { 'puppetlabs': + ensure => present, + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_content => '-----BEGIN PGP PUBLIC KEY BLOCK----- + Version: GnuPG v1.4.12 (GNU/Linux) + Comment: GPGTools - http://gpgtools.org + + mQINBEw3u0ABEAC1+aJQpU59fwZ4mxFjqNCgfZgDhONDSYQFMRnYC1dzBpJHzI6b + fUBQeaZ8rh6N4kZ+wq1eL86YDXkCt4sCvNTP0eF2XaOLbmxtV9bdpTIBep9bQiKg + 5iZaz+brUZlFk/MyJ0Yz//VQ68N1uvXccmD6uxQsVO+gx7rnarg/BGuCNaVtGwy+ + S98g8Begwxs9JmGa8pMCcSxtC7fAfAEZ02cYyrw5KfBvFI3cHDdBqrEJQKwKeLKY + GHK3+H1TM4ZMxPsLuR/XKCbvTyl+OCPxU2OxPjufAxLlr8BWUzgJv6ztPe9imqpH + Ppp3KuLFNorjPqWY5jSgKl94W/CO2x591e++a1PhwUn7iVUwVVe+mOEWnK5+Fd0v + VMQebYCXS+3dNf6gxSvhz8etpw20T9Ytg4EdhLvCJRV/pYlqhcq+E9le1jFOHOc0 + Nc5FQweUtHGaNVyn8S1hvnvWJBMxpXq+Bezfk3X8PhPT/l9O2lLFOOO08jo0OYiI + wrjhMQQOOSZOb3vBRvBZNnnxPrcdjUUm/9cVB8VcgI5KFhG7hmMCwH70tpUWcZCN + NlI1wj/PJ7Tlxjy44f1o4CQ5FxuozkiITJvh9CTg+k3wEmiaGz65w9jRl9ny2gEl + f4CR5+ba+w2dpuDeMwiHJIs5JsGyJjmA5/0xytB7QvgMs2q25vWhygsmUQARAQAB + tEdQdXBwZXQgTGFicyBSZWxlYXNlIEtleSAoUHVwcGV0IExhYnMgUmVsZWFzZSBL + ZXkpIDxpbmZvQHB1cHBldGxhYnMuY29tPokCPgQTAQIAKAUCTDe7QAIbAwUJA8Jn + AAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQEFS3okvW7DAZaw//aLmE/eob + pXpIUVyCUWQxEvPtM/h/SAJsG3KoHN9u216ews+UHsL/7F91ceVXQQdD2e8CtYWF + eLNM0RSM9i/KM60g4CvIQlmNqdqhi1HsgGqInZ72/XLAXun0gabfC36rLww2kel+ + aMpRf58SrSuskY321NnMEJl4OsHV2hfNtAIgw2e/zm9RhoMpGKxoHZCvFhnP7u2M + 2wMq7iNDDWb6dVsLpzdlVf242zCbubPCxxQXOpA56rzkUPuJ85mdVw4i19oPIFIZ + VL5owit1SxCOxBg4b8oaMS36hEl3qtZG834rtLfcqAmqjhx6aJuJLOAYN84QjDEU + 3NI5IfNRMvluIeTcD4Dt5FCYahN045tW1Rc6s5GAR8RW45GYwQDzG+kkkeeGxwEh + qCW7nOHuwZIoVJufNhd28UFn83KGJHCQt4NBBr3K5TcY6bDQEIrpSplWSDBbd3p1 + IaoZY1WSDdP9OTVOSbsz0JiglWmUWGWCdd/CMSW/D7/3VUOJOYRDwptvtSYcjJc8 + 1UV+1zB+rt5La/OWe4UOORD+jU1ATijQEaFYxBbqBBkFboAEXq9btRQyegqk+eVp + HhzacP5NYFTMThvHuTapNytcCso5au/cMywqCgY1DfcMJyjocu4bCtrAd6w4kGKN + MUdwNDYQulHZDI+UjJInhramyngdzZLjdeGJARwEEAECAAYFAkw3wEYACgkQIVr+ + UOQUcDKvEwgAoBuOPnPioBwYp8oHVPTo/69cJn1225kfraUYGebCcrRwuoKd8Iyh + R165nXYJmD8yrAFBk8ScUVKsQ/pSnqNrBCrlzQD6NQvuIWVFegIdjdasrWX6Szj+ + N1OllbzIJbkE5eo0WjCMEKJVI/GTY2AnTWUAm36PLQC5HnSATykqwxeZDsJ/s8Rc + kd7+QN5sBVytG3qb45Q7jLJpLcJO6KYH4rz9ZgN7LzyyGbu9DypPrulADG9OrL7e + lUnsGDG4E1M8Pkgk9Xv9MRKao1KjYLD5zxOoVtdeoKEQdnM+lWMJin1XvoqJY7FT + DJk6o+cVqqHkdKL+sgsscFVQljgCEd0EgIkCHAQQAQgABgUCTPlA6QAKCRBcE9bb + kwUuAxdYD/40FxAeNCYByxkr/XRT0gFT+NCjPuqPWCM5tf2NIhSapXtb2+32WbAf + DzVfqWjC0G0RnQBve+vcjpY4/rJu4VKIDGIT8CtnKOIyEcXTNFOehi65xO4ypaei + BPSb3ip3P0of1iZZDQrNHMW5VcyL1c+PWT/6exXSGsePtO/89tc6mupqZtC05f5Z + XG4jswMF0U6Q5s3S0tG7Y+oQhKNFJS4sH4rHe1o5CxKwNRSzqccA0hptKy3MHUZ2 + +zeHzuRdRWGjb2rUiVxnIvPPBGxF2JHhB4ERhGgbTxRZ6wZbdW06BOE8r7pGrUpU + fCw/WRT3gGXJHpGPOzFAvr3Xl7VcDUKTVmIajnpd3SoyD1t2XsvJlSQBOWbViucH + dvE4SIKQ77vBLRlZIoXXVb6Wu7Vq+eQs1ybjwGOhnnKjz8llXcMnLzzN86STpjN4 + qGTXQy/E9+dyUP1sXn3RRwb+ZkdI77m1YY95QRNgG/hqh77IuWWg1MtTSgQnP+F2 + 7mfo0/522hObhdAe73VO3ttEPiriWy7tw3bS9daP2TAVbYyFqkvptkBb1OXRUSzq + UuWjBmZ35UlXjKQsGeUHlOiEh84aondF90A7gx0X/ktNIPRrfCGkHJcDu+HVnR7x + Kk+F0qb9+/pGLiT3rqeQTr8fYsb4xLHT7uEg1gVFB1g0kd+RQHzV74kCPgQTAQIA + KAIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AFAk/x5PoFCQtIMjoACgkQEFS3 + okvW7DAIKQ/9HvZyf+LHVSkCk92Kb6gckniin3+5ooz67hSr8miGBfK4eocqQ0H7 + bdtWjAILzR/IBY0xj6OHKhYP2k8TLc7QhQjt0dRpNkX+Iton2AZryV7vUADreYz4 + 4B0bPmhiE+LL46ET5IThLKu/KfihzkEEBa9/t178+dO9zCM2xsXaiDhMOxVE32gX + vSZKP3hmvnK/FdylUY3nWtPedr+lHpBLoHGaPH7cjI+MEEugU3oAJ0jpq3V8n4w0 + jIq2V77wfmbD9byIV7dXcxApzciK+ekwpQNQMSaceuxLlTZKcdSqo0/qmS2A863Y + ZQ0ZBe+Xyf5OI33+y+Mry+vl6Lre2VfPm3udgR10E4tWXJ9Q2CmG+zNPWt73U1FD + 7xBI7PPvOlyzCX4QJhy2Fn/fvzaNjHp4/FSiCw0HvX01epcersyun3xxPkRIjwwR + M9m5MJ0o4hhPfa97zibXSh8XXBnosBQxeg6nEnb26eorVQbqGx0ruu/W2m5/JpUf + REsFmNOBUbi8xlKNS5CZypH3Zh88EZiTFolOMEh+hT6s0l6znBAGGZ4m/Unacm5y + DHmg7unCk4JyVopQ2KHMoqG886elu+rm0ASkhyqBAk9sWKptMl3NHiYTRE/m9VAk + ugVIB2pi+8u84f+an4Hml4xlyijgYu05pqNvnLRyJDLd61hviLC8GYU= + =a34C + -----END PGP PUBLIC KEY BLOCK-----', + } + EOS + + shell('apt-key del 4BD6EC30', :acceptable_exit_codes => [0,1,2]) + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/sources.list.d/puppetlabs.list') do + it { should be_file } + end + describe 'keys should exist' do + it 'finds puppetlabs key' do + shell('apt-key list | grep 4BD6EC30') + end + end + end + end + + context 'key_source' do + context 'http://apt.puppetlabs.com/pubkey.gpg' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::source { 'puppetlabs': + ensure => present, + location => 'http://apt.puppetlabs.com', + release => 'precise', + repos => 'main', + key => '4BD6EC30', + key_source => 'http://apt.puppetlabs.com/pubkey.gpg', + } + EOS + + shell('apt-key del 4BD6EC30', :acceptable_exit_codes => [0,1,2]) + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/sources.list.d/puppetlabs.list') do + it { should be_file } + it { should contain 'deb http://apt.puppetlabs.com precise main' } + end + describe 'keys should exist' do + it 'finds puppetlabs key' do + shell('apt-key list | grep 4BD6EC30') + end + end + end + end + + context 'pin' do + context 'false' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::source { 'puppetlabs': + ensure => present, + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + pin => false, + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/puppetlabs.pref') do + it { should_not be_file } + end + end + context 'true' do + it 'should work with no errors' do + pp = <<-EOS + include '::apt' + apt::source { 'puppetlabs': + ensure => present, + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + pin => true, + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/puppetlabs.pref') do + it { should be_file } + end + end + end + +end diff --git a/modules/apt/spec/acceptance/apt_spec.rb b/modules/apt/spec/acceptance/apt_spec.rb new file mode 100644 index 0000000..13f1d50 --- /dev/null +++ b/modules/apt/spec/acceptance/apt_spec.rb @@ -0,0 +1,280 @@ +require 'spec_helper_acceptance' + +describe 'apt class', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + + context 'reset' do + it 'fixes the sources.list' do + shell('cp /etc/apt/sources.list /tmp') + end + end + + context 'always_apt_update => true' do + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': always_apt_update => true } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/apt_update/) + end + end + end + context 'always_apt_update => false' do + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': always_apt_update => false } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to_not match(/apt_update/) + end + end + end + + # disable_keys drops in a 99unauth file to ignore keys in + # other files. + context 'disable_keys => true' do + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': disable_keys => true } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/99unauth') do + it { should be_file } + it { should contain 'APT::Get::AllowUnauthenticated 1;' } + end + end + context 'disable_keys => false' do + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': disable_keys => false } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/99unauth') do + it { should_not be_file } + end + end + + # proxy_host sets the proxy to use for transfers. + # proxy_port sets the proxy port to use. + context 'proxy settings' do + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': + proxy_host => 'localhost', + proxy_port => '7042', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/01proxy') do + it { should be_file } + it { should contain 'Acquire::http::Proxy "http://localhost:7042\";' } + end + describe file('/etc/apt/apt.conf.d/proxy') do + it { should_not be_file } + end + end + + context 'purge_sources' do + it 'creates a fake apt file' do + shell('touch /etc/apt/sources.list.d/fake.list') + shell('echo "deb fake" >> /etc/apt/sources.list') + end + it 'purge_sources_list and purge_sources_list_d => true' do + pp = <<-EOS + class { 'apt': + purge_sources_list => true, + purge_sources_list_d => true, + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/sources.list') do + it { should_not contain 'deb fake' } + end + + describe file('/etc/apt/sources.list.d/fake.list') do + it { should_not be_file } + end + end + context 'proxy settings' do + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': + proxy_host => 'localhost', + proxy_port => '7042', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/01proxy') do + it { should be_file } + it { should contain 'Acquire::http::Proxy "http://localhost:7042\";' } + end + describe file('/etc/apt/apt.conf.d/proxy') do + it { should_not be_file } + end + end + + context 'purge_sources' do + context 'false' do + it 'creates a fake apt file' do + shell('touch /etc/apt/sources.list.d/fake.list') + shell('echo "deb fake" >> /etc/apt/sources.list') + end + it 'purge_sources_list and purge_sources_list_d => false' do + pp = <<-EOS + class { 'apt': + purge_sources_list => false, + purge_sources_list_d => false, + } + EOS + + apply_manifest(pp, :catch_failures => false) + end + + describe file('/etc/apt/sources.list') do + it { should contain 'deb fake' } + end + + describe file('/etc/apt/sources.list.d/fake.list') do + it { should be_file } + end + end + + context 'true' do + it 'creates a fake apt file' do + shell('touch /etc/apt/sources.list.d/fake.list') + shell('echo "deb fake" >> /etc/apt/sources.list') + end + it 'purge_sources_list and purge_sources_list_d => true' do + pp = <<-EOS + class { 'apt': + purge_sources_list => true, + purge_sources_list_d => true, + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/sources.list') do + it { should_not contain 'deb fake' } + end + + describe file('/etc/apt/sources.list.d/fake.list') do + it { should_not be_file } + end + end + end + + context 'purge_preferences' do + context 'false' do + it 'creates a preferences file' do + shell("echo 'original' > /etc/apt/preferences") + end + + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': purge_preferences => false } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences') do + it { should be_file } + it 'is not managed by Puppet' do + shell("grep 'original' /etc/apt/preferences", {:acceptable_exit_codes => 0}) + end + end + end + + context 'true' do + it 'creates a preferences file' do + shell('touch /etc/apt/preferences') + end + + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': purge_preferences => true } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences') do + it { should_not be_file } + end + end + end + + context 'purge_preferences_d' do + context 'false' do + it 'creates a preferences file' do + shell('touch /etc/apt/preferences.d/test') + end + + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': purge_preferences_d => false } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/test') do + it { should be_file } + end + end + context 'true' do + it 'creates a preferences file' do + shell('touch /etc/apt/preferences.d/test') + end + + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': purge_preferences_d => true } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/test') do + it { should_not be_file } + end + end + end + + context 'update_timeout' do + context '5000' do + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': update_timeout => '5000' } + EOS + + apply_manifest(pp, :catch_failures => true) + end + end + end + + context 'reset' do + it 'fixes the sources.list' do + shell('cp /tmp/sources.list /etc/apt') + end + end + +end diff --git a/modules/apt/spec/acceptance/backports_spec.rb b/modules/apt/spec/acceptance/backports_spec.rb new file mode 100644 index 0000000..78f21fd --- /dev/null +++ b/modules/apt/spec/acceptance/backports_spec.rb @@ -0,0 +1,73 @@ +require 'spec_helper_acceptance' + +codename = fact('lsbdistcodename') +case fact('operatingsystem') +when 'Ubuntu' + repos = 'main universe multiverse restricted' +when 'Debian' + repos = 'main contrib non-free' +end + +describe 'apt::backports class', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + context 'defaults' do + it 'should work with no errors' do + pp = <<-EOS + class { 'apt::backports': } + EOS + + apply_manifest(pp, :catch_failures => true) + end + end + + context 'release' do + it 'should work with no errors' do + pp = <<-EOS + class { 'apt::backports': release => '#{codename}' } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/sources.list.d/backports.list') do + it { should be_file } + it { should contain "#{codename}-backports #{repos}" } + end + end + + context 'location' do + it 'should work with no errors' do + pp = <<-EOS + class { 'apt::backports': release => 'precise', location => 'http://localhost/ubuntu' } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/sources.list.d/backports.list') do + it { should be_file } + it { should contain "deb http://localhost/ubuntu precise-backports #{repos}" } + end + end + + context 'pin_priority' do + it 'should work with no errors' do + pp = <<-EOS + class { 'apt::backports': pin_priority => 500, } + EOS + + apply_manifest(pp, :catch_failures => true) + end + describe file('/etc/apt/preferences.d/backports.pref') do + it { should be_file } + it { should contain "Pin-Priority: 500" } + end + end + + context 'reset' do + it 'deletes backport files' do + shell('rm -rf /etc/apt/sources.list.d/backports.list') + shell('rm -rf /etc/apt/preferences.d/backports.pref') + end + end + +end diff --git a/modules/apt/spec/acceptance/class_spec.rb b/modules/apt/spec/acceptance/class_spec.rb new file mode 100644 index 0000000..e599449 --- /dev/null +++ b/modules/apt/spec/acceptance/class_spec.rb @@ -0,0 +1,17 @@ +require 'spec_helper_acceptance' + +describe 'apt class', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + + context 'default parameters' do + # Using puppet_apply as a helper + it 'should work with no errors' do + pp = <<-EOS + class { 'apt': } + EOS + + # Run it twice and test for idempotency + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_failures => true) + end + end +end diff --git a/modules/apt/spec/acceptance/conf_spec.rb b/modules/apt/spec/acceptance/conf_spec.rb new file mode 100644 index 0000000..8a8ed63 --- /dev/null +++ b/modules/apt/spec/acceptance/conf_spec.rb @@ -0,0 +1,66 @@ +require 'spec_helper_acceptance' + +describe 'apt::conf define', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + context 'defaults' do + it 'should work with no errors' do + pp = <<-EOS + apt::conf { 'test': + content => 'test', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50test') do + it { should be_file } + it { should contain 'test' } + end + end + + context 'ensure' do + context 'absent' do + it 'should work with no errors' do + pp = <<-EOS + apt::conf { 'test': + ensure => absent, + content => 'test', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50test') do + it { should_not be_file } + end + end + end + + context 'priority' do + context '99' do + it 'should work with no errors' do + pp = <<-EOS + apt::conf { 'test': + ensure => present, + content => 'test', + priority => '99', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/99test') do + it { should be_file } + it { should contain 'test' } + end + end + end + + context 'cleanup' do + it 'deletes 99test' do + shell ('rm -rf /etc/apt/apt.conf.d/99test') + end + end +end diff --git a/modules/apt/spec/acceptance/force_spec.rb b/modules/apt/spec/acceptance/force_spec.rb new file mode 100644 index 0000000..5f4dec3 --- /dev/null +++ b/modules/apt/spec/acceptance/force_spec.rb @@ -0,0 +1,76 @@ +require 'spec_helper_acceptance' + +codename = fact('lsbdistcodename') + +describe 'apt::force define', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + context 'defaults' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::force { 'vim': } + EOS + + shell('apt-get remove -y vim') + apply_manifest(pp, :catch_failures => true) + end + + describe package('vim') do + it { should be_installed } + end + end + + context 'release' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::force { 'vim': release => '#{codename}' } + EOS + + shell('apt-get remove -y vim') + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/apt-get -y -t #{codename} install vim/) + end + end + + describe package('vim') do + it { should be_installed } + end + end + + context 'version' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::force { 'vim': version => '1.1.1' } + EOS + + shell('apt-get remove -y vim') + apply_manifest(pp, :catch_failures => false) do |r| + expect(r.stdout).to match(/apt-get -y install vim=1.1.1/) + end + end + + describe package('vim') do + it { should_not be_installed } + end + end + + context 'timeout' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::force { 'ocaml': timeout => '1' } + EOS + + shell('apt-get clean') + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/Error: Command exceeded timeout/) + end + end + + describe package('ocaml') do + it { should_not be_installed } + end + end + +end diff --git a/modules/apt/spec/acceptance/nodesets/debian-70rc1-x64.yml b/modules/apt/spec/acceptance/nodesets/debian-70rc1-x64.yml new file mode 100644 index 0000000..4b55677 --- /dev/null +++ b/modules/apt/spec/acceptance/nodesets/debian-70rc1-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + debian-70rc1-x64: + roles: + - master + platform: debian-70rc1-x64 + box : debian-70rc1-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/debian-70rc1-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/apt/spec/acceptance/nodesets/debian-73-x64.yml b/modules/apt/spec/acceptance/nodesets/debian-73-x64.yml new file mode 100644 index 0000000..d714345 --- /dev/null +++ b/modules/apt/spec/acceptance/nodesets/debian-73-x64.yml @@ -0,0 +1,11 @@ +HOSTS: + debian-73-x64: + roles: + - master + platform: debian-7-amd64 + box : debian-73-x64-virtualbox-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/debian-73-x64-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + log_level: debug + type: git \ No newline at end of file diff --git a/modules/apt/spec/acceptance/nodesets/default.yml b/modules/apt/spec/acceptance/nodesets/default.yml new file mode 100644 index 0000000..45af989 --- /dev/null +++ b/modules/apt/spec/acceptance/nodesets/default.yml @@ -0,0 +1,11 @@ +HOSTS: + ubuntu-server-12042-x64: + roles: + - master + platform: ubuntu-server-12.04-amd64 + box : ubuntu-server-12042-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-12042-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss + vagrant_ssh_port_random: true diff --git a/modules/apt/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml b/modules/apt/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml new file mode 100644 index 0000000..c1b8bdf --- /dev/null +++ b/modules/apt/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml @@ -0,0 +1,11 @@ +HOSTS: + ubuntu-server-10044-x64: + roles: + - master + platform: ubuntu-10.04-amd64 + box : ubuntu-server-10044-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-10044-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + log_level: debug + type: git diff --git a/modules/apt/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml b/modules/apt/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml new file mode 100644 index 0000000..a5f38f7 --- /dev/null +++ b/modules/apt/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + ubuntu-server-12042-x64: + roles: + - master + platform: ubuntu-server-12.04-amd64 + box : ubuntu-server-12042-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-12042-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/apt/spec/acceptance/nodesets/ubuntu-server-1404-x64.yml b/modules/apt/spec/acceptance/nodesets/ubuntu-server-1404-x64.yml new file mode 100644 index 0000000..cba1cd0 --- /dev/null +++ b/modules/apt/spec/acceptance/nodesets/ubuntu-server-1404-x64.yml @@ -0,0 +1,11 @@ +HOSTS: + ubuntu-server-1404-x64: + roles: + - master + platform: ubuntu-14.04-amd64 + box : puppetlabs/ubuntu-14.04-64-nocm + box_url : https://vagrantcloud.com/puppetlabs/ubuntu-14.04-64-nocm + hypervisor : vagrant +CONFIG: + log_level : debug + type: git diff --git a/modules/apt/spec/acceptance/pin_spec.rb b/modules/apt/spec/acceptance/pin_spec.rb new file mode 100644 index 0000000..07fc607 --- /dev/null +++ b/modules/apt/spec/acceptance/pin_spec.rb @@ -0,0 +1,286 @@ +require 'spec_helper_acceptance' + +describe 'apt::pin define', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + context 'defaults' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should be_file } + it { should contain 'Pin: release a=vim-puppet' } + end + end + + context 'ensure' do + context 'present' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': ensure => present } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should be_file } + it { should contain 'Pin: release a=vim-puppet' } + end + end + + context 'absent' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': ensure => absent } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should_not be_file } + end + end + end + + context 'order' do + context '99' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': + ensure => present, + order => '99', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/99-vim-puppet.pref') do + it { should be_file } + it { should contain 'Pin: release a=vim-puppet' } + end + end + end + + context 'packages' do + context 'test' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': + ensure => present, + packages => 'test', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should be_file } + it { should contain 'Package: test' } + it { should contain 'Pin: release a=vim-puppet' } + end + end + + context 'array' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'array': + ensure => present, + packages => ['apache', 'ntop'], + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/array.pref') do + it { should be_file } + it { should contain 'Package: apache ntop' } + it { should contain 'Pin: release a=array' } + end + end + end + + context 'release' do + context 'testrelease' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': + ensure => present, + release => 'testrelease', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should be_file } + it { should contain 'Pin: release a=testrelease' } + end + end + end + + context 'origin' do + context 'testrelease' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': + ensure => present, + origin => 'testrelease', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should be_file } + it { should contain 'Pin: origin testrelease' } + end + end + end + + context 'version' do + context '1.0.0' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': + ensure => present, + packages => 'test', + version => '1.0.0', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should be_file } + it { should contain 'Package: test' } + it { should contain 'Pin: version 1.0.0' } + end + end + end + + context 'codename' do + context 'testname' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': + ensure => present, + codename => 'testname', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should be_file } + it { should contain 'Pin: release n=testname' } + end + end + end + + context 'release_version' do + context '1.1.1' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': + ensure => present, + release_version => '1.1.1', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should be_file } + it { should contain 'Pin: release v=1.1.1' } + end + end + end + + context 'component' do + context 'testcomponent' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': + ensure => present, + component => 'testcomponent', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should be_file } + it { should contain 'Pin: release c=testcomponent' } + end + end + end + + context 'originator' do + context 'testorigin' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': + ensure => present, + originator => 'testorigin', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should be_file } + it { should contain 'Pin: release o=testorigin' } + end + end + end + + context 'label' do + context 'testlabel' do + it 'should work with no errors' do + pp = <<-EOS + include apt + apt::pin { 'vim-puppet': + ensure => present, + label => 'testlabel', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/preferences.d/vim-puppet.pref') do + it { should be_file } + it { should contain 'Pin: release l=testlabel' } + end + end + end + +end diff --git a/modules/apt/spec/acceptance/release_spec.rb b/modules/apt/spec/acceptance/release_spec.rb new file mode 100644 index 0000000..e7467bf --- /dev/null +++ b/modules/apt/spec/acceptance/release_spec.rb @@ -0,0 +1,26 @@ +require 'spec_helper_acceptance' + +describe 'apt::release class', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + context 'release_id' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::release': release_id => 'precise', } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/01release') do + it { should be_file } + it { should contain 'APT::Default-Release "precise";' } + end + end + + context 'reset' do + it 'cleans up' do + shell('rm -rf /etc/apt/apt.conf.d/01release') + end + end + +end diff --git a/modules/apt/spec/acceptance/unattended_upgrade_spec.rb b/modules/apt/spec/acceptance/unattended_upgrade_spec.rb new file mode 100644 index 0000000..6a19f4e --- /dev/null +++ b/modules/apt/spec/acceptance/unattended_upgrade_spec.rb @@ -0,0 +1,562 @@ +require 'spec_helper_acceptance' + +describe 'apt::unattended_upgrades class', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + context 'defaults' do + it 'should work with no errors' do + pp = <<-EOS + include apt + include apt::unattended_upgrades + EOS + + # Attempted workaround for problems seen on debian with + # something holding the package database open. + #shell('killall -9 apt-get') + #shell('killall -9 dpkg') + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + end + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + end + end + + context 'origins' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + origins => ['${distro_id}:${distro_codename}-test'], + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain '${distro_id}:${distro_codename}-test' } + end + end + + context 'blacklist' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + blacklist => ['puppet'] + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'puppet' } + end + end + + context 'update' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + update => '99' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::Update-Package-Lists "99";' } + end + end + + context 'download' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + download => '99' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::Download-Upgradeable-Packages "99";' } + end + end + + context 'upgrade' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + upgrade => '99' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::Unattended-Upgrade "99";' } + end + end + + context 'autoclean' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + autoclean => '99' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::AutocleanInterval "99";' } + end + end + + context 'auto_fix' do + context 'true' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + auto_fix => true + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::AutoFixInterruptedDpkg "true";' } + end + end + + context 'false' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + auto_fix => false + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::AutoFixInterruptedDpkg "false";' } + end + end + end + + context 'minimal_steps' do + context 'true' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + minimal_steps => true + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::MinimalSteps "true";' } + end + end + + context 'false' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + minimal_steps => false + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::MinimalSteps "false";' } + end + end + end + + context 'install_on_shutdown' do + context 'true' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + install_on_shutdown => true + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::InstallOnShutdown "true";' } + end + end + + context 'false' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + install_on_shutdown => false + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::InstallOnShutdown "false";' } + end + end + end + + context 'mail_to' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + mail_to => 'test@example.com' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::Mail "test@example.com";' } + end + end + + context 'mail_only_on_error' do + context 'true' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + mail_to => 'test@example.com', + mail_only_on_error => true + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::MailOnlyOnError "true";' } + end + end + + context 'false' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + mail_to => 'test@example.com', + mail_only_on_error => false, + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::MailOnlyOnError "false";' } + end + end + + context 'mail_to missing' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + mail_only_on_error => true, + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should_not contain 'Unattended-Upgrade::MailOnlyOnError "true";' } + end + end + end + + context 'remove_unused' do + context 'true' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + remove_unused => true + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::Remove-Unused-Dependencies "true";' } + end + end + + context 'false' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + remove_unused => false, + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::Remove-Unused-Dependencies "false";' } + end + end + end + + context 'auto_reboot' do + context 'true' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + auto_reboot => true + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::Automatic-Reboot "true";' } + end + end + + context 'false' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + auto_reboot => false, + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Unattended-Upgrade::Automatic-Reboot "false";' } + end + end + end + + context 'dl_limit' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + dl_limit => '99' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/50unattended-upgrades') do + it { should be_file } + it { should contain 'Acquire::http::Dl-Limit "99"' } + end + end + + context 'enable' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + enable => '2' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::Enable "2"' } + end + end + + context 'backup_interval' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + backup_interval => '2' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::BackUpArchiveInterval "2";' } + end + end + + context 'backup_level' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + backup_level => '2' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::BackUpLevel "2";' } + end + end + + context 'max_age' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + max_age => '2' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::MaxAge "2";' } + end + end + + context 'min_age' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + min_age => '2' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::MinAge "2";' } + end + end + + context 'max_size' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + max_size => '2' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::MaxSize "2";' } + end + end + + context 'download_delta' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + download_delta => '2' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::Download-Upgradeable-Packages-Debdelta "2";' } + end + end + + context 'verbose' do + it 'should work with no errors' do + pp = <<-EOS + include apt + class { 'apt::unattended_upgrades': + verbose => '2' + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/apt/apt.conf.d/10periodic') do + it { should be_file } + it { should contain 'APT::Periodic::Verbose "2";' } + end + end + +end diff --git a/modules/apt/spec/acceptance/unsupported_spec.rb b/modules/apt/spec/acceptance/unsupported_spec.rb new file mode 100644 index 0000000..3f74685 --- /dev/null +++ b/modules/apt/spec/acceptance/unsupported_spec.rb @@ -0,0 +1,10 @@ +require 'spec_helper_acceptance' + +describe 'unsupported distributions and OSes', :if => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + it 'class apt fails' do + pp = <<-EOS + class { 'apt': } + EOS + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/This module only works on Debian or derivatives like Ubuntu/i) + end +end diff --git a/modules/apt/spec/classes/apt_spec.rb b/modules/apt/spec/classes/apt_spec.rb new file mode 100644 index 0000000..a21e044 --- /dev/null +++ b/modules/apt/spec/classes/apt_spec.rb @@ -0,0 +1,170 @@ +require 'spec_helper' +describe 'apt', :type => :class do + let(:facts) { { :lsbdistid => 'Debian', :osfamily => 'Debian' } } + let :default_params do + { + :disable_keys => :undef, + :always_apt_update => false, + :purge_sources_list => false, + :purge_sources_list_d => false, + } + end + + [{}, + { + :disable_keys => true, + :always_apt_update => true, + :proxy_host => true, + :proxy_port => '3128', + :purge_sources_list => true, + :purge_sources_list_d => true, + }, + { + :purge_preferences => true, + :purge_preferences_d => true, + }, + { + :disable_keys => false + } + ].each do |param_set| + describe "when #{param_set == {} ? "using default" : "specifying"} class parameters" do + let :param_hash do + default_params.merge(param_set) + end + + let :params do + param_set + end + + let :refresh_only_apt_update do + if param_hash[:always_apt_update] + false + else + true + end + end + + it { should contain_class("apt::params") } + + it { + if param_hash[:purge_sources_list] + should contain_file("sources.list").with({ + 'path' => "/etc/apt/sources.list", + 'ensure' => "present", + 'owner' => "root", + 'group' => "root", + 'mode' => "0644", + "content" => "# Repos managed by puppet.\n" + }) + else + should contain_file("sources.list").with({ + 'path' => "/etc/apt/sources.list", + 'ensure' => "present", + 'owner' => "root", + 'group' => "root", + 'mode' => "0644", + 'content' => nil + }) + end + } + it { + if param_hash[:purge_sources_list_d] + should create_file("sources.list.d").with({ + 'path' => "/etc/apt/sources.list.d", + 'ensure' => "directory", + 'owner' => "root", + 'group' => "root", + 'purge' => true, + 'recurse' => true, + 'notify' => 'Exec[apt_update]' + }) + else + should create_file("sources.list.d").with({ + 'path' => "/etc/apt/sources.list.d", + 'ensure' => "directory", + 'owner' => "root", + 'group' => "root", + 'purge' => false, + 'recurse' => false, + 'notify' => 'Exec[apt_update]' + }) + end + } + it { + if param_hash[:purge_preferences] + should create_file('apt-preferences').with({ + :ensure => 'absent', + :path => '/etc/apt/preferences', + }) + else + should_not contain_file('apt-preferences') + end + } + + it { + if param_hash[:purge_preferences_d] + should create_file("preferences.d").with({ + 'path' => "/etc/apt/preferences.d", + 'ensure' => "directory", + 'owner' => "root", + 'group' => "root", + 'purge' => true, + 'recurse' => true, + }) + else + should create_file("preferences.d").with({ + 'path' => "/etc/apt/preferences.d", + 'ensure' => "directory", + 'owner' => "root", + 'group' => "root", + 'purge' => false, + 'recurse' => false, + }) + end + } + + it { + should contain_exec("apt_update").with({ + 'command' => "/usr/bin/apt-get update", + 'refreshonly' => refresh_only_apt_update + }) + } + + it { + if param_hash[:disable_keys] == true + should create_file("99unauth").with({ + 'content' => "APT::Get::AllowUnauthenticated 1;\n", + 'ensure' => "present", + 'path' => "/etc/apt/apt.conf.d/99unauth" + }) + elsif param_hash[:disable_keys] == false + should create_file("99unauth").with({ + 'ensure' => "absent", + 'path' => "/etc/apt/apt.conf.d/99unauth" + }) + elsif param_hash[:disable_keys] != :undef + should_not create_file("99unauth").with({ + 'path' => "/etc/apt/apt.conf.d/99unauth" + }) + end + } + describe 'when setting a proxy' do + it { + if param_hash[:proxy_host] + should contain_file('01proxy').with( + 'path' => '/etc/apt/apt.conf.d/01proxy', + 'content' => "Acquire::http::Proxy \"http://#{param_hash[:proxy_host]}:#{param_hash[:proxy_port]}\";\n", + 'notify' => "Exec[apt_update]" + ) + else + should contain_file('01proxy').with( + 'path' => '/etc/apt/apt.conf.d/01proxy', + 'notify' => 'Exec[apt_update]', + 'ensure' => 'absent' + ) + end + } + end + end + end +end diff --git a/modules/apt/spec/classes/backports_spec.rb b/modules/apt/spec/classes/backports_spec.rb new file mode 100644 index 0000000..2f67aa4 --- /dev/null +++ b/modules/apt/spec/classes/backports_spec.rb @@ -0,0 +1,101 @@ +require 'spec_helper' +describe 'apt::backports', :type => :class do + + describe 'when asigning a custom priority to backports' do + let :facts do + { + 'lsbdistcodename' => 'Karmic', + 'lsbdistid' => 'Ubuntu' + } + end + + context 'integer priority' do + let :params do { :pin_priority => 500 } end + + it { should contain_apt__source('backports').with({ + 'location' => 'http://old-releases.ubuntu.com/ubuntu', + 'release' => 'karmic-backports', + 'repos' => 'main universe multiverse restricted', + 'key' => '437D05B5', + 'key_server' => 'pgp.mit.edu', + 'pin' => 500, + }) + } + end + + context 'invalid priority' do + let :params do { :pin_priority => 'banana' } end + it 'should fail' do + expect { subject }.to raise_error(/must be an integer/) + end + end + end + + describe 'when turning on backports for ubuntu karmic' do + + let :facts do + { + 'lsbdistcodename' => 'Karmic', + 'lsbdistid' => 'Ubuntu' + } + end + + it { should contain_apt__source('backports').with({ + 'location' => 'http://old-releases.ubuntu.com/ubuntu', + 'release' => 'karmic-backports', + 'repos' => 'main universe multiverse restricted', + 'key' => '437D05B5', + 'key_server' => 'pgp.mit.edu', + 'pin' => 200, + }) + } + end + + describe "when turning on backports for debian squeeze" do + + let :facts do + { + 'lsbdistcodename' => 'Squeeze', + 'lsbdistid' => 'Debian', + } + end + + it { should contain_apt__source('backports').with({ + 'location' => 'http://backports.debian.org/debian-backports', + 'release' => 'squeeze-backports', + 'repos' => 'main contrib non-free', + 'key' => '46925553', + 'key_server' => 'pgp.mit.edu', + 'pin' => 200, + }) + } + end + + describe "when turning on backports for debian squeeze but using your own mirror" do + + let :facts do + { + 'lsbdistcodename' => 'Squeeze', + 'lsbdistid' => 'Debian' + } + end + + let :location do + 'http://mirrors.example.com/debian-backports' + end + + let :params do + { 'location' => location } + end + + it { should contain_apt__source('backports').with({ + 'location' => location, + 'release' => 'squeeze-backports', + 'repos' => 'main contrib non-free', + 'key' => '46925553', + 'key_server' => 'pgp.mit.edu', + 'pin' => 200, + }) + } + end +end diff --git a/modules/apt/spec/classes/debian_testing_spec.rb b/modules/apt/spec/classes/debian_testing_spec.rb new file mode 100644 index 0000000..6e03326 --- /dev/null +++ b/modules/apt/spec/classes/debian_testing_spec.rb @@ -0,0 +1,15 @@ +require 'spec_helper' +describe 'apt::debian::testing', :type => :class do + let(:facts) { { :lsbdistid => 'Debian', :osfamily => 'Debian' } } + it { + should contain_apt__source("debian_testing").with({ + "location" => "http://debian.mirror.iweb.ca/debian/", + "release" => "testing", + "repos" => "main contrib non-free", + "required_packages" => "debian-keyring debian-archive-keyring", + "key" => "46925553", + "key_server" => "subkeys.pgp.net", + "pin" => "-10" + }) + } +end diff --git a/modules/apt/spec/classes/debian_unstable_spec.rb b/modules/apt/spec/classes/debian_unstable_spec.rb new file mode 100644 index 0000000..8477a39 --- /dev/null +++ b/modules/apt/spec/classes/debian_unstable_spec.rb @@ -0,0 +1,15 @@ +require 'spec_helper' +describe 'apt::debian::unstable', :type => :class do + let(:facts) { { :lsbdistid => 'Debian', :osfamily => 'Debian' } } + it { + should contain_apt__source("debian_unstable").with({ + "location" => "http://debian.mirror.iweb.ca/debian/", + "release" => "unstable", + "repos" => "main contrib non-free", + "required_packages" => "debian-keyring debian-archive-keyring", + "key" => "46925553", + "key_server" => "subkeys.pgp.net", + "pin" => "-10" + }) + } +end diff --git a/modules/apt/spec/classes/init_spec.rb b/modules/apt/spec/classes/init_spec.rb new file mode 100644 index 0000000..120b7e8 --- /dev/null +++ b/modules/apt/spec/classes/init_spec.rb @@ -0,0 +1,57 @@ +require 'spec_helper' +describe 'apt' do + context 'with sources defined on valid osfamily' do + let :facts do + { :osfamily => 'Debian', + :lsbdistcodename => 'precise', + :lsbdistid => 'Debian', + } + end + let(:params) { { :sources => { + 'debian_unstable' => { + 'location' => 'http://debian.mirror.iweb.ca/debian/', + 'release' => 'unstable', + 'repos' => 'main contrib non-free', + 'required_packages' => 'debian-keyring debian-archive-keyring', + 'key' => '55BE302B', + 'key_server' => 'subkeys.pgp.net', + 'pin' => '-10', + 'include_src' => true + }, + 'puppetlabs' => { + 'location' => 'http://apt.puppetlabs.com', + 'repos' => 'main', + 'key' => '4BD6EC30', + 'key_server' => 'pgp.mit.edu', + } + } } } + + it { + should contain_file('debian_unstable.list').with({ + 'ensure' => 'present', + 'path' => '/etc/apt/sources.list.d/debian_unstable.list', + 'owner' => 'root', + 'group' => 'root', + 'mode' => '0644', + 'notify' => 'Exec[apt_update]', + }) + } + + it { should contain_file('debian_unstable.list').with_content(/^deb http:\/\/debian.mirror.iweb.ca\/debian\/ unstable main contrib non-free$/) } + it { should contain_file('debian_unstable.list').with_content(/^deb-src http:\/\/debian.mirror.iweb.ca\/debian\/ unstable main contrib non-free$/) } + + it { + should contain_file('puppetlabs.list').with({ + 'ensure' => 'present', + 'path' => '/etc/apt/sources.list.d/puppetlabs.list', + 'owner' => 'root', + 'group' => 'root', + 'mode' => '0644', + 'notify' => 'Exec[apt_update]', + }) + } + + it { should contain_file('puppetlabs.list').with_content(/^deb http:\/\/apt.puppetlabs.com precise main$/) } + it { should contain_file('puppetlabs.list').with_content(/^deb-src http:\/\/apt.puppetlabs.com precise main$/) } + end +end diff --git a/modules/apt/spec/classes/params_spec.rb b/modules/apt/spec/classes/params_spec.rb new file mode 100644 index 0000000..aa330bb --- /dev/null +++ b/modules/apt/spec/classes/params_spec.rb @@ -0,0 +1,27 @@ +require 'spec_helper' +describe 'apt::params', :type => :class do + let(:facts) { { :lsbdistid => 'Debian', :osfamily => 'Debian' } } + let (:title) { 'my_package' } + + it { should contain_apt__params } + + # There are 4 resources in this class currently + # there should not be any more resources because it is a params class + # The resources are class[apt::params], class[main], class[settings], stage[main] + it "Should not contain any resources" do + subject.resources.size.should == 4 + end + + describe "With unknown lsbdistid" do + + let(:facts) { { :lsbdistid => 'CentOS' } } + let (:title) { 'my_package' } + + it do + expect { + should compile + }.to raise_error(Puppet::Error, /Unsupported lsbdistid/) + end + + end +end diff --git a/modules/apt/spec/classes/release_spec.rb b/modules/apt/spec/classes/release_spec.rb new file mode 100644 index 0000000..e43f449 --- /dev/null +++ b/modules/apt/spec/classes/release_spec.rb @@ -0,0 +1,23 @@ +require 'spec_helper' +describe 'apt::release', :type => :class do + let(:facts) { { :lsbdistid => 'Debian' } } + let (:title) { 'my_package' } + + let :param_set do + { :release_id => 'precise' } + end + + let (:params) { param_set } + + it { should contain_class("apt::params") } + + it { + should contain_file("/etc/apt/apt.conf.d/01release").with({ + "mode" => "0644", + "owner" => "root", + "group" => "root", + "content" => "APT::Default-Release \"#{param_set[:release_id]}\";" + }) + } +end + diff --git a/modules/apt/spec/classes/unattended_upgrades_spec.rb b/modules/apt/spec/classes/unattended_upgrades_spec.rb new file mode 100644 index 0000000..a2fb48b --- /dev/null +++ b/modules/apt/spec/classes/unattended_upgrades_spec.rb @@ -0,0 +1,291 @@ +require 'spec_helper' +describe 'apt::unattended_upgrades', :type => :class do + let(:file_unattended) { '/etc/apt/apt.conf.d/50unattended-upgrades' } + let(:file_periodic) { '/etc/apt/apt.conf.d/10periodic' } + let(:facts) { { :lsbdistid => 'Debian' } } + + it { should contain_package("unattended-upgrades") } + + it { + should create_file("/etc/apt/apt.conf.d/50unattended-upgrades").with({ + "owner" => "root", + "group" => "root", + "mode" => "0644", + "require" => "Package[unattended-upgrades]", + }) + } + + it { + should create_file("/etc/apt/apt.conf.d/10periodic").with({ + "owner" => "root", + "group" => "root", + "mode" => "0644", + "require" => "Package[unattended-upgrades]", + }) + } + + describe "origins" do + describe 'on Debian' do + default_facts = { :lsbdistid => 'Debian' } + context 'defaults' do + let :facts do default_facts end + it { + should contain_file(file_unattended).with_content( + /^Unattended-Upgrade::Origins-Pattern/ + ).with_content( + /"origin=Debian,archive=stable,label=Debian-Security";/ + ) + } + end + context 'defaults with custom origin' do + let :facts do default_facts end + let :params do { :origins => ['bananana']} end + it { + should contain_file(file_unattended).with_content( + /^Unattended-Upgrade::Origins-Pattern/ + ).with_content( + /"bananana";/ + ) + } + end + context 'defaults with invalid origin' do + let :facts do default_facts end + let :params do { :origins => 'bananana'} end + it { + expect {subject}.to raise_error(/is not an Array/) + } + end + context 'squeeze' do + let :facts do default_facts.merge({:lsbdistcodename => 'squeeze'}) end + it { + should contain_file(file_unattended).with_content( + /^Unattended-Upgrade::Allowed-Origins/ + ).with_content( + /"\${distro_id} \${distro_codename}-security";/ + ).with_content( + /"\${distro_id} oldstable";/ + ) + } + end + context 'wheezy' do + let :facts do default_facts.merge({:lsbdistcodename => 'wheezy'}) end + it { + should contain_file(file_unattended).with_content( + /^Unattended-Upgrade::Origins-Pattern/ + ).with_content( + /"origin=Debian,archive=stable,label=Debian-Security";/ + ) + } + end + end + + describe 'on Ubuntu' do + default_facts = { :lsbdistid => 'Ubuntu' } + context 'default' do + let :facts do default_facts end + it { + should contain_file(file_unattended).with_content( + /^Unattended-Upgrade::Allowed-Origins/ + ).with_content( + /"\${distro_id}\:\${distro_codename}-security";/ + ) + } + end + context 'lucid' do + let :facts do default_facts.merge({:lsbdistcodename => 'lucid'}) end + it { + should contain_file(file_unattended).with_content( + /^Unattended-Upgrade::Allowed-Origins/ + ).with_content( + /"\${distro_id} \${distro_codename}-security";/ + ) + } + end + context 'precise' do + let :facts do default_facts.merge({:lsbdistcodename => 'precise'}) end + it { + should contain_file(file_unattended).with_content( + /^Unattended-Upgrade::Allowed-Origins/ + ).with_content( + /"\${distro_id}\:\${distro_codename}-security";/ + ) + } + end + context 'trusty' do + let :facts do default_facts.merge({:lsbdistcodename => 'trusty'}) end + it { + should contain_file(file_unattended).with_content( + /^Unattended-Upgrade::Allowed-Origins/ + ).with_content( + /"\${distro_id}\:\${distro_codename}-security";/ + ) + } + end + end + end + + describe "blacklist" do + describe "with param defaults" do + let(:params) {{ }} + it { should contain_file(file_unattended).with_content(/^Unattended-Upgrade::Package-Blacklist \{\n\};$/) } + end + + describe "with blacklist => []" do + let :params do + { :blacklist => ['libc6', 'libc6-dev'] } + end + it { should contain_file(file_unattended).with_content(/^Unattended-Upgrade::Package-Blacklist \{\n\t"libc6";\n\t"libc6-dev";\n\};$/) } + end + end + + describe "with update => 2" do + let :params do + { :update => "2" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::Update-Package-Lists "2";$/) } + end + + describe "with download => 2" do + let :params do + { :download => "2" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::Download-Upgradeable-Packages "2";$/) } + end + + describe "with upgrade => 2" do + let :params do + { :upgrade => "2" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::Unattended-Upgrade "2";$/) } + end + + describe "with autoclean => 2" do + let :params do + { :autoclean => "2" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::AutocleanInterval "2";$/) } + end + + describe "with auto_fix => false" do + let :params do + { :auto_fix => false } + end + it { should contain_file(file_unattended).with_content(/^Unattended-Upgrade::AutoFixInterruptedDpkg "false";$/) } + end + + describe "with minimal_steps => true" do + let :params do + { :minimal_steps => true } + end + it { should contain_file(file_unattended).with_content(/^Unattended-Upgrade::MinimalSteps "true";$/) } + end + + describe "with install_on_shutdown => true" do + let :params do + { :install_on_shutdown => true } + end + it { should contain_file(file_unattended).with_content(/^Unattended-Upgrade::InstallOnShutdown "true";$/) } + end + + describe "mail_to" do + describe "param defaults" do + let(:params) {{ }} + it { should_not contain_file(file_unattended).with_content(/^Unattended-Upgrade::Mail /) } + it { should_not contain_file(file_unattended).with_content(/^Unattended-Upgrade::MailOnlyOnError /) } + end + + describe "with mail_to => user@website, mail_only_on_error => true" do + let :params do + { :mail_to => "user@website", + :mail_only_on_error => true } + end + it { should contain_file(file_unattended).with_content(/^Unattended-Upgrade::Mail "user@website";$/) } + it { should contain_file(file_unattended).with_content(/^Unattended-Upgrade::MailOnlyOnError "true";$/) } + end + end + + describe "with remove_unused => false" do + let :params do + { :remove_unused => false } + end + it { should contain_file(file_unattended).with_content(/^Unattended-Upgrade::Remove-Unused-Dependencies "false";$/) } + end + + describe "with auto_reboot => true" do + let :params do + { :auto_reboot => true } + end + it { should contain_file(file_unattended).with_content(/^Unattended-Upgrade::Automatic-Reboot "true";$/) } + end + + describe "dl_limit" do + describe "param defaults" do + let(:params) {{ }} + it { should_not contain_file(file_unattended).with_content(/^Acquire::http::Dl-Limit /) } + end + + describe "with dl_limit => 70" do + let :params do + { :dl_limit => "70" } + end + it { should contain_file(file_unattended).with_content(/^Acquire::http::Dl-Limit "70";$/) } + end + end + + describe "with enable => 0" do + let :params do + { :enable => "0" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::Enable "0";$/) } + end + + describe "with backup_interval => 1" do + let :params do + { :backup_interval => "1" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::BackUpArchiveInterval "1";$/) } + end + + describe "with backup_level => 0" do + let :params do + { :backup_level => "0" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::BackUpLevel "0";$/) } + end + + describe "with max_age => 1" do + let :params do + { :max_age => "1" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::MaxAge "1";$/) } + end + + describe "with min_age => 1" do + let :params do + { :min_age => "1" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::MinAge "1";$/) } + end + + describe "with max_size => 1" do + let :params do + { :max_size => "1" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::MaxSize "1";$/) } + end + + describe "with download_delta => 2" do + let :params do + { :download_delta => "2" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::Download-Upgradeable-Packages-Debdelta "2";$/) } + end + + describe "with verbose => 2" do + let :params do + { :verbose => "2" } + end + it { should contain_file(file_periodic).with_content(/^APT::Periodic::Verbose "2";$/) } + end + +end diff --git a/modules/apt/spec/defines/builddep_spec.rb b/modules/apt/spec/defines/builddep_spec.rb new file mode 100644 index 0000000..a0cbaa4 --- /dev/null +++ b/modules/apt/spec/defines/builddep_spec.rb @@ -0,0 +1,19 @@ +require 'spec_helper' +describe 'apt::builddep', :type => :define do + + let(:facts) { { :lsbdistid => 'Debian' } } + let(:title) { 'my_package' } + + describe "should require apt-get update" do + it { should contain_exec("apt_update").with({ + 'command' => "/usr/bin/apt-get update", + 'refreshonly' => true + }) + } + it { should contain_anchor("apt::builddep::my_package").with({ + 'require' => 'Class[Apt::Update]', + }) + } + end + +end diff --git a/modules/apt/spec/defines/conf_spec.rb b/modules/apt/spec/defines/conf_spec.rb new file mode 100644 index 0000000..cda5900 --- /dev/null +++ b/modules/apt/spec/defines/conf_spec.rb @@ -0,0 +1,58 @@ +require 'spec_helper' +describe 'apt::conf', :type => :define do + let(:facts) { { :lsbdistid => 'Debian' } } + let :title do + 'norecommends' + end + + describe "when creating an apt preference" do + let :params do + { + :priority => '00', + :content => "Apt::Install-Recommends 0;\nApt::AutoRemove::InstallRecommends 1;\n" + } + end + + let :filename do + "/etc/apt/apt.conf.d/00norecommends" + end + + it { should contain_apt__conf('norecommends').with({ + 'priority' => '00', + 'content' => "Apt::Install-Recommends 0;\nApt::AutoRemove::InstallRecommends 1;\n" + }) + } + + it { should contain_file(filename).with({ + 'ensure' => 'present', + 'content' => "Apt::Install-Recommends 0;\nApt::AutoRemove::InstallRecommends 1;\n", + 'owner' => 'root', + 'group' => 'root', + 'mode' => '0644', + }) + } + end + + describe "when removing an apt preference" do + let :params do + { + :ensure => 'absent', + :priority => '00', + :content => "Apt::Install-Recommends 0;\nApt::AutoRemove::InstallRecommends 1;\n" + } + end + + let :filename do + "/etc/apt/apt.conf.d/00norecommends" + end + + it { should contain_file(filename).with({ + 'ensure' => 'absent', + 'content' => "Apt::Install-Recommends 0;\nApt::AutoRemove::InstallRecommends 1;\n", + 'owner' => 'root', + 'group' => 'root', + 'mode' => '0644', + }) + } + end +end diff --git a/modules/apt/spec/defines/force_spec.rb b/modules/apt/spec/defines/force_spec.rb new file mode 100644 index 0000000..0d3d6e5 --- /dev/null +++ b/modules/apt/spec/defines/force_spec.rb @@ -0,0 +1,58 @@ +require 'spec_helper' +describe 'apt::force', :type => :define do + let(:facts) { { :lsbdistid => 'Debian' } } + let :pre_condition do + 'include apt::params' + end + + let :title do + 'my_package' + end + + let :default_params do + { + :release => false, + :version => false + } + end + + describe "when using default parameters" do + let :params do + default_params + end + it { should contain_exec("/usr/bin/apt-get -y install #{title}").with( + :unless => "/usr/bin/dpkg -s #{title} | grep -q 'Status: install'", + :timeout => '300' + ) } + end + + describe "when specifying release parameter" do + let :params do + default_params.merge(:release => 'testing') + end + it { should contain_exec("/usr/bin/apt-get -y -t #{params[:release]} install #{title}").with( + :unless => "/usr/bin/test \$(/usr/bin/apt-cache policy -t #{params[:release]} #{title} | /bin/grep -E 'Installed|Candidate' | /usr/bin/uniq -s 14 | /usr/bin/wc -l) -eq 1" + ) } + end + + describe "when specifying version parameter" do + let :params do + default_params.merge(:version => '1') + end + it { should contain_exec("/usr/bin/apt-get -y install #{title}=#{params[:version]}").with( + :unless => "/usr/bin/dpkg -s #{title} | grep -q 'Version: #{params[:version]}'" + ) } + end + + describe "when specifying release and version parameters" do + let :params do + default_params.merge( + :release => 'testing', + :version => '1' + ) + end + it { should contain_exec("/usr/bin/apt-get -y -t #{params[:release]} install #{title}=1").with( + :unless => "/usr/bin/apt-cache policy -t #{params[:release]} #{title} | /bin/grep -q 'Installed: #{params[:version]}'" + ) } + end +end diff --git a/modules/apt/spec/defines/hold_spec.rb b/modules/apt/spec/defines/hold_spec.rb new file mode 100644 index 0000000..731e218 --- /dev/null +++ b/modules/apt/spec/defines/hold_spec.rb @@ -0,0 +1,100 @@ +require 'spec_helper' +describe 'apt::hold' do + let :facts do { + :osfamily => 'Debian', + :lsbdistid => 'Debian', + :lsbrelease => 'wheezy', + } end + + let :title do + 'vim' + end + + let :default_params do { + :version => '1.1.1', + } end + + describe 'default params' do + let :params do default_params end + + it 'creates an apt preferences file' do + should contain_apt__hold(title).with({ + :ensure => 'present', + :package => title, + :version => params[:version], + :priority => 1001, + }) + + should contain_apt__pin("hold #{title} at #{params[:version]}").with({ + :ensure => 'present', + :packages => title, + :version => params[:version], + :priority => 1001, + }) + end + end + + describe 'ensure => absent' do + let :params do default_params.merge({:ensure => 'absent',}) end + + it 'creates an apt preferences file' do + should contain_apt__hold(title).with({ + :ensure => params[:ensure], + }) + + should contain_apt__pin("hold #{title} at #{params[:version]}").with({ + :ensure => params[:ensure], + }) + end + end + + describe 'priority => 990' do + let :params do default_params.merge({:priority => 990,}) end + + it 'creates an apt preferences file' do + should contain_apt__hold(title).with({ + :ensure => 'present', + :package => title, + :version => params[:version], + :priority => params[:priority], + }) + + should contain_apt__pin("hold #{title} at #{params[:version]}").with({ + :ensure => 'present', + :packages => title, + :version => params[:version], + :priority => params[:priority], + }) + end + end + + describe 'validation' do + context 'version => {}' do + let :params do { :version => {}, } end + it 'should fail' do + expect { subject }.to raise_error(/is not a string/) + end + end + + context 'ensure => bananana' do + let :params do default_params.merge({:ensure => 'bananana',}) end + it 'should fail' do + expect { subject }.to raise_error(/does not match/) + end + end + + context 'package => []' do + let :params do default_params.merge({:package => [],}) end + it 'should fail' do + expect { subject }.to raise_error(/is not a string/) + end + end + + context 'priority => bananana' do + let :params do default_params.merge({:priority => 'bananana',}) end + it 'should fail' do + expect { subject }.to raise_error(/must be an integer/) + end + end + end +end diff --git a/modules/apt/spec/defines/key_spec.rb b/modules/apt/spec/defines/key_spec.rb new file mode 100644 index 0000000..a85d171 --- /dev/null +++ b/modules/apt/spec/defines/key_spec.rb @@ -0,0 +1,285 @@ +require 'spec_helper' + +describe 'apt::key', :type => :define do + let(:facts) { { :lsbdistid => 'Debian' } } + GPG_KEY_ID = '4BD6EC30' + + let :title do + GPG_KEY_ID + end + + describe 'normal operation' do + describe 'default options' do + it 'contains the apt::key' do + should contain_apt__key(title).with({ + :key => title, + :ensure => 'present', + }) + end + it 'contains the apt_key' do + should contain_apt_key(title).with({ + :id => title, + :ensure => 'present', + :source => nil, + :server => nil, + :content => nil, + :keyserver_options => nil, + }) + end + it 'contains the apt_key present anchor' do + should contain_anchor("apt_key #{title} present") + end + end + + describe 'title and key =>' do + let :title do + 'puppetlabs' + end + + let :params do { + :key => GPG_KEY_ID, + } end + + it 'contains the apt::key' do + should contain_apt__key(title).with({ + :key => GPG_KEY_ID, + :ensure => 'present', + }) + end + it 'contains the apt_key' do + should contain_apt_key(title).with({ + :id => GPG_KEY_ID, + :ensure => 'present', + :source => nil, + :server => nil, + :content => nil, + :keyserver_options => nil, + }) + end + it 'contains the apt_key present anchor' do + should contain_anchor("apt_key #{GPG_KEY_ID} present") + end + end + + describe 'ensure => absent' do + let :params do { + :ensure => 'absent', + } end + + it 'contains the apt::key' do + should contain_apt__key(title).with({ + :key => title, + :ensure => 'absent', + }) + end + it 'contains the apt_key' do + should contain_apt_key(title).with({ + :id => title, + :ensure => 'absent', + :source => nil, + :server => nil, + :content => nil, + :keyserver_options => nil, + }) + end + it 'contains the apt_key absent anchor' do + should contain_anchor("apt_key #{title} absent") + end + end + + describe 'key_content =>' do + let :params do { + :key_content => 'GPG key content', + } end + + it 'contains the apt::key' do + should contain_apt__key(title).with({ + :key => title, + :ensure => 'present', + :key_content => params[:key_content], + }) + end + it 'contains the apt_key' do + should contain_apt_key(title).with({ + :id => title, + :ensure => 'present', + :source => nil, + :server => nil, + :content => params[:key_content], + :keyserver_options => nil, + }) + end + it 'contains the apt_key present anchor' do + should contain_anchor("apt_key #{title} present") + end + end + + describe 'key_source =>' do + let :params do { + :key_source => 'http://apt.puppetlabs.com/pubkey.gpg', + } end + + it 'contains the apt::key' do + should contain_apt__key(title).with({ + :key => title, + :ensure => 'present', + :key_source => params[:key_source], + }) + end + it 'contains the apt_key' do + should contain_apt_key(title).with({ + :id => title, + :ensure => 'present', + :source => params[:key_source], + :server => nil, + :content => nil, + :keyserver_options => nil, + }) + end + it 'contains the apt_key present anchor' do + should contain_anchor("apt_key #{title} present") + end + end + + describe 'key_server =>' do + let :params do { + :key_server => 'pgp.mit.edu', + } end + + it 'contains the apt::key' do + should contain_apt__key(title).with({ + :key => title, + :ensure => 'present', + :key_server => 'pgp.mit.edu', + }) + end + it 'contains the apt_key' do + should contain_apt_key(title).with({ + :id => title, + :ensure => 'present', + :source => nil, + :server => params[:key_server], + :content => nil, + :keyserver_options => nil, + }) + end + it 'contains the apt_key present anchor' do + should contain_anchor("apt_key #{title} present") + end + end + + describe 'key_options =>' do + let :params do { + :key_options => 'debug', + } end + + it 'contains the apt::key' do + should contain_apt__key(title).with({ + :key => title, + :ensure => 'present', + :key_options => 'debug', + }) + end + it 'contains the apt_key' do + should contain_apt_key(title).with({ + :id => title, + :ensure => 'present', + :source => nil, + :server => nil, + :content => nil, + :keyserver_options => params[:key_options], + }) + end + it 'contains the apt_key present anchor' do + should contain_anchor("apt_key #{title} present") + end + end + end + + describe 'validation' do + context 'invalid key' do + let :title do + 'Out of rum. Why? Why are we out of rum?' + end + it 'fails' do + expect { subject }.to raise_error(/does not match/) + end + end + + context 'invalid source' do + let :params do { + :key_source => 'afp://puppetlabs.com/key.gpg', + } end + it 'fails' do + expect { subject }.to raise_error(/does not match/) + end + end + + context 'invalid content' do + let :params do { + :key_content => [], + } end + it 'fails' do + expect { subject }.to raise_error(/is not a string/) + end + end + + context 'invalid server' do + let :params do { + :key_server => 'two bottles of rum', + } end + it 'fails' do + expect { subject }.to raise_error(/must be a valid domain name/) + end + end + + context 'invalid keyserver_options' do + let :params do { + :key_options => {}, + } end + it 'fails' do + expect { subject }.to raise_error(/is not a string/) + end + end + end + + describe 'duplication' do + context 'two apt::key resources for same key, different titles' do + let :pre_condition do + "apt::key { 'duplicate': key => #{title}, }" + end + + it 'contains two apt::key resources' do + should contain_apt__key('duplicate').with({ + :key => title, + :ensure => 'present', + }) + should contain_apt__key(title).with({ + :key => title, + :ensure => 'present', + }) + end + + it 'contains only a single apt_key' do + should contain_apt_key('duplicate').with({ + :id => title, + :ensure => 'present', + :source => nil, + :server => nil, + :content => nil, + :keyserver_options => nil, + }) + should_not contain_apt_key(title) + end + end + + context 'two apt::key resources, different ensure' do + let :pre_condition do + "apt::key { 'duplicate': key => #{title}, ensure => 'absent', }" + end + it 'informs the user of the impossibility' do + expect { subject }.to raise_error(/already ensured as absent/) + end + end + end +end diff --git a/modules/apt/spec/defines/pin_spec.rb b/modules/apt/spec/defines/pin_spec.rb new file mode 100644 index 0000000..d79462c --- /dev/null +++ b/modules/apt/spec/defines/pin_spec.rb @@ -0,0 +1,120 @@ +require 'spec_helper' +describe 'apt::pin', :type => :define do + let(:facts) { { :lsbdistid => 'Debian' } } + let(:title) { 'my_pin' } + + let :default_params do + { + :ensure => 'present', + :order => '', + :packages => '*', + :priority => '0', + :release => nil + } + end + + [ + { :params => {}, + :content => "Explanation: : my_pin\nPackage: *\nPin: release a=my_pin\nPin-Priority: 0\n" + }, + { + :params => { + :packages => 'apache', + :priority => '1' + }, + :content => "Explanation: : my_pin\nPackage: apache\nPin: release a=my_pin\nPin-Priority: 1\n" + }, + { + :params => { + :order => 50, + :packages => 'apache', + :priority => '1' + }, + :content => "Explanation: : my_pin\nPackage: apache\nPin: release a=my_pin\nPin-Priority: 1\n" + }, + { + :params => { + :ensure => 'absent', + :packages => 'apache', + :priority => '1' + }, + :content => "Explanation: : my_pin\nPackage: apache\nPin: release a=my_pin\nPin-Priority: 1\n" + }, + { + :params => { + :packages => 'apache', + :priority => '1', + :release => 'my_newpin' + }, + :content => "Explanation: : my_pin\nPackage: apache\nPin: release a=my_newpin\nPin-Priority: 1\n" + }, + { + :params => { + :packages => 'apache', + :priority => '1', + :version => '2.2.16*' + }, + :content => "Explanation: : my_pin\nPackage: apache\nPin: version 2.2.16*\nPin-Priority: 1\n" + }, + { + :params => { + :priority => '1', + :origin => 'ftp.de.debian.org' + }, + :content => "Explanation: : my_pin\nPackage: *\nPin: origin ftp.de.debian.org\nPin-Priority: 1\n" + }, + { + :params => { + :packages => 'apache', + :priority => '1', + :release => 'stable', + :codename => 'wheezy', + :release_version => '3.0', + :component => 'main', + :originator => 'Debian', + :label => 'Debian' + }, + :content => "Explanation: : my_pin\nPackage: apache\nPin: release a=stable, n=wheezy, v=3.0, c=main, o=Debian, l=Debian\nPin-Priority: 1\n" + }, + { + :params => { + :packages => ['apache', 'ntop'], + }, + :content => "Explanation: : my_pin\nPackage: apache ntop\nPin: release a=my_pin\nPin-Priority: 0\n" + }, + ].each do |param_set| + describe "when #{param_set == {} ? "using default" : "specifying"} define parameters" do + let :param_hash do + default_params.merge(param_set[:params]) + end + + let :params do + param_set[:params] + end + + it { should contain_class("apt::params") } + + it { should contain_file("#{title}.pref").with({ + 'ensure' => param_hash[:ensure], + 'path' => "/etc/apt/preferences.d/#{param_hash[:order] == '' ? "" : "#{param_hash[:order]}-"}#{title}.pref", + 'owner' => 'root', + 'group' => 'root', + 'mode' => '0644', + 'content' => param_set[:content], + }) + } + end + end + + describe 'resource title with invalid chars' do + context 'spaces' do + let(:title) { 'oh my god this is not valid' } + it { should contain_file('oh_my_god_this_is_not_valid.pref') } + end + + context '#$&*$' do + let(:title) { 'so && many $* invalid @! things' } + it { should contain_file('so____many____invalid____things.pref') } + end + end +end diff --git a/modules/apt/spec/defines/ppa_spec.rb b/modules/apt/spec/defines/ppa_spec.rb new file mode 100644 index 0000000..6944f9b --- /dev/null +++ b/modules/apt/spec/defines/ppa_spec.rb @@ -0,0 +1,158 @@ +require 'spec_helper' +describe 'apt::ppa', :type => :define do + [ + { + :lsbdistrelease => '11.04', + :lsbdistcodename => 'natty', + :operatingsystem => 'Ubuntu', + :lsbdistid => 'Ubuntu', + :package => 'python-software-properties' + }, + { + :lsbdistrelease => '12.10', + :lsbdistcodename => 'quantal', + :operatingsystem => 'Ubuntu', + :lsbdistid => 'Ubuntu', + :package => 'software-properties-common' + }, + ].each do |platform| + context "on #{platform[:lsbdistcodename]}" do + let :facts do + { + :lsbdistrelease => platform[:lsbdistrelease], + :lsbdistcodename => platform[:lsbdistcodename], + :operatingsystem => platform[:operatingsystem], + :lsbdistid => platform[:lsbdistid], + :osfamily => 'Debian', + } + end + let :release do + "#{platform[:lsbdistcodename]}" + end + let :package do + "#{platform[:package]}" + end + let :options do + "-y" + end + ['ppa:dans_ppa', 'dans_ppa','ppa:dans-daily/ubuntu'].each do |t| + describe "with title #{t}" do + let :pre_condition do + 'class { "apt": }' + end + let :title do + t + end + let :filename do + t.sub(/^ppa:/,'').gsub('/','-') << "-" << "#{release}.list" + end + + it { should contain_package("#{package}") } + + it { should contain_exec("apt_update").with( + 'command' => '/usr/bin/apt-get update', + 'refreshonly' => true + ) + } + + it { should contain_exec("add-apt-repository-#{t}").with( + 'command' => "/usr/bin/add-apt-repository #{options} #{t}", + 'unless' => "/usr/bin/test -s /etc/apt/sources.list.d/#{filename}", + 'require' => ["File[sources.list.d]", "Package[#{package}]"], + 'notify' => "Exec[apt_update]" + ) + } + + it { should create_file("/etc/apt/sources.list.d/#{filename}").with( + 'ensure' => 'file', + 'require' => "Exec[add-apt-repository-#{t}]" + ) + } + end + end + describe 'without a proxy defined' do + let :title do + 'rspec_ppa' + end + let :pre_condition do + 'class { "apt": + proxy_host => false + }' + end + let :filename do + "#{title}-#{release}.list" + end + + it { should contain_exec("add-apt-repository-#{title}").with( + 'environment' => [], + 'command' => "/usr/bin/add-apt-repository #{options} #{title}", + 'unless' => "/usr/bin/test -s /etc/apt/sources.list.d/#{filename}", + 'require' => ["File[sources.list.d]", "Package[#{package}]"], + 'notify' => "Exec[apt_update]" + ) + } + end + + describe 'behind a proxy' do + let :title do + 'rspec_ppa' + end + let :pre_condition do + 'class { "apt": + proxy_host => "user:pass@proxy", + }' + end + let :filename do + "#{title}-#{release}.list" + end + + it { should contain_exec("add-apt-repository-#{title}").with( + 'environment' => [ + "http_proxy=http://user:pass@proxy:8080", + "https_proxy=http://user:pass@proxy:8080", + ], + 'command' => "/usr/bin/add-apt-repository #{options} #{title}", + 'unless' => "/usr/bin/test -s /etc/apt/sources.list.d/#{filename}", + 'require' => ["File[sources.list.d]", "Package[#{package}]"], + 'notify' => "Exec[apt_update]" + ) + } + end + end + end + + [ { :lsbdistcodename => 'natty', + :package => 'python-software-properties' }, + { :lsbdistcodename => 'quantal', + :package => 'software-properties-common'}, + ].each do |platform| + context "on #{platform[:lsbdistcodename]}" do + describe "it should not error if package['#{platform[:package]}'] is already defined" do + let :pre_condition do + 'class {"apt": }' + + 'package { "#{platform[:package]}": }->Apt::Ppa["ppa"]' + end + let :facts do + {:lsbdistcodename => '#{platform[:lsbdistcodename]}', + :operatingsystem => 'Ubuntu', + :lsbdistid => 'Ubuntu', + :osfamily => 'Debian'} + end + let(:title) { "ppa" } + let(:release) { "#{platform[:lsbdistcodename]}" } + it { should contain_package('#{platform[:package]}') } + end + end + end + + describe "without Class[apt] should raise a Puppet::Error" do + let(:release) { "natty" } + let(:title) { "ppa" } + it { expect { should contain_apt__ppa(title) }.to raise_error(Puppet::Error) } + end + + describe "without release should raise a Puppet::Error" do + let(:title) { "ppa:" } + it { expect { should contain_apt__ppa(:release) }.to raise_error(Puppet::Error) } + end +end diff --git a/modules/apt/spec/defines/source_spec.rb b/modules/apt/spec/defines/source_spec.rb new file mode 100644 index 0000000..34b3942 --- /dev/null +++ b/modules/apt/spec/defines/source_spec.rb @@ -0,0 +1,172 @@ +require 'spec_helper' + +describe 'apt::source', :type => :define do + let(:facts) { { :lsbdistid => 'Debian' } } + GPG_KEY_ID = '4BD6EC30' + + let :title do + 'my_source' + end + + let :default_params do + { + :ensure => 'present', + :location => '', + :release => 'karmic', + :repos => 'main', + :include_src => true, + :required_packages => false, + :key => false, + :key_server => false, + :key_content => false, + :key_source => false, + :pin => false + } + end + + [{}, + { + :location => 'http://example.com', + :release => 'precise', + :repos => 'security', + :include_src => false, + :required_packages => 'apache', + :key => GPG_KEY_ID, + :key_server => 'keyserver.debian.com', + :pin => '600', + :key_content => 'ABCD1234' + }, + { + :key => GPG_KEY_ID, + :key_server => 'keyserver.debian.com', + }, + { + :ensure => 'absent', + :location => 'http://example.com', + :release => 'precise', + :repos => 'security', + }, + { + :release => '', + }, + { + :release => 'custom', + }, + { + :architecture => 'amd64', + } + ].each do |param_set| + describe "when #{param_set == {} ? "using default" : "specifying"} class parameters" do + let :param_hash do + default_params.merge(param_set) + end + + let :facts do + {:lsbdistcodename => 'karmic', :lsbdistid => 'Ubuntu'} + end + + let :params do + param_set + end + + let :filename do + "/etc/apt/sources.list.d/#{title}.list" + end + + let :content do + content = "# #{title}" + if param_hash[:architecture] + arch = "[arch=#{param_hash[:architecture]}] " + end + content << "\ndeb #{arch}#{param_hash[:location]} #{param_hash[:release]} #{param_hash[:repos]}\n" + + if param_hash[:include_src] + content << "deb-src #{arch}#{param_hash[:location]} #{param_hash[:release]} #{param_hash[:repos]}\n" + end + content + end + + it { should contain_apt__params } + + it { should contain_file("#{title}.list").with({ + 'ensure' => param_hash[:ensure], + 'path' => filename, + 'owner' => 'root', + 'group' => 'root', + 'mode' => '0644', + 'content' => content, + }) + } + + it { + if param_hash[:pin] + should contain_apt__pin(title).with({ + "priority" => param_hash[:pin], + "before" => "File[#{title}.list]" + }) + else + should_not contain_apt__pin(title).with({ + "priority" => param_hash[:pin], + "before" => "File[#{title}.list]" + }) + end + } + + it { + should contain_exec("apt_update").with({ + "command" => "/usr/bin/apt-get update", + "refreshonly" => true + }) + } + + it { + if param_hash[:required_packages] + should contain_exec("Required packages: '#{param_hash[:required_packages]}' for #{title}").with({ + "command" => "/usr/bin/apt-get -y install #{param_hash[:required_packages]}", + "subscribe" => "File[#{title}.list]", + "refreshonly" => true, + "before" => 'Exec[apt_update]', + }) + else + should_not contain_exec("Required packages: '#{param_hash[:required_packages]}' for #{title}").with({ + "command" => "/usr/bin/apt-get -y install #{param_hash[:required_packages]}", + "subscribe" => "File[#{title}.list]", + "refreshonly" => true + }) + end + } + + it { + key_server = param_hash[:key_server] || nil + key_content = param_hash[:key_content] || nil + key_source = param_hash[:key_source] || nil + if param_hash[:key] + should contain_apt__key("Add key: #{param_hash[:key]} from Apt::Source #{title}").with({ + "key" => param_hash[:key], + "ensure" => :present, + "key_server" => key_server, + "key_content" => key_content, + "key_source" => key_source, + "before" => "File[#{title}.list]" + }) + else + should_not contain_apt__key("Add key: #{param_hash[:key]} from Apt::Source #{title}").with({ + "key" => param_hash[:key], + "ensure" => :present, + "key_server" => param_hash[:key_server], + "key_content" => param_hash[:key_content], + "key_source" => param_hash[:key_source], + "before" => "File[#{title}.list]" + }) + end + } + end + end + describe "without release should raise a Puppet::Error" do + let(:default_params) { Hash.new } + let(:facts) { Hash.new } + it { expect { should raise_error(Puppet::Error) } } + let(:facts) { { :lsbdistcodename => 'lucid', :lsbdistid => 'Ubuntu' } } + it { should contain_apt__source(title) } + end +end diff --git a/modules/apt/spec/spec_helper.rb b/modules/apt/spec/spec_helper.rb new file mode 100644 index 0000000..2c6f566 --- /dev/null +++ b/modules/apt/spec/spec_helper.rb @@ -0,0 +1 @@ +require 'puppetlabs_spec_helper/module_spec_helper' diff --git a/modules/apt/spec/spec_helper_acceptance.rb b/modules/apt/spec/spec_helper_acceptance.rb new file mode 100644 index 0000000..3352564 --- /dev/null +++ b/modules/apt/spec/spec_helper_acceptance.rb @@ -0,0 +1,33 @@ +require 'beaker-rspec' + +# Install Puppet +unless ENV['RS_PROVISION'] == 'no' + hosts.each do |host| + if host.is_pe? + install_pe + else + install_puppet + on host, "mkdir -p #{host['distmoduledir']}" + end + end +end + +UNSUPPORTED_PLATFORMS = ['RedHat','Suse','windows','AIX','Solaris'] + +RSpec.configure do |c| + # Project root + proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) + + # Readable test descriptions + c.formatter = :documentation + + # Configure all nodes in nodeset + c.before :suite do + # Install module and dependencies + puppet_module_install(:source => proj_root, :module_name => 'apt') + hosts.each do |host| + shell('/bin/touch /etc/puppet/hiera.yaml') + shell('puppet module install puppetlabs-stdlib --version 2.2.1', { :acceptable_exit_codes => [0,1] }) + end + end +end diff --git a/modules/apt/spec/unit/puppet/type/apt_key_spec.rb b/modules/apt/spec/unit/puppet/type/apt_key_spec.rb new file mode 100644 index 0000000..c29f82b --- /dev/null +++ b/modules/apt/spec/unit/puppet/type/apt_key_spec.rb @@ -0,0 +1,160 @@ +require 'spec_helper' +require 'puppet' + +describe Puppet::Type::type(:apt_key) do + context 'only namevar 32bit key id' do + let(:resource) { Puppet::Type.type(:apt_key).new( + :id => '4BD6EC30' + )} + it 'id is set' do + resource[:id].should eq '4BD6EC30' + end + + it 'name is set to id' do + resource[:name].should eq '4BD6EC30' + end + + it 'keyserver is default' do + resource[:server].should eq :'keyserver.ubuntu.com' + end + + it 'source is not set' do + resource[:source].should eq nil + end + + it 'content is not set' do + resource[:content].should eq nil + end + end + + context 'with a lowercase 32bit key id' do + let(:resource) { Puppet::Type.type(:apt_key).new( + :id => '4bd6ec30' + )} + it 'id is set' do + resource[:id].should eq '4BD6EC30' + end + end + + context 'with a 64bit key id' do + let(:resource) { Puppet::Type.type(:apt_key).new( + :id => 'FFFFFFFF4BD6EC30' + )} + it 'id is set' do + resource[:id].should eq '4BD6EC30' + end + end + + context 'with a 0x formatted key id' do + let(:resource) { Puppet::Type.type(:apt_key).new( + :id => '0x4BD6EC30' + )} + it 'id is set' do + resource[:id].should eq '4BD6EC30' + end + end + + context 'with a 0x formatted lowercase key id' do + let(:resource) { Puppet::Type.type(:apt_key).new( + :id => '0x4bd6ec30' + )} + it 'id is set' do + resource[:id].should eq '4BD6EC30' + end + end + + context 'with a 0x formatted 64bit key id' do + let(:resource) { Puppet::Type.type(:apt_key).new( + :id => '0xFFFFFFFF4BD6EC30' + )} + it 'id is set' do + resource[:id].should eq '4BD6EC30' + end + end + + context 'with source' do + let(:resource) { Puppet::Type.type(:apt_key).new( + :id => '4BD6EC30', + :source => 'http://apt.puppetlabs.com/pubkey.gpg' + )} + + it 'source is set to the URL' do + resource[:source].should eq 'http://apt.puppetlabs.com/pubkey.gpg' + end + end + + context 'with content' do + let(:resource) { Puppet::Type.type(:apt_key).new( + :id => '4BD6EC30', + :content => 'http://apt.puppetlabs.com/pubkey.gpg' + )} + + it 'content is set to the string' do + resource[:content].should eq 'http://apt.puppetlabs.com/pubkey.gpg' + end + end + + context 'with keyserver' do + let(:resource) { Puppet::Type.type(:apt_key).new( + :id => '4BD6EC30', + :server => 'http://keyring.debian.org' + )} + + it 'keyserver is set to Debian' do + resource[:server].should eq 'http://keyring.debian.org' + end + end + + context 'validation' do + it 'raises an error if content and source are set' do + expect { Puppet::Type.type(:apt_key).new( + :id => '4BD6EC30', + :source => 'http://apt.puppetlabs.com/pubkey.gpg', + :content => 'Completely invalid as a GPG key' + )}.to raise_error(/content and source are mutually exclusive/) + end + + it 'raises an error if a weird length key is used' do + expect { Puppet::Type.type(:apt_key).new( + :id => 'F4BD6EC30', + :source => 'http://apt.puppetlabs.com/pubkey.gpg', + :content => 'Completely invalid as a GPG key' + )}.to raise_error(/Valid values match/) + end + + it 'raises an error when an invalid URI scheme is used in source' do + expect { Puppet::Type.type(:apt_key).new( + :id => '4BD6EC30', + :source => 'hkp://pgp.mit.edu' + )}.to raise_error(/Valid values match/) + end + + it 'allows the http URI scheme in source' do + expect { Puppet::Type.type(:apt_key).new( + :id => '4BD6EC30', + :source => 'http://pgp.mit.edu' + )}.to_not raise_error + end + + it 'allows the https URI scheme in source' do + expect { Puppet::Type.type(:apt_key).new( + :id => '4BD6EC30', + :source => 'https://pgp.mit.edu' + )}.to_not raise_error + end + + it 'allows the ftp URI scheme in source' do + expect { Puppet::Type.type(:apt_key).new( + :id => '4BD6EC30', + :source => 'ftp://pgp.mit.edu' + )}.to_not raise_error + end + + it 'allows an absolute path in source' do + expect { Puppet::Type.type(:apt_key).new( + :id => '4BD6EC30', + :source => '/path/to/a/file' + )}.to_not raise_error + end + end +end diff --git a/modules/apt/templates/10periodic.erb b/modules/apt/templates/10periodic.erb new file mode 100644 index 0000000..5737c9a --- /dev/null +++ b/modules/apt/templates/10periodic.erb @@ -0,0 +1,12 @@ +APT::Periodic::Enable "<%= @enable %>"; +APT::Periodic::BackUpArchiveInterval "<%= @backup_interval %>"; +APT::Periodic::BackUpLevel "<%= @backup_level %>"; +APT::Periodic::MaxAge "<%= @max_age %>"; +APT::Periodic::MinAge "<%= @min_age %>"; +APT::Periodic::MaxSize "<%= @max_size %>"; +APT::Periodic::Update-Package-Lists "<%= @update %>"; +APT::Periodic::Download-Upgradeable-Packages "<%= @download %>"; +APT::Periodic::Download-Upgradeable-Packages-Debdelta "<%= @download_delta %>"; +APT::Periodic::Unattended-Upgrade "<%= @upgrade %>"; +APT::Periodic::AutocleanInterval "<%= @autoclean %>"; +APT::Periodic::Verbose "<%= @verbose %>"; diff --git a/modules/apt/templates/50unattended-upgrades.erb b/modules/apt/templates/50unattended-upgrades.erb new file mode 100644 index 0000000..1177922 --- /dev/null +++ b/modules/apt/templates/50unattended-upgrades.erb @@ -0,0 +1,57 @@ +// Automatically upgrade packages from these (origin:archive) pairs +<%- if @legacy_origin -%> +Unattended-Upgrade::Allowed-Origins { +<%- else -%> +Unattended-Upgrade::Origins-Pattern { +<%- end -%> +<% @origins.each do |origin| -%> + "<%= origin %>"; +<% end -%> +}; + +// List of packages to not update +Unattended-Upgrade::Package-Blacklist { +<% @blacklist.each do |package| -%> + "<%= package %>"; +<% end -%> +}; + +// This option allows you to control if on a unclean dpkg exit +// unattended-upgrades will automatically run +// dpkg --force-confold --configure -a +// The default is true, to ensure updates keep getting installed +Unattended-Upgrade::AutoFixInterruptedDpkg "<%= @auto_fix %>"; + +// Split the upgrade into the smallest possible chunks so that +// they can be interrupted with SIGUSR1. 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) +Unattended-Upgrade::MinimalSteps "<%= @minimal_steps %>"; + +// Install all unattended-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 +Unattended-Upgrade::InstallOnShutdown "<%= @install_on_shutdown %>"; + +// 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 @mail_to != "NONE" %>Unattended-Upgrade::Mail "<%= @mail_to %>";<% 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 +<% if @mail_to != "NONE" %>Unattended-Upgrade::MailOnlyOnError "<%= @mail_only_on_error %>";<% end %> + +// Do automatic removal of new unused dependencies after the upgrade +// (equivalent to apt-get autoremove) +Unattended-Upgrade::Remove-Unused-Dependencies "<%= @remove_unused %>"; + +// Automatically reboot *WITHOUT CONFIRMATION* if a +// the file /var/run/reboot-required is found after the upgrade +Unattended-Upgrade::Automatic-Reboot "<%= @auto_reboot %>"; + + +// Use apt bandwidth limit feature, this example limits the download +// speed to 70kb/sec +<% if @dl_limit != "NONE" %>Acquire::http::Dl-Limit "<%= @dl_limit %>";<% end %> diff --git a/modules/apt/templates/pin.pref.erb b/modules/apt/templates/pin.pref.erb new file mode 100644 index 0000000..26b2516 --- /dev/null +++ b/modules/apt/templates/pin.pref.erb @@ -0,0 +1,21 @@ +<%- +@pin = "release a=#{@name}" # default value +if @pin_release.length > 0 + options = [] + options.push("a=#{@release}") if @release.length > 0 + options.push("n=#{@codename}") if @codename.length > 0 + options.push("v=#{@release_version}") if @release_version.length > 0 + options.push("c=#{@component}") if @component.length > 0 + options.push("o=#{@originator}") if @originator.length > 0 + options.push("l=#{@label}") if @label.length > 0 + @pin = "release #{options.join(', ')}" +elsif @version.length > 0 + @pin = "version #{@version}" +elsif @origin.length > 0 + @pin = "origin #{@origin}" +end +-%> +Explanation: <%= @explanation %> +Package: <%= @packages_string %> +Pin: <%= @pin %> +Pin-Priority: <%= @priority %> diff --git a/modules/apt/templates/source.list.erb b/modules/apt/templates/source.list.erb new file mode 100644 index 0000000..9946966 --- /dev/null +++ b/modules/apt/templates/source.list.erb @@ -0,0 +1,5 @@ +# <%= @name %> +deb <% if @architecture %>[arch=<%= @architecture %>] <% end %><%= @location %> <%= @release_real %> <%= @repos %> +<%- if @include_src then -%> +deb-src <% if @architecture %>[arch=<%= @architecture %>] <% end %><%= @location %> <%= @release_real %> <%= @repos %> +<%- end -%> diff --git a/modules/apt/tests/builddep.pp b/modules/apt/tests/builddep.pp new file mode 100644 index 0000000..8b4f796 --- /dev/null +++ b/modules/apt/tests/builddep.pp @@ -0,0 +1,2 @@ +class { 'apt': } +apt::builddep{ 'glusterfs-server': } diff --git a/modules/apt/tests/debian/testing.pp b/modules/apt/tests/debian/testing.pp new file mode 100644 index 0000000..8245b3a --- /dev/null +++ b/modules/apt/tests/debian/testing.pp @@ -0,0 +1,2 @@ +class { 'apt': } +class { 'apt::debian::testing': } diff --git a/modules/apt/tests/debian/unstable.pp b/modules/apt/tests/debian/unstable.pp new file mode 100644 index 0000000..8605179 --- /dev/null +++ b/modules/apt/tests/debian/unstable.pp @@ -0,0 +1,2 @@ +class { 'apt': } +class { 'apt::debian::unstable': } diff --git a/modules/apt/tests/force.pp b/modules/apt/tests/force.pp new file mode 100644 index 0000000..59ad8f1 --- /dev/null +++ b/modules/apt/tests/force.pp @@ -0,0 +1,17 @@ +# force.pp + +# force a package from a specific release +apt::force { 'package1': + release => 'backports', +} + +# force a package to be a specific version +apt::force { 'package2': + version => '1.0.0-1', +} + +# force a package from a specific release to be a specific version +apt::force { 'package3': + release => 'sid', + version => '2.0.0-1', +} diff --git a/modules/apt/tests/init.pp b/modules/apt/tests/init.pp new file mode 100644 index 0000000..abc75af --- /dev/null +++ b/modules/apt/tests/init.pp @@ -0,0 +1 @@ +class { 'apt': } diff --git a/modules/apt/tests/key.pp b/modules/apt/tests/key.pp new file mode 100644 index 0000000..79e0e1b --- /dev/null +++ b/modules/apt/tests/key.pp @@ -0,0 +1,6 @@ +# Declare Apt key for apt.puppetlabs.com source +apt::key { 'puppetlabs': + key => '4BD6EC30', + key_server => 'pgp.mit.edu', + key_options => 'http-proxy="http://proxyuser:proxypass@example.org:3128"', +} diff --git a/modules/apt/tests/params.pp b/modules/apt/tests/params.pp new file mode 100644 index 0000000..5ddf3c6 --- /dev/null +++ b/modules/apt/tests/params.pp @@ -0,0 +1 @@ +include apt::params diff --git a/modules/apt/tests/pin.pp b/modules/apt/tests/pin.pp new file mode 100644 index 0000000..6a9024c --- /dev/null +++ b/modules/apt/tests/pin.pp @@ -0,0 +1,5 @@ +# pin a release in apt, useful for unstable repositories +apt::pin { 'foo': + packages => '*', + priority => 0, +} diff --git a/modules/apt/tests/ppa.pp b/modules/apt/tests/ppa.pp new file mode 100644 index 0000000..e728f6f --- /dev/null +++ b/modules/apt/tests/ppa.pp @@ -0,0 +1,4 @@ +class { 'apt': } + +# Example declaration of an Apt PPA +apt::ppa{ 'ppa:openstack-ppa/bleeding-edge': } diff --git a/modules/apt/tests/release.pp b/modules/apt/tests/release.pp new file mode 100644 index 0000000..823f586 --- /dev/null +++ b/modules/apt/tests/release.pp @@ -0,0 +1,4 @@ +class { 'apt': } +class { 'apt::release': + release_id => 'karmic' +} diff --git a/modules/apt/tests/source.pp b/modules/apt/tests/source.pp new file mode 100644 index 0000000..c20b596 --- /dev/null +++ b/modules/apt/tests/source.pp @@ -0,0 +1,29 @@ +# Declare the apt class to manage /etc/apt/sources.list and /etc/sources.list.d +class { 'apt': } + +# Install the puppetlabs apt source +# Release is automatically obtained from lsbdistcodename fact if available. +apt::source { 'puppetlabs': + location => 'http://apt.puppetlabs.com', + repos => 'main', + key => '4BD6EC30', + key_server => 'pgp.mit.edu', +} + +# test two sources with the same key +apt::source { 'debian_testing': + location => 'http://debian.mirror.iweb.ca/debian/', + release => 'testing', + repos => 'main contrib non-free', + key => '46925553', + key_server => 'subkeys.pgp.net', + pin => '-10', +} +apt::source { 'debian_unstable': + location => 'http://debian.mirror.iweb.ca/debian/', + release => 'unstable', + repos => 'main contrib non-free', + key => '46925553', + key_server => 'subkeys.pgp.net', + pin => '-10', +} diff --git a/modules/apt/tests/unattended_upgrades.pp b/modules/apt/tests/unattended_upgrades.pp new file mode 100644 index 0000000..3b9b49e --- /dev/null +++ b/modules/apt/tests/unattended_upgrades.pp @@ -0,0 +1 @@ +include apt::unattended_upgrades diff --git a/modules/concat/CHANGELOG b/modules/concat/CHANGELOG new file mode 100644 index 0000000..c66b922 --- /dev/null +++ b/modules/concat/CHANGELOG @@ -0,0 +1,127 @@ +2014-05-14 1.1.0 + +Summary + +This release is primarily a bugfix release since 1.1.0-rc1. + +Features: +- Improved testing, with tests moved to beaker + +Bugfixes: +- No longer attempts to set fragment owner and mode on Windows +- Fix numeric sorting +- Fix incorrect quoting +- Fix newlines + +2014-01-03 1.1.0-rc1 + +Summary: + +This release of concat was 90% written by Joshua Hoblitt, and the module team +would like to thank him for the huge amount of work he put into this release. + +This module deprecates a bunch of old parameters and usage patterns, modernizes +much of the manifest code, simplifies a whole bunch of logic and makes +improvements to almost all parts of the module. + +The other major feature is windows support, courtesy of luisfdez, with an +alternative version of the concat bash script in ruby. We've attempted to +ensure that there are no backwards incompatible changes, all users of 1.0.0 +should be able to use 1.1.0 without any failures, but you may find deprecation +warnings and we'll be aggressively moving for a 2.0 to remove those too. + +For further information on deprecations, please read: +https://github.com/puppetlabs/puppetlabs-concat/blob/master/README.md#api-deprecations + +Removed: +- Puppet 0.24 support. +- Filebucket backup of all file resources except the target concatenated file. +- Default owner/user/group values. +- Purging of long unused /usr/local/bin/concatfragments.sh + +Features: +- Windows support via a ruby version of the concat bash script. +- Huge amount of acceptance testing work added. +- Documentation (README) completely rewritten. +- New parameters in concat: + - `ensure`: Controls if the file should be present/absent at all. +- Remove requirement to include concat::setup in manifests. +- Made `gnu` parameter deprecated. +- Added parameter validation. + +Bugfixes: +- Ensure concat::setup runs before concat::fragment in all cases. +- Pluginsync references updated for modern Puppet. +- Fix incorrect group parameter. +- Use $owner instead of $id to avoid confusion with $::id +- Compatibility fixes for Puppet 2.7/ruby 1.8.7 +- Use LC_ALL=C instead of LANG=C +- Always exec the concatfragments script as root when running as root. +- Syntax and other cleanup changes. + +2013-08-09 1.0.0 + +Summary: + +Many new features and bugfixes in this release, and if you're a heavy concat +user you should test carefully before upgrading. The features should all be +backwards compatible but only light testing has been done from our side before +this release. + +Features: +- New parameters in concat: + - `replace`: specify if concat should replace existing files. + - `ensure_newline`: controls if fragments should contain a newline at the end. +- Improved README documentation. +- Add rspec:system tests (rake spec:system to test concat) + +Bugfixes +- Gracefully handle \n in a fragment resource name. +- Adding more helpful message for 'pluginsync = true' +- Allow passing `source` and `content` directly to file resource, rather than +defining resource defaults. +- Added -r flag to read so that filenames with \ will be read correctly. +- sort always uses LANG=C. +- Allow WARNMSG to contain/start with '#'. +- Replace while-read pattern with for-do in order to support Solaris. + +CHANGELOG: +- 2010/02/19 - initial release +- 2010/03/12 - add support for 0.24.8 and newer + - make the location of sort configurable + - add the ability to add shell comment based warnings to + top of files + - add the ablity to create empty files +- 2010/04/05 - fix parsing of WARN and change code style to match rest + of the code + - Better and safer boolean handling for warn and force + - Don't use hard coded paths in the shell script, set PATH + top of the script + - Use file{} to copy the result and make all fragments owned + by root. This means we can chnage the ownership/group of the + resulting file at any time. + - You can specify ensure => "/some/other/file" in concat::fragment + to include the contents of a symlink into the final file. +- 2010/04/16 - Add more cleaning of the fragment name - removing / from the $name +- 2010/05/22 - Improve documentation and show the use of ensure => +- 2010/07/14 - Add support for setting the filebucket behavior of files +- 2010/10/04 - Make the warning message configurable +- 2010/12/03 - Add flags to make concat work better on Solaris - thanks Jonathan Boyett +- 2011/02/03 - Make the shell script more portable and add a config option for root group +- 2011/06/21 - Make base dir root readable only for security +- 2011/06/23 - Set base directory using a fact instead of hardcoding it +- 2011/06/23 - Support operating as non privileged user +- 2011/06/23 - Support dash instead of bash or sh +- 2011/07/11 - Better solaris support +- 2011/12/05 - Use fully qualified variables +- 2011/12/13 - Improve Nexenta support +- 2012/04/11 - Do not use any GNU specific extensions in the shell script +- 2012/03/24 - Comply to community style guides +- 2012/05/23 - Better errors when basedir isnt set +- 2012/05/31 - Add spec tests +- 2012/07/11 - Include concat::setup in concat improving UX +- 2012/08/14 - Puppet Lint improvements +- 2012/08/30 - The target path can be different from the $name +- 2012/08/30 - More Puppet Lint cleanup +- 2012/09/04 - RELEASE 0.2.0 +- 2012/12/12 - Added (file) $replace parameter to concat diff --git a/modules/concat/Gemfile b/modules/concat/Gemfile new file mode 100644 index 0000000..56b9775 --- /dev/null +++ b/modules/concat/Gemfile @@ -0,0 +1,20 @@ +source ENV['GEM_SOURCE'] || "https://rubygems.org" + +group :development, :test do + gem 'rake', :require => false + gem 'rspec-puppet', :require => false + gem 'puppetlabs_spec_helper', :require => false + gem 'beaker', :require => false + gem 'beaker-rspec', :require => false + gem 'puppet-lint', :require => false + gem 'serverspec', :require => false + gem 'pry', :require => false +end + +if puppetversion = ENV['PUPPET_GEM_VERSION'] + gem 'puppet', puppetversion, :require => false +else + gem 'puppet', :require => false +end + +# vim:ft=ruby diff --git a/modules/concat/LICENSE b/modules/concat/LICENSE new file mode 100644 index 0000000..6a9e9a1 --- /dev/null +++ b/modules/concat/LICENSE @@ -0,0 +1,14 @@ + Copyright 2012 R.I.Pienaar + + 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/modules/concat/Modulefile b/modules/concat/Modulefile new file mode 100644 index 0000000..ea9ef2c --- /dev/null +++ b/modules/concat/Modulefile @@ -0,0 +1,9 @@ +name 'puppetlabs-concat' +version '1.1.0' +source 'git://github.com/puppetlabs/puppetlabs-concat.git' +author 'Puppetlabs' +license 'Apache 2.0' +summary 'Concat module' +description 'Concat module' +project_page 'http://github.com/puppetlabs/puppetlabs-concat' +dependency 'puppetlabs/stdlib', '>= 4.0.0' diff --git a/modules/concat/README.md b/modules/concat/README.md new file mode 100644 index 0000000..60eca38 --- /dev/null +++ b/modules/concat/README.md @@ -0,0 +1,441 @@ +#Concat + +[![Build Status](https://travis-ci.org/puppetlabs/puppetlabs-concat.png?branch=master)](https://travis-ci.org/puppetlabs/puppetlabs-concat) + +####Table of Contents + +1. [Overview](#overview) +2. [Module Description - What the module does and why it is useful](#module-description) +3. [Setup - The basics of getting started with concat](#setup) + * [What concat affects](#what-concat-affects) + * [Setup requirements](#setup-requirements) + * [Beginning with concat](#beginning-with-concat) +4. [Usage - Configuration options and additional functionality](#usage) + * [API _deprecations_](#api-deprecations) +5. [Reference - An under-the-hood peek at what the module is doing and how](#reference) +5. [Limitations - OS compatibility, etc.](#limitations) +6. [Development - Guide for contributing to the module](#development) + +##Overview + +This module constructs files from multiple fragments in an ordered way. + +##Module Description + +This module lets you use many concat::fragment{} resources throughout +your modules to construct a single file at the end. It does this through +a shell (or ruby) script and a temporary holding space for the fragments. + +##Setup + +###What concat affects + +* Installs concatfragments.[sh|rb] based on platform. +* Adds a concat/ directory into Puppets `vardir`. + +###Beginning with concat + +To start using concat you need to create: + +* A concat{} resource for the final file. +* One or more concat::fragment{}'s. + +A minimal example might be: + +```puppet +concat { '/tmp/file': + ensure => present, +} + +concat::fragment { 'tmpfile': + target => '/tmp/file' + content => 'test contents', + order => '01' +} +``` + +##Usage + +Please be aware that there have been a number of [API +_deprecations_](#api-deprecations). + +If you wanted a /etc/motd file that listed all the major modules +on the machine. And that would be maintained automatically even +if you just remove the include lines for other modules you could +use code like below, a sample /etc/motd would be: + +
+Puppet modules on this server:
+
+    -- Apache
+    -- MySQL
+
+ +Local sysadmins can also append to the file by just editing /etc/motd.local +their changes will be incorporated into the puppet managed motd. + +```puppet +class motd { + $motd = '/etc/motd' + + concat { $motd: + owner => 'root', + group => 'root', + mode => '0644' + } + + concat::fragment{ 'motd_header': + target => $motd, + content => "\nPuppet modules on this server:\n\n", + order => '01' + } + + # local users on the machine can append to motd by just creating + # /etc/motd.local + concat::fragment{ 'motd_local': + target => $motd, + source => '/etc/motd.local', + order => '15' + } +} + +# used by other modules to register themselves in the motd +define motd::register($content="", $order=10) { + if $content == "" { + $body = $name + } else { + $body = $content + } + + concat::fragment{ "motd_fragment_$name": + target => '/etc/motd', + order => $order, + content => " -- $body\n" + } +} +``` + +To use this you'd then do something like: + +```puppet +class apache { + include apache::install, apache::config, apache::service + + motd::register{ 'Apache': } +} +``` + +##Reference + +###Classes + +####Public classes + +####Private classes +* `concat::setup`: Sets up the concat script/directories. + +###Parameters + +###Defines + +####concat + +#####`ensure` +Controls if the combined file is present or absent. + +######Example +- ensure => present +- ensure => absent + +#####`path` +Controls the destination of the file to create. + +######Example +- path => '/tmp/filename' + +#####`owner` +Set the owner of the combined file. + +######Example +- owner => 'root' + +#####`group` +Set the group of the combined file. + +######Example +- group => 'root' + +#####`mode` +Set the mode of the combined file. + +######Example +- mode => '0644' + +#####`warn` +Determine if a warning message should be added at the top of the file to let +users know it was autogenerated by Puppet. + +######Example +- warn => true +- warn => false + +#####`warn_message` +Set the contents of the warning message. + +######Example +- warn_message => 'This file is autogenerated!' + +#####`force` +Determine if empty files are allowed when no fragments were added. + +######Example +- force => true +- force => false + +#####`backup` +Controls the filebucket behavior used for the file. + +######Example +- backup => 'puppet' + +#####`replace` +Controls if Puppet should replace the destination file if it already exists. + +######Example +- replace => true +- replace => false + +#####`order` +Controls the way in which the shell script chooses to sort the files. It's +rare you'll need to adjust this. + +######Allowed Values +- order => 'alpha' +- order => 'numeric' + +#####`ensure_newline` +Ensure there's a newline at the end of the fragments. + +######Example +- ensure_newline => true +- ensure_newline => false + +####concat::fragment + +#####`target` +Choose the destination file of the fragment. + +######Example +- target => '/tmp/testfile' + +#####`content` +Create the content of the fragment. + +######Example +- content => 'test file contents' + +#####`source` +Find the sources within Puppet of the fragment. + +######Example +- source => 'puppet:///modules/test/testfile' +- source => ['puppet:///modules/test/1', 'puppet:///modules/test/2'] + +#####`order` +Order the fragments. + +######Example +- order => '01' + +#####`ensure` +Control the file of fragment created. + +######Example +- ensure => 'present' +- ensure => 'absent' +- ensure => 'file' +- ensure => 'directory' + +#####`mode` +Set the mode of the fragment. + +######Example +- mode => '0644' + +#####`owner` +Set the owner of the fragment. + +######Example +- owner => 'root' + +#####`group` +Set the group of the fragment. + +######Example +- group => 'root' + +#####`backup` +Control the filebucket behavior for the fragment. + +######Example +- backup => 'puppet' + +### API _deprecations_ + +#### Since version `1.0.0` + +##### `concat{}` `warn` parameter + +```puppet +concat { '/tmp/file': + ensure => present, + warn => 'true', # generates stringified boolean value warning +} +``` + +Using stringified Boolean values as the `warn` parameter to `concat` is +deprecated, generates a catalog compile time warning, and will be silently +treated as the concatenated file header/warning message in a future release. + +The following strings are considered a stringified Boolean value: + + * `'true'` + * `'yes'` + * `'on'` + * `'false'` + * `'no'` + * `'off'` + +Please migrate to using the Puppet DSL's native [Boolean data +type](http://docs.puppetlabs.com/puppet/3/reference/lang_datatypes.html#booleans). + +##### `concat{}` `gnu` parameter + +```puppet +concat { '/tmp/file': + ensure => present, + gnu => $foo, # generates deprecation warning +} +``` + +The `gnu` parameter to `concat` is deprecated, generates a catalog compile time +warning, and has no effect. This parameter will be removed in a future +release. + +Note that this parameter was silently ignored in the `1.0.0` release. + +##### `concat::fragment{}` `ensure` parameter + +```puppet +concat::fragment { 'cpuinfo': + ensure => '/proc/cpuinfo', # generates deprecation warning + target => '/tmp/file', +} +``` + +Passing a value other than `'present'` or `'absent'` as the `ensure` parameter +to `concat::fragment` is deprecated and generates a catalog compile time +warning. The warning will become a catalog compilation failure in a future +release. + +This type emulates the Puppet core `file` type's disfavored [`ensure` +semantics](http://docs.puppetlabs.com/references/latest/type.html#file-attribute-ensure) +of treating a file path as a directive to create a symlink. This feature is +problematic in several ways. It copies an API semantic of another type that is +both frowned upon and not generally well known. It's behavior may be +surprising in that the target concatenated file will not be a symlink nor is +there any common file system that has a concept of a section of a plain file +being symbolically linked to another file. Additionally, the behavior is +generally inconsistent with most Puppet types in that a missing source file +will be silently ignored. + +If you want to use the content of a file as a fragment please use the `source` +parameter. + +##### `concat::fragment{}` `mode/owner/group` parameters + +```puppet +concat::fragment { 'foo': + target => '/tmp/file', + content => 'foo', + mode => $mode, # generates deprecation warning + owner => $owner, # generates deprecation warning + group => $group, # generates deprecation warning +} +``` + +The `mode` parameter to `concat::fragment` is deprecated, generates a catalog compile time warning, and has no effect. + +The `owner` parameter to `concat::fragment` is deprecated, generates a catalog +compile time warning, and has no effect. + +The `group` parameter to `concat::fragment` is deprecated, generates a catalog +compile time warning, and has no effect. + +These parameters had no user visible effect in version `1.0.0` and will be +removed in a future release. + +##### `concat::fragment{}` `backup` parameter + +```puppet +concat::fragment { 'foo': + target => '/tmp/file', + content => 'foo', + backup => 'bar', # generates deprecation warning +} +``` + +The `backup` parameter to `concat::fragment` is deprecated, generates a catalog +compile time warning, and has no effect. It will be removed in a future +release. + +In the `1.0.0` release this parameter controlled file bucketing of the file +fragment. Bucketting the fragment(s) is redundant with bucketting the final +concatenated file and this feature has been removed. + +##### `class { 'concat::setup': }` + +```puppet +include concat::setup # generates deprecation warning + +class { 'concat::setup: } # generates deprecation warning +``` + +The `concat::setup` class is deprecated as a public API of this module and +should no longer be directly included in the manifest. This class may be +removed in a future release. + +##### Parameter validation + +While not an API depreciation, users should be aware that all public parameters +in this module are now validated for at least variable type. This may cause +validation errors in a manifest that was previously silently misbehaving. + +##Limitations + +This module has been tested on: + +* RedHat Enterprise Linux (and Centos) 5/6 +* Debian 6/7 +* Ubuntu 12.04 + +Testing on other platforms has been light and cannot be guaranteed. + +#Development + +Puppet Labs modules on the Puppet Forge are open projects, and community +contributions are essential for keeping them great. We can’t access the +huge number of platforms and myriad of hardware, software, and deployment +configurations that Puppet is intended to serve. + +We want to keep it as easy as possible to contribute changes so that our +modules work in your environment. There are a few guidelines that we need +contributors to follow so that we can have a chance of keeping on top of things. + +You can read the complete module contribution guide [on the Puppet Labs wiki.](http://projects.puppetlabs.com/projects/module-site/wiki/Module_contributing) + +###Contributors + +The list of contributors can be found at: + +https://github.com/puppetlabs/puppetlabs-concat/graphs/contributors diff --git a/modules/concat/Rakefile b/modules/concat/Rakefile new file mode 100644 index 0000000..23aea87 --- /dev/null +++ b/modules/concat/Rakefile @@ -0,0 +1,5 @@ +require 'puppetlabs_spec_helper/rake_tasks' +require 'puppet-lint/tasks/puppet-lint' + +PuppetLint.configuration.send('disable_80chars') +PuppetLint.configuration.send('disable_quoted_booleans') diff --git a/modules/concat/files/concatfragments.rb b/modules/concat/files/concatfragments.rb new file mode 100755 index 0000000..73fd7f9 --- /dev/null +++ b/modules/concat/files/concatfragments.rb @@ -0,0 +1,137 @@ +# Script to concat files to a config file. +# +# Given a directory like this: +# /path/to/conf.d +# |-- fragments +# | |-- 00_named.conf +# | |-- 10_domain.net +# | `-- zz_footer +# +# The script supports a test option that will build the concat file to a temp location and +# use /usr/bin/cmp to verify if it should be run or not. This would result in the concat happening +# twice on each run but gives you the option to have an unless option in your execs to inhibit rebuilds. +# +# Without the test option and the unless combo your services that depend on the final file would end up +# restarting on each run, or in other manifest models some changes might get missed. +# +# OPTIONS: +# -o The file to create from the sources +# -d The directory where the fragments are kept +# -t Test to find out if a build is needed, basically concats the files to a temp +# location and compare with what's in the final location, return codes are designed +# for use with unless on an exec resource +# -w Add a shell style comment at the top of the created file to warn users that it +# is generated by puppet +# -f Enables the creation of empty output files when no fragments are found +# -n Sort the output numerically rather than the default alpha sort +# +# the command: +# +# concatfragments.rb -o /path/to/conffile.cfg -d /path/to/conf.d +# +# creates /path/to/conf.d/fragments.concat and copies the resulting +# file to /path/to/conffile.cfg. The files will be sorted alphabetically +# pass the -n switch to sort numerically. +# +# The script does error checking on the various dirs and files to make +# sure things don't fail. +require 'optparse' +require 'fileutils' + +settings = { + :outfile => "", + :workdir => "", + :test => false, + :force => false, + :warn => "", + :sortarg => "" +} + +OptionParser.new do |opts| + opts.banner = "Usage: #{$0} [options]" + opts.separator "Specific options:" + + opts.on("-o", "--outfile OUTFILE", String, "The file to create from the sources") do |o| + settings[:outfile] = o + end + + opts.on("-d", "--workdir WORKDIR", String, "The directory where the fragments are kept") do |d| + settings[:workdir] = d + end + + opts.on("-t", "--test", "Test to find out if a build is needed") do + settings[:test] = true + end + + opts.separator "Other options:" + opts.on("-w", "--warn WARNMSG", String, + "Add a shell style comment at the top of the created file to warn users that it is generated by puppet") do |w| + settings[:warn] = w + end + + opts.on("-f", "--force", "Enables the creation of empty output files when no fragments are found") do + settings[:force] = true + end + + opts.on("-n", "--sort", "Sort the output numerically rather than the default alpha sort") do + settings[:sortarg] = "-n" + end +end.parse! + +# do we have -o? +raise 'Please specify an output file with -o' unless !settings[:outfile].empty? + +# do we have -d? +raise 'Please specify fragments directory with -d' unless !settings[:workdir].empty? + +# can we write to -o? +if File.file?(settings[:outfile]) + if !File.writable?(settings[:outfile]) + raise "Cannot write to #{settings[:outfile]}" + end +else + if !File.writable?(File.dirname(settings[:outfile])) + raise "Cannot write to dirname #{File.dirname(settings[:outfile])} to create #{settings[:outfile]}" + end +end + +# do we have a fragments subdir inside the work dir? +if !File.directory?(File.join(settings[:workdir], "fragments")) && !File.executable?(File.join(settings[:workdir], "fragments")) + raise "Cannot access the fragments directory" +end + +# are there actually any fragments? +if (Dir.entries(File.join(settings[:workdir], "fragments")) - %w{ . .. }).empty? + if !settings[:force] + raise "The fragments directory is empty, cowardly refusing to make empty config files" + end +end + +Dir.chdir(settings[:workdir]) + +if settings[:warn].empty? + File.open("fragments.concat", 'w') {|f| f.write("") } +else + File.open("fragments.concat", 'w') {|f| f.write("#{settings[:warn]}\n") } +end + +# find all the files in the fragments directory, sort them numerically and concat to fragments.concat in the working dir +open('fragments.concat', 'a') do |f| + Dir.entries("fragments").sort.each{ |entry| + if File.file?(File.join("fragments", entry)) + f << File.read(File.join("fragments", entry)) + end + } +end + +if !settings[:test] + # This is a real run, copy the file to outfile + FileUtils.cp 'fragments.concat', settings[:outfile] +else + # Just compare the result to outfile to help the exec decide + if FileUtils.cmp 'fragments.concat', settings[:outfile] + exit 0 + else + exit 1 + end +end diff --git a/modules/concat/files/concatfragments.sh b/modules/concat/files/concatfragments.sh new file mode 100755 index 0000000..7e6b0f5 --- /dev/null +++ b/modules/concat/files/concatfragments.sh @@ -0,0 +1,140 @@ +#!/bin/sh + +# Script to concat files to a config file. +# +# Given a directory like this: +# /path/to/conf.d +# |-- fragments +# | |-- 00_named.conf +# | |-- 10_domain.net +# | `-- zz_footer +# +# The script supports a test option that will build the concat file to a temp location and +# use /usr/bin/cmp to verify if it should be run or not. This would result in the concat happening +# twice on each run but gives you the option to have an unless option in your execs to inhibit rebuilds. +# +# Without the test option and the unless combo your services that depend on the final file would end up +# restarting on each run, or in other manifest models some changes might get missed. +# +# OPTIONS: +# -o The file to create from the sources +# -d The directory where the fragments are kept +# -t Test to find out if a build is needed, basically concats the files to a temp +# location and compare with what's in the final location, return codes are designed +# for use with unless on an exec resource +# -w Add a shell style comment at the top of the created file to warn users that it +# is generated by puppet +# -f Enables the creation of empty output files when no fragments are found +# -n Sort the output numerically rather than the default alpha sort +# +# the command: +# +# concatfragments.sh -o /path/to/conffile.cfg -d /path/to/conf.d +# +# creates /path/to/conf.d/fragments.concat and copies the resulting +# file to /path/to/conffile.cfg. The files will be sorted alphabetically +# pass the -n switch to sort numerically. +# +# The script does error checking on the various dirs and files to make +# sure things don't fail. + +OUTFILE="" +WORKDIR="" +TEST="" +FORCE="" +WARN="" +SORTARG="" +ENSURE_NEWLINE="" + +PATH=/sbin:/usr/sbin:/bin:/usr/bin + +## Well, if there's ever a bad way to do things, Nexenta has it. +## http://nexenta.org/projects/site/wiki/Personalities +unset SUN_PERSONALITY + +while getopts "o:s:d:tnw:fl" options; do + case $options in + o ) OUTFILE=$OPTARG;; + d ) WORKDIR=$OPTARG;; + n ) SORTARG="-n";; + w ) WARNMSG="$OPTARG";; + f ) FORCE="true";; + t ) TEST="true";; + l ) ENSURE_NEWLINE="true";; + * ) echo "Specify output file with -o and fragments directory with -d" + exit 1;; + esac +done + +# do we have -o? +if [ "x${OUTFILE}" = "x" ]; then + echo "Please specify an output file with -o" + exit 1 +fi + +# do we have -d? +if [ "x${WORKDIR}" = "x" ]; then + echo "Please fragments directory with -d" + exit 1 +fi + +# can we write to -o? +if [ -f "${OUTFILE}" ]; then + if [ ! -w "${OUTFILE}" ]; then + echo "Cannot write to ${OUTFILE}" + exit 1 + fi +else + if [ ! -w `dirname "${OUTFILE}"` ]; then + echo "Cannot write to `dirname \"${OUTFILE}\"` to create ${OUTFILE}" + exit 1 + fi +fi + +# do we have a fragments subdir inside the work dir? +if [ ! -d "${WORKDIR}/fragments" ] && [ ! -x "${WORKDIR}/fragments" ]; then + echo "Cannot access the fragments directory" + exit 1 +fi + +# are there actually any fragments? +if [ ! "$(ls -A """${WORKDIR}/fragments""")" ]; then + if [ "x${FORCE}" = "x" ]; then + echo "The fragments directory is empty, cowardly refusing to make empty config files" + exit 1 + fi +fi + +cd "${WORKDIR}" + +if [ "x${WARNMSG}" = "x" ]; then + : > "fragments.concat" +else + printf '%s\n' "$WARNMSG" > "fragments.concat" +fi + +# find all the files in the fragments directory, sort them numerically and concat to fragments.concat in the working dir +IFS_BACKUP=$IFS +IFS=' +' +for fragfile in `find fragments/ -type f -follow -print0 | xargs -0 -n1 basename | LC_ALL=C sort ${SORTARG}` +do + cat "fragments/$fragfile" >> "fragments.concat" + # Handle newlines. + if [ "x${ENSURE_NEWLINE}" != "x" ]; then + echo >> "fragments.concat" + fi +done +IFS=$IFS_BACKUP + +if [ "x${TEST}" = "x" ]; then + # This is a real run, copy the file to outfile + cp fragments.concat "${OUTFILE}" + RETVAL=$? +else + # Just compare the result to outfile to help the exec decide + cmp "${OUTFILE}" fragments.concat + RETVAL=$? +fi + +exit $RETVAL diff --git a/modules/concat/lib/facter/concat_basedir.rb b/modules/concat/lib/facter/concat_basedir.rb new file mode 100644 index 0000000..bfac071 --- /dev/null +++ b/modules/concat/lib/facter/concat_basedir.rb @@ -0,0 +1,11 @@ +# == Fact: concat_basedir +# +# A custom fact that sets the default location for fragments +# +# "${::vardir}/concat/" +# +Facter.add("concat_basedir") do + setcode do + File.join(Puppet[:vardir],"concat") + end +end diff --git a/modules/concat/manifests/fragment.pp b/modules/concat/manifests/fragment.pp new file mode 100644 index 0000000..40baadd --- /dev/null +++ b/modules/concat/manifests/fragment.pp @@ -0,0 +1,121 @@ +# == Define: concat::fragment +# +# Puts a file fragment into a directory previous setup using concat +# +# === Options: +# +# [*target*] +# The file that these fragments belong to +# [*content*] +# If present puts the content into the file +# [*source*] +# If content was not specified, use the source +# [*order*] +# By default all files gets a 10_ prefix in the directory you can set it to +# anything else using this to influence the order of the content in the file +# [*ensure*] +# Present/Absent or destination to a file to include another file +# [*mode*] +# Deprecated +# [*owner*] +# Deprecated +# [*group*] +# Deprecated +# [*backup*] +# Deprecated +# +define concat::fragment( + $target, + $content = undef, + $source = undef, + $order = 10, + $ensure = undef, + $mode = undef, + $owner = undef, + $group = undef, + $backup = undef +) { + validate_string($target) + validate_string($content) + if !(is_string($source) or is_array($source)) { + fail('$source is not a string or an Array.') + } + validate_string($order) + if $mode { + warning('The $mode parameter to concat::fragment is deprecated and has no effect') + } + if $owner { + warning('The $owner parameter to concat::fragment is deprecated and has no effect') + } + if $group { + warning('The $group parameter to concat::fragment is deprecated and has no effect') + } + if $backup { + warning('The $backup parameter to concat::fragment is deprecated and has no effect') + } + if $ensure == undef { + $_ensure = getparam(Concat[$target], 'ensure') + } else { + if ! ($ensure in [ 'present', 'absent' ]) { + warning('Passing a value other than \'present\' or \'absent\' as the $ensure parameter to concat::fragment is deprecated. If you want to use the content of a file as a fragment please use the $source parameter.') + } + $_ensure = $ensure + } + + include concat::setup + + $safe_name = regsubst($name, '[/:\n]', '_', 'GM') + $safe_target_name = regsubst($target, '[/:\n]', '_', 'GM') + $concatdir = $concat::setup::concatdir + $fragdir = "${concatdir}/${safe_target_name}" + $fragowner = $concat::setup::fragment_owner + $fragmode = $concat::setup::fragment_mode + + # The file type's semantics are problematic in that ensure => present will + # not over write a pre-existing symlink. We are attempting to provide + # backwards compatiblity with previous concat::fragment versions that + # supported the file type's ensure => /target syntax + + # be paranoid and only allow the fragment's file resource's ensure param to + # be file, absent, or a file target + $safe_ensure = $_ensure ? { + '' => 'file', + undef => 'file', + 'file' => 'file', + 'present' => 'file', + 'absent' => 'absent', + default => $_ensure, + } + + # if it looks line ensure => /target syntax was used, fish that out + if ! ($_ensure in ['', 'present', 'absent', 'file' ]) { + $ensure_target = $_ensure + } else { + $ensure_target = undef + } + + # the file type's semantics only allows one of: ensure => /target, content, + # or source + if ($ensure_target and $source) or + ($ensure_target and $content) or + ($source and $content) { + fail('You cannot specify more than one of $content, $source, $ensure => /target') + } + + if ! ($content or $source or $ensure_target) { + crit('No content, source or symlink specified') + } + + # punt on group ownership until some point in the distant future when $::gid + # can be relied on to be present + file { "${fragdir}/fragments/${order}_${safe_name}": + ensure => $safe_ensure, + owner => $fragowner, + mode => $fragmode, + source => $source, + content => $content, + backup => false, + alias => "concat_fragment_${name}", + notify => Exec["concat_${target}"] + } +} diff --git a/modules/concat/manifests/init.pp b/modules/concat/manifests/init.pp new file mode 100644 index 0000000..91d82eb --- /dev/null +++ b/modules/concat/manifests/init.pp @@ -0,0 +1,232 @@ +# == Define: concat +# +# Sets up so that you can use fragments to build a final config file, +# +# === Options: +# +# [*ensure*] +# Present/Absent +# [*path*] +# The path to the final file. Use this in case you want to differentiate +# between the name of a resource and the file path. Note: Use the name you +# provided in the target of your fragments. +# [*owner*] +# Who will own the file +# [*group*] +# Who will own the file +# [*mode*] +# The mode of the final file +# [*force*] +# Enables creating empty files if no fragments are present +# [*warn*] +# Adds a normal shell style comment top of the file indicating that it is +# built by puppet +# [*force*] +# [*backup*] +# Controls the filebucketing behavior of the final file and see File type +# reference for its use. Defaults to 'puppet' +# [*replace*] +# Whether to replace a file that already exists on the local system +# [*order*] +# [*ensure_newline*] +# [*gnu*] +# Deprecated +# +# === Actions: +# * Creates fragment directories if it didn't exist already +# * Executes the concatfragments.sh script to build the final file, this +# script will create directory/fragments.concat. Execution happens only +# when: +# * The directory changes +# * fragments.concat != final destination, this means rebuilds will happen +# whenever someone changes or deletes the final file. Checking is done +# using /usr/bin/cmp. +# * The Exec gets notified by something else - like the concat::fragment +# define +# * Copies the file over to the final destination using a file resource +# +# === Aliases: +# +# * The exec can notified using Exec["concat_/path/to/file"] or +# Exec["concat_/path/to/directory"] +# * The final file can be referenced as File["/path/to/file"] or +# File["concat_/path/to/file"] +# +define concat( + $ensure = 'present', + $path = $name, + $owner = undef, + $group = undef, + $mode = '0644', + $warn = false, + $force = false, + $backup = 'puppet', + $replace = true, + $order = 'alpha', + $ensure_newline = false, + $gnu = undef +) { + validate_re($ensure, '^present$|^absent$') + validate_absolute_path($path) + validate_string($owner) + validate_string($group) + validate_string($mode) + if ! (is_string($warn) or $warn == true or $warn == false) { + fail('$warn is not a string or boolean') + } + validate_bool($force) + validate_string($backup) + validate_bool($replace) + validate_re($order, '^alpha$|^numeric$') + validate_bool($ensure_newline) + if $gnu { + warning('The $gnu parameter to concat is deprecated and has no effect') + } + + include concat::setup + + $safe_name = regsubst($name, '[/:]', '_', 'G') + $concatdir = $concat::setup::concatdir + $fragdir = "${concatdir}/${safe_name}" + $concat_name = 'fragments.concat.out' + $script_command = $concat::setup::script_command + $default_warn_message = '# This file is managed by Puppet. DO NOT EDIT.' + $bool_warn_message = 'Using stringified boolean values (\'true\', \'yes\', \'on\', \'false\', \'no\', \'off\') to represent boolean true/false as the $warn parameter to concat is deprecated and will be treated as the warning message in a future release' + + case $warn { + true: { + $warn_message = $default_warn_message + } + 'true', 'yes', 'on': { + warning($bool_warn_message) + $warn_message = $default_warn_message + } + false: { + $warn_message = '' + } + 'false', 'no', 'off': { + warning($bool_warn_message) + $warn_message = '' + } + default: { + $warn_message = $warn + } + } + + $warnmsg_escaped = regsubst($warn_message, '\'', '\'\\\'\'', 'G') + $warnflag = $warnmsg_escaped ? { + '' => '', + default => "-w '${warnmsg_escaped}'" + } + + $forceflag = $force ? { + true => '-f', + false => '', + } + + $orderflag = $order ? { + 'numeric' => '-n', + 'alpha' => '', + } + + $newlineflag = $ensure_newline ? { + true => '-l', + false => '', + } + + File { + backup => false, + } + + if $ensure == 'present' { + file { $fragdir: + ensure => directory, + mode => '0750', + } + + file { "${fragdir}/fragments": + ensure => directory, + mode => '0750', + force => true, + ignore => ['.svn', '.git', '.gitignore'], + notify => Exec["concat_${name}"], + purge => true, + recurse => true, + } + + file { "${fragdir}/fragments.concat": + ensure => present, + mode => '0640', + } + + file { "${fragdir}/${concat_name}": + ensure => present, + mode => '0640', + } + + file { $name: + ensure => present, + owner => $owner, + group => $group, + mode => $mode, + replace => $replace, + path => $path, + alias => "concat_${name}", + source => "${fragdir}/${concat_name}", + backup => $backup, + } + + # remove extra whitespace from string interpolation to make testing easier + $command = strip(regsubst("${script_command} -o \"${fragdir}/${concat_name}\" -d \"${fragdir}\" ${warnflag} ${forceflag} ${orderflag} ${newlineflag}", '\s+', ' ', 'G')) + + # if puppet is running as root, this exec should also run as root to allow + # the concatfragments.sh script to potentially be installed in path that + # may not be accessible by a target non-root owner. + exec { "concat_${name}": + alias => "concat_${fragdir}", + command => $command, + notify => File[$name], + subscribe => File[$fragdir], + unless => "${command} -t", + path => $::path, + require => [ + File[$fragdir], + File["${fragdir}/fragments"], + File["${fragdir}/fragments.concat"], + ], + } + } else { + file { [ + $fragdir, + "${fragdir}/fragments", + "${fragdir}/fragments.concat", + "${fragdir}/${concat_name}" + ]: + ensure => absent, + force => true, + } + + file { $path: + ensure => absent, + backup => $backup, + } + + $absent_exec_command = $::kernel ? { + 'windows' => 'cmd.exe /c exit 0', + default => 'true', + } + + $absent_exec_path = $::kernel ? { + 'windows' => $::path, + default => '/bin:/usr/bin', + } + + exec { "concat_${name}": + alias => "concat_${fragdir}", + command => $absent_exec_command, + path => $absent_exec_path + } + } +} + +# vim:sw=2:ts=2:expandtab:textwidth=79 diff --git a/modules/concat/manifests/setup.pp b/modules/concat/manifests/setup.pp new file mode 100644 index 0000000..1767400 --- /dev/null +++ b/modules/concat/manifests/setup.pp @@ -0,0 +1,58 @@ +# === Class: concat::setup +# +# Sets up the concat system. This is a private class. +# +# [$concatdir] +# is where the fragments live and is set on the fact concat_basedir. +# Since puppet should always manage files in $concatdir and they should +# not be deleted ever, /tmp is not an option. +# +# It also copies out the concatfragments.sh file to ${concatdir}/bin +# +class concat::setup { + if $caller_module_name != $module_name { + warning("${name} is deprecated as a public API of the ${module_name} module and should no longer be directly included in the manifest.") + } + + if $::concat_basedir { + $concatdir = $::concat_basedir + } else { + fail ('$concat_basedir not defined. Try running again with pluginsync=true on the [master] and/or [main] section of your node\'s \'/etc/puppet/puppet.conf\'.') + } + + # owner and mode of fragment files (on windows owner and access rights should be inherited from concatdir and not explicitly set to avoid problems) + $fragment_owner = $osfamily ? { 'windows' => undef, default => $::id } + $fragment_mode = $osfamily ? { 'windows' => undef, default => '0640' } + + $script_name = $::kernel ? { + 'windows' => 'concatfragments.rb', + default => 'concatfragments.sh' + } + + $script_path = "${concatdir}/bin/${script_name}" + + $script_owner = $osfamily ? { 'windows' => undef, default => $::id } + + $script_mode = $osfamily ? { 'windows' => undef, default => '0755' } + + $script_command = $::kernel ? { + 'windows' => "ruby.exe ${script_path}", + default => $script_path + } + + File { + backup => false, + } + + file { $script_path: + ensure => file, + owner => $script_owner, + mode => $script_mode, + source => "puppet:///modules/concat/${script_name}", + } + + file { [ $concatdir, "${concatdir}/bin" ]: + ensure => directory, + mode => '0755', + } +} diff --git a/modules/concat/metadata.json b/modules/concat/metadata.json new file mode 100644 index 0000000..c7305f2 --- /dev/null +++ b/modules/concat/metadata.json @@ -0,0 +1,67 @@ +{ + "name": "puppetlabs-concat", + "version": "1.1.0", + "source": "git://github.com/puppetlabs/puppetlabs-concat.git", + "author": "Puppetlabs", + "license": "Apache 2.0", + "summary": "Concat module", + "description": "Concat module", + "project_page": "http://github.com/puppetlabs/puppetlabs-concat", + "dependencies": [ + { + "name": "puppetlabs/stdlib", + "version_requirement": ">= 4.0.0" + } + ], + "types": [ + + ], + "checksums": { + "CHANGELOG": "fca146b0dcd7cc60a9082b8e301a2e18", + "Gemfile": "3cadf91e1baf9c8b7d2b1c3036676ba9", + "LICENSE": "f5a76685d453424cd63dde1535811cf0", + "Modulefile": "f8abb1236ed5211c4a3aa732431c2e19", + "README.md": "adecb8db1313997083179540b20ede86", + "Rakefile": "e415d40cd8db238f02bf4575d5e1e693", + "files/concatfragments.rb": "6784c28044a4204efb75fe4eb759816a", + "files/concatfragments.sh": "7bbe7c5fce25a5ddd20415d909ba44fc", + "lib/facter/concat_basedir.rb": "ff080677e7f192b9b96911698b0b9b3d", + "manifests/fragment.pp": "8bfd199e757f6a57f6174b558f87d2ce", + "manifests/init.pp": "79c6dc5bf0b2b0da3ce84cc2f0ae5f02", + "manifests/setup.pp": "0ff9f4d9b4c01360606ae29d8df31ff0", + "spec/acceptance/backup_spec.rb": "d4ffdf3d4f5a1b7c0aa64dd118375124", + "spec/acceptance/concat_spec.rb": "600243521241dac0b238ad01b10c7132", + "spec/acceptance/deprecation_warnings_spec.rb": "40286704d0f544437293ed8a1cc66fe9", + "spec/acceptance/empty_spec.rb": "c2edc5cef72870b0894e1b2184207325", + "spec/acceptance/fragment_source_spec.rb": "c5cda233f208b71d7d5cc89dfa4be81d", + "spec/acceptance/newline_spec.rb": "55b9f470bdff4c0245da6895c9b6e64d", + "spec/acceptance/nodesets/aix-71-vcloud.yml": "de6cc5bf18be2be8d50e62503652cb32", + "spec/acceptance/nodesets/centos-59-x64.yml": "57eb3e471b9042a8ea40978c467f8151", + "spec/acceptance/nodesets/centos-64-x64-pe.yml": "ec075d95760df3d4702abea1ce0a829b", + "spec/acceptance/nodesets/centos-64-x64.yml": "092dd2c588a9f87fa1fb12997c0723ef", + "spec/acceptance/nodesets/debian-607-x64.yml": "d566bf76f534e2af7c9a4605316d232c", + "spec/acceptance/nodesets/debian-70rc1-x64.yml": "31ccca73af7b74e1cc2fb0035c230b2c", + "spec/acceptance/nodesets/debian-73-x64.yml": "bd3ea8245ce691c2b234529d62d043eb", + "spec/acceptance/nodesets/default.yml": "3d68f9581097bb3a807ba1931c961959", + "spec/acceptance/nodesets/fedora-18-x64.yml": "80e41b1ee16ea489f53164bfdae58855", + "spec/acceptance/nodesets/rhel-7-x64.yml": "91b55d29f059e23383c7bc352b5d671d", + "spec/acceptance/nodesets/sles-11-x64.yml": "44e4c6c15c018333bfa9840a5e702f66", + "spec/acceptance/nodesets/sles-11sp1-x64.yml": "fa0046bd89c1ab4ba9521ad79db234cd", + "spec/acceptance/nodesets/ubuntu-server-10044-x64.yml": "75e86400b7889888dc0781c0ae1a1297", + "spec/acceptance/nodesets/ubuntu-server-12042-x64.yml": "d30d73e34cd50b043c7d14e305955269", + "spec/acceptance/nodesets/ubuntu-server-1404-x64.yml": "5f0aed10098ac5b78e4217bb27c7aaf0", + "spec/acceptance/order_spec.rb": "0de9b4993a3e3f6f36c52bb18f48280c", + "spec/acceptance/quoted_paths_spec.rb": "953a5a665bd4bb468e70856260c47c6e", + "spec/acceptance/replace_spec.rb": "7072d819d5997ad227fc17f4b813fe4f", + "spec/acceptance/symbolic_name_spec.rb": "10e856a87253cf8bbef95f8f9635b63e", + "spec/acceptance/warn_spec.rb": "ec03f0fa8086fc4be03da1c5aff25097", + "spec/spec_helper.rb": "0db89c9a486df193c0e40095422e19dc", + "spec/spec_helper_acceptance.rb": "5be78c42f01346abf097bbcab34ff424", + "spec/unit/classes/concat_setup_spec.rb": "6d3729833715d65f3c50c2153caed6bc", + "spec/unit/defines/concat_fragment_spec.rb": "ced7c3b1b6d7f2e65c6dc066aa8c0527", + "spec/unit/defines/concat_spec.rb": "d8da592546c9811bf40e111bf52755dc", + "spec/unit/facts/concat_basedir_spec.rb": "cf00f5a07948436fa0a84d00fc098539", + "tests/fragment.pp": "9adc3d9ba61676066072e1b949a37dbb", + "tests/init.pp": "bd3ce7d2ee146744b5dbbaae8a927043" + } +} \ No newline at end of file diff --git a/modules/concat/spec/acceptance/backup_spec.rb b/modules/concat/spec/acceptance/backup_spec.rb new file mode 100644 index 0000000..7b2858d --- /dev/null +++ b/modules/concat/spec/acceptance/backup_spec.rb @@ -0,0 +1,101 @@ +require 'spec_helper_acceptance' + +describe 'concat backup parameter' do + context '=> puppet' do + before :all do + shell('rm -rf /tmp/concat') + shell('mkdir -p /tmp/concat') + shell("/bin/echo 'old contents' > /tmp/concat/file") + end + + pp = <<-EOS + concat { '/tmp/concat/file': + backup => 'puppet', + } + concat::fragment { 'new file': + target => '/tmp/concat/file', + content => 'new contents', + } + EOS + + it 'applies the manifest twice with "Filebucketed" stdout and no stderr' do + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stderr).to eq("") + expect(r.stdout).to match(/Filebucketed \/tmp\/concat\/file to puppet with sum 0140c31db86293a1a1e080ce9b91305f/) # sum is for file contents of 'old contents' + end + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain 'new contents' } + end + end + + context '=> .backup' do + before :all do + shell('rm -rf /tmp/concat') + shell('mkdir -p /tmp/concat') + shell("/bin/echo 'old contents' > /tmp/concat/file") + end + + pp = <<-EOS + concat { '/tmp/concat/file': + backup => '.backup', + } + concat::fragment { 'new file': + target => '/tmp/concat/file', + content => 'new contents', + } + EOS + + # XXX Puppet doesn't mention anything about filebucketing with a given + # extension like .backup + it 'applies the manifest twice no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain 'new contents' } + end + describe file('/tmp/concat/file.backup') do + it { should be_file } + it { should contain 'old contents' } + end + end + + # XXX The backup parameter uses validate_string() and thus can't be the + # boolean false value, but the string 'false' has the same effect in Puppet 3 + context "=> 'false'" do + before :all do + shell('rm -rf /tmp/concat') + shell('mkdir -p /tmp/concat') + shell("/bin/echo 'old contents' > /tmp/concat/file") + end + + pp = <<-EOS + concat { '/tmp/concat/file': + backup => '.backup', + } + concat::fragment { 'new file': + target => '/tmp/concat/file', + content => 'new contents', + } + EOS + + it 'applies the manifest twice with no "Filebucketed" stdout and no stderr' do + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stderr).to eq("") + expect(r.stdout).to_not match(/Filebucketed/) + end + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain 'new contents' } + end + end +end diff --git a/modules/concat/spec/acceptance/concat_spec.rb b/modules/concat/spec/acceptance/concat_spec.rb new file mode 100644 index 0000000..89919cc --- /dev/null +++ b/modules/concat/spec/acceptance/concat_spec.rb @@ -0,0 +1,204 @@ +require 'spec_helper_acceptance' + +describe 'basic concat test' do + + shared_examples 'successfully_applied' do |pp| + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file("#{default['puppetvardir']}/concat") do + it { should be_directory } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 755 } + end + describe file("#{default['puppetvardir']}/concat/bin") do + it { should be_directory } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 755 } + end + describe file("#{default['puppetvardir']}/concat/bin/concatfragments.sh") do + it { should be_file } + it { should be_owned_by 'root' } + #it { should be_grouped_into 'root' } + it { should be_mode 755 } + end + describe file("#{default['puppetvardir']}/concat/_tmp_concat_file") do + it { should be_directory } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 750 } + end + describe file("#{default['puppetvardir']}/concat/_tmp_concat_file/fragments") do + it { should be_directory } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 750 } + end + describe file("#{default['puppetvardir']}/concat/_tmp_concat_file/fragments.concat") do + it { should be_file } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 640 } + end + describe file("#{default['puppetvardir']}/concat/_tmp_concat_file/fragments.concat.out") do + it { should be_file } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 640 } + end + end + + context 'owner/group root' do + pp = <<-EOS + concat { '/tmp/concat/file': + owner => 'root', + group => 'root', + mode => '0644', + } + + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + order => '01', + } + + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + order => '02', + } + EOS + + it_behaves_like 'successfully_applied', pp + + describe file('/tmp/concat/file') do + it { should be_file } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 644 } + it { should contain '1' } + it { should contain '2' } + end + describe file("#{default['puppetvardir']}/concat/_tmp_concat_file/fragments/01_1") do + it { should be_file } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 640 } + end + describe file("#{default['puppetvardir']}/concat/_tmp_concat_file/fragments/02_2") do + it { should be_file } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 640 } + end + end + + context 'owner/group non-root' do + before(:all) do + shell "groupadd -g 64444 bob" + shell "useradd -u 42 -g 64444 bob" + end + after(:all) do + shell "userdel bob" + end + + pp=" + concat { '/tmp/concat/file': + owner => 'bob', + group => 'bob', + mode => '0644', + } + + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + order => '01', + } + + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + order => '02', + } + " + + it_behaves_like 'successfully_applied', pp + + describe file('/tmp/concat/file') do + it { should be_file } + it { should be_owned_by 'bob' } + it { should be_grouped_into 'bob' } + it { should be_mode 644 } + it { should contain '1' } + it { should contain '2' } + end + describe file("#{default['puppetvardir']}/concat/_tmp_concat_file/fragments/01_1") do + it { should be_file } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 640 } + it { should contain '1' } + end + describe file("#{default['puppetvardir']}/concat/_tmp_concat_file/fragments/02_2") do + it { should be_file } + it { should be_owned_by 'root' } + it { should be_grouped_into 'root' } + it { should be_mode 640 } + it { should contain '2' } + end + end + + context 'ensure' do + context 'works when set to present with path set' do + pp=" + concat { 'file': + ensure => present, + path => '/tmp/concat/file', + mode => '0644', + } + concat::fragment { '1': + target => 'file', + content => '1', + order => '01', + } + " + + it_behaves_like 'successfully_applied', pp + + describe file('/tmp/concat/file') do + it { should be_file } + it { should be_mode 644 } + it { should contain '1' } + end + end + context 'works when set to absent with path set' do + pp=" + concat { 'file': + ensure => absent, + path => '/tmp/concat/file', + mode => '0644', + } + concat::fragment { '1': + target => 'file', + content => '1', + order => '01', + } + " + + # Can't used shared examples as this will always trigger the exec when + # absent is set. + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should_not be_file } + end + end + end +end diff --git a/modules/concat/spec/acceptance/deprecation_warnings_spec.rb b/modules/concat/spec/acceptance/deprecation_warnings_spec.rb new file mode 100644 index 0000000..f139d81 --- /dev/null +++ b/modules/concat/spec/acceptance/deprecation_warnings_spec.rb @@ -0,0 +1,230 @@ +require 'spec_helper_acceptance' + +describe 'deprecation warnings' do + + shared_examples 'has_warning'do |pp, w| + it 'applies the manifest twice with a stderr regex' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to match(/#{Regexp.escape(w)}/m) + expect(apply_manifest(pp, :catch_changes => true).stderr).to match(/#{Regexp.escape(w)}/m) + end + end + + context 'concat gnu parameter' do + pp = <<-EOS + concat { '/tmp/concat/file': + gnu => 'foo', + } + concat::fragment { 'foo': + target => '/tmp/concat/file', + content => 'bar', + } + EOS + w = 'The $gnu parameter to concat is deprecated and has no effect' + + it_behaves_like 'has_warning', pp, w + end + + context 'concat warn parameter =>' do + ['true', 'yes', 'on'].each do |warn| + context warn do + pp = <<-EOS + concat { '/tmp/concat/file': + warn => '#{warn}', + } + concat::fragment { 'foo': + target => '/tmp/concat/file', + content => 'bar', + } + EOS + w = 'Using stringified boolean values (\'true\', \'yes\', \'on\', \'false\', \'no\', \'off\') to represent boolean true/false as the $warn parameter to concat is deprecated and will be treated as the warning message in a future release' + + it_behaves_like 'has_warning', pp, w + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain '# This file is managed by Puppet. DO NOT EDIT.' } + it { should contain 'bar' } + end + end + end + + ['false', 'no', 'off'].each do |warn| + context warn do + pp = <<-EOS + concat { '/tmp/concat/file': + warn => '#{warn}', + } + concat::fragment { 'foo': + target => '/tmp/concat/file', + content => 'bar', + } + EOS + w = 'Using stringified boolean values (\'true\', \'yes\', \'on\', \'false\', \'no\', \'off\') to represent boolean true/false as the $warn parameter to concat is deprecated and will be treated as the warning message in a future release' + + it_behaves_like 'has_warning', pp, w + + describe file('/tmp/concat/file') do + it { should be_file } + it { should_not contain '# This file is managed by Puppet. DO NOT EDIT.' } + it { should contain 'bar' } + end + end + end + end + + context 'concat::fragment ensure parameter' do + context 'target file exists' do + before(:all) do + shell("/bin/echo 'file1 contents' > /tmp/concat/file1") + end + after(:all) do + # XXX this test may leave behind a symlink in the fragment directory + # which could cause warnings and/or breakage from the subsequent tests + # unless we clean it up. + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + shell('mkdir -p /tmp/concat') + end + + pp = <<-EOS + concat { '/tmp/concat/file': } + concat::fragment { 'foo': + target => '/tmp/concat/file', + ensure => '/tmp/concat/file1', + } + EOS + w = 'Passing a value other than \'present\' or \'absent\' as the $ensure parameter to concat::fragment is deprecated. If you want to use the content of a file as a fragment please use the $source parameter.' + + it_behaves_like 'has_warning', pp, w + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain 'file1 contents' } + end + + describe 'the fragment can be changed from a symlink to a plain file' do + pp = <<-EOS + concat { '/tmp/concat/file': } + concat::fragment { 'foo': + target => '/tmp/concat/file', + content => 'new content', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain 'new content' } + it { should_not contain 'file1 contents' } + end + end + end # target file exists + + context 'target does not exist' do + pp = <<-EOS + concat { '/tmp/concat/file': } + concat::fragment { 'foo': + target => '/tmp/concat/file', + ensure => '/tmp/concat/file1', + } + EOS + w = 'Passing a value other than \'present\' or \'absent\' as the $ensure parameter to concat::fragment is deprecated. If you want to use the content of a file as a fragment please use the $source parameter.' + + it_behaves_like 'has_warning', pp, w + + describe file('/tmp/concat/file') do + it { should be_file } + end + + describe 'the fragment can be changed from a symlink to a plain file' do + pp = <<-EOS + concat { '/tmp/concat/file': } + concat::fragment { 'foo': + target => '/tmp/concat/file', + content => 'new content', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain 'new content' } + end + end + end # target file exists + + end # concat::fragment ensure parameter + + context 'concat::fragment mode parameter' do + pp = <<-EOS + concat { '/tmp/concat/file': } + concat::fragment { 'foo': + target => '/tmp/concat/file', + content => 'bar', + mode => 'bar', + } + EOS + w = 'The $mode parameter to concat::fragment is deprecated and has no effect' + + it_behaves_like 'has_warning', pp, w + end + + context 'concat::fragment owner parameter' do + pp = <<-EOS + concat { '/tmp/concat/file': } + concat::fragment { 'foo': + target => '/tmp/concat/file', + content => 'bar', + owner => 'bar', + } + EOS + w = 'The $owner parameter to concat::fragment is deprecated and has no effect' + + it_behaves_like 'has_warning', pp, w + end + + context 'concat::fragment group parameter' do + pp = <<-EOS + concat { '/tmp/concat/file': } + concat::fragment { 'foo': + target => '/tmp/concat/file', + content => 'bar', + group => 'bar', + } + EOS + w = 'The $group parameter to concat::fragment is deprecated and has no effect' + + it_behaves_like 'has_warning', pp, w + end + + context 'concat::fragment backup parameter' do + pp = <<-EOS + concat { '/tmp/concat/file': } + concat::fragment { 'foo': + target => '/tmp/concat/file', + content => 'bar', + backup => 'bar', + } + EOS + w = 'The $backup parameter to concat::fragment is deprecated and has no effect' + + it_behaves_like 'has_warning', pp, w + end + + context 'include concat::setup' do + pp = <<-EOS + include concat::setup + EOS + w = 'concat::setup is deprecated as a public API of the concat module and should no longer be directly included in the manifest.' + + it_behaves_like 'has_warning', pp, w + end + +end diff --git a/modules/concat/spec/acceptance/empty_spec.rb b/modules/concat/spec/acceptance/empty_spec.rb new file mode 100644 index 0000000..0999528 --- /dev/null +++ b/modules/concat/spec/acceptance/empty_spec.rb @@ -0,0 +1,24 @@ +require 'spec_helper_acceptance' + +describe 'concat force empty parameter' do + context 'should run successfully' do + pp = <<-EOS + concat { '/tmp/concat/file': + owner => root, + group => root, + mode => '0644', + force => true, + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should_not contain '1\n2' } + end + end +end diff --git a/modules/concat/spec/acceptance/fragment_source_spec.rb b/modules/concat/spec/acceptance/fragment_source_spec.rb new file mode 100644 index 0000000..3afd534 --- /dev/null +++ b/modules/concat/spec/acceptance/fragment_source_spec.rb @@ -0,0 +1,134 @@ +require 'spec_helper_acceptance' + +describe 'concat::fragment source' do + context 'should read file fragments from local system' do + before(:all) do + shell("/bin/echo 'file1 contents' > /tmp/concat/file1") + shell("/bin/echo 'file2 contents' > /tmp/concat/file2") + end + + pp = <<-EOS + concat { '/tmp/concat/foo': } + + concat::fragment { '1': + target => '/tmp/concat/foo', + source => '/tmp/concat/file1', + } + concat::fragment { '2': + target => '/tmp/concat/foo', + content => 'string1 contents', + } + concat::fragment { '3': + target => '/tmp/concat/foo', + source => '/tmp/concat/file2', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/foo') do + it { should be_file } + it { should contain 'file1 contents' } + it { should contain 'string1 contents' } + it { should contain 'file2 contents' } + end + end # should read file fragments from local system + + context 'should create files containing first match only.' do + before(:all) do + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + shell('mkdir -p /tmp/concat') + shell("/bin/echo 'file1 contents' > /tmp/concat/file1") + shell("/bin/echo 'file2 contents' > /tmp/concat/file2") + end + + pp = <<-EOS + concat { '/tmp/concat/result_file1': + owner => root, + group => root, + mode => '0644', + } + concat { '/tmp/concat/result_file2': + owner => root, + group => root, + mode => '0644', + } + concat { '/tmp/concat/result_file3': + owner => root, + group => root, + mode => '0644', + } + + concat::fragment { '1': + target => '/tmp/concat/result_file1', + source => [ '/tmp/concat/file1', '/tmp/concat/file2' ], + order => '01', + } + concat::fragment { '2': + target => '/tmp/concat/result_file2', + source => [ '/tmp/concat/file2', '/tmp/concat/file1' ], + order => '01', + } + concat::fragment { '3': + target => '/tmp/concat/result_file3', + source => [ '/tmp/concat/file1', '/tmp/concat/file2' ], + order => '01', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + describe file('/tmp/concat/result_file1') do + it { should be_file } + it { should contain 'file1 contents' } + it { should_not contain 'file2 contents' } + end + describe file('/tmp/concat/result_file2') do + it { should be_file } + it { should contain 'file2 contents' } + it { should_not contain 'file1 contents' } + end + describe file('/tmp/concat/result_file3') do + it { should be_file } + it { should contain 'file1 contents' } + it { should_not contain 'file2 contents' } + end + end + + context 'should fail if no match on source.' do + before(:all) do + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + shell('mkdir -p /tmp/concat') + shell('/bin/rm -rf /tmp/concat/fail_no_source /tmp/concat/nofilehere /tmp/concat/nothereeither') + end + + pp = <<-EOS + concat { '/tmp/concat/fail_no_source': + owner => root, + group => root, + mode => '0644', + } + + concat::fragment { '1': + target => '/tmp/concat/fail_no_source', + source => [ '/tmp/concat/nofilehere', '/tmp/concat/nothereeither' ], + order => '01', + } + EOS + + it 'applies the manifest with resource failures' do + apply_manifest(pp, :expect_failures => true) + end + describe file('/tmp/concat/fail_no_source') do + #FIXME: Serverspec::Type::File doesn't support exists? for some reason. so... hack. + it { should_not be_file } + it { should_not be_directory } + end + end +end + diff --git a/modules/concat/spec/acceptance/newline_spec.rb b/modules/concat/spec/acceptance/newline_spec.rb new file mode 100644 index 0000000..1e989df --- /dev/null +++ b/modules/concat/spec/acceptance/newline_spec.rb @@ -0,0 +1,57 @@ +require 'spec_helper_acceptance' + +describe 'concat ensure_newline parameter' do + context '=> false' do + pp = <<-EOS + concat { '/tmp/concat/file': + ensure_newline => false, + } + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + } + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain '12' } + end + end + + context '=> true' do + pp = <<-EOS + concat { '/tmp/concat/file': + ensure_newline => true, + } + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + } + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + #XXX ensure_newline => true causes changes on every run because the files + #are modified in place. + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain "1\n2\n" } + end + end +end diff --git a/modules/concat/spec/acceptance/nodesets/aix-71-vcloud.yml b/modules/concat/spec/acceptance/nodesets/aix-71-vcloud.yml new file mode 100644 index 0000000..f0ae87a --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/aix-71-vcloud.yml @@ -0,0 +1,19 @@ +HOSTS: + pe-aix-71-acceptance: + roles: + - master + - dashboard + - database + - agent + - default + platform: aix-7.1-power + hypervisor: aix + ip: pe-aix-71-acceptance.delivery.puppetlabs.net +CONFIG: + type: pe + nfs_server: NONE + consoleport: 443 + datastore: instance0 + folder: Delivery/Quality Assurance/Enterprise/Dynamic + resourcepool: delivery/Quality Assurance/Enterprise/Dynamic + pooling_api: http://vcloud.delivery.puppetlabs.net/ diff --git a/modules/concat/spec/acceptance/nodesets/centos-59-x64.yml b/modules/concat/spec/acceptance/nodesets/centos-59-x64.yml new file mode 100644 index 0000000..2ad90b8 --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/centos-59-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-59-x64: + roles: + - master + platform: el-5-x86_64 + box : centos-59-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-59-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/concat/spec/acceptance/nodesets/centos-64-x64-pe.yml b/modules/concat/spec/acceptance/nodesets/centos-64-x64-pe.yml new file mode 100644 index 0000000..7d9242f --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/centos-64-x64-pe.yml @@ -0,0 +1,12 @@ +HOSTS: + centos-64-x64: + roles: + - master + - database + - dashboard + platform: el-6-x86_64 + box : centos-64-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: pe diff --git a/modules/concat/spec/acceptance/nodesets/centos-64-x64.yml b/modules/concat/spec/acceptance/nodesets/centos-64-x64.yml new file mode 100644 index 0000000..05540ed --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/centos-64-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-64-x64: + roles: + - master + platform: el-6-x86_64 + box : centos-64-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/concat/spec/acceptance/nodesets/debian-607-x64.yml b/modules/concat/spec/acceptance/nodesets/debian-607-x64.yml new file mode 100644 index 0000000..4c8be42 --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/debian-607-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + debian-607-x64: + roles: + - master + platform: debian-6-amd64 + box : debian-607-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/debian-607-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/concat/spec/acceptance/nodesets/debian-70rc1-x64.yml b/modules/concat/spec/acceptance/nodesets/debian-70rc1-x64.yml new file mode 100644 index 0000000..19181c1 --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/debian-70rc1-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + debian-70rc1-x64: + roles: + - master + platform: debian-7-amd64 + box : debian-70rc1-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/debian-70rc1-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/concat/spec/acceptance/nodesets/debian-73-x64.yml b/modules/concat/spec/acceptance/nodesets/debian-73-x64.yml new file mode 100644 index 0000000..3e6a3a9 --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/debian-73-x64.yml @@ -0,0 +1,11 @@ +HOSTS: + debian-73-x64.localhost: + roles: + - master + platform: debian-7-amd64 + box : debian-73-x64-virtualbox-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/debian-73-x64-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + log_level: debug + type: foss diff --git a/modules/concat/spec/acceptance/nodesets/default.yml b/modules/concat/spec/acceptance/nodesets/default.yml new file mode 100644 index 0000000..ae812b0 --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/default.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-64-x64.localdomain: + roles: + - master + platform: el-6-x86_64 + box : centos-65-x64-virtualbox-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-65-x64-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/concat/spec/acceptance/nodesets/fedora-18-x64.yml b/modules/concat/spec/acceptance/nodesets/fedora-18-x64.yml new file mode 100644 index 0000000..1361649 --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/fedora-18-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + fedora-18-x64: + roles: + - master + platform: fedora-18-x86_64 + box : fedora-18-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/fedora-18-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/concat/spec/acceptance/nodesets/rhel-7-x64.yml b/modules/concat/spec/acceptance/nodesets/rhel-7-x64.yml new file mode 100644 index 0000000..cf8f79a --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/rhel-7-x64.yml @@ -0,0 +1,15 @@ +HOSTS: + 'redhat-7-vcloud': + roles: + - master + platform: el-7-x86_64 + hypervisor: vcloud + template: redhat-7-x86_64 +CONFIG: + type: foss + ssh: + keys: "~/.ssh/id_rsa-acceptance" + datastore: instance0 + folder: Delivery/Quality Assurance/Enterprise/Dynamic + resourcepool: delivery/Quality Assurance/Enterprise/Dynamic + pooling_api: http://vcloud.delivery.puppetlabs.net/ diff --git a/modules/concat/spec/acceptance/nodesets/sles-11-x64.yml b/modules/concat/spec/acceptance/nodesets/sles-11-x64.yml new file mode 100644 index 0000000..41abe21 --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/sles-11-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + sles-11-x64.local: + roles: + - master + platform: sles-11-x64 + box : sles-11sp1-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/sles-11sp1-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/concat/spec/acceptance/nodesets/sles-11sp1-x64.yml b/modules/concat/spec/acceptance/nodesets/sles-11sp1-x64.yml new file mode 100644 index 0000000..554c37a --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/sles-11sp1-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + sles-11sp1-x64: + roles: + - master + platform: sles-11-x86_64 + box : sles-11sp1-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/sles-11sp1-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/concat/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml b/modules/concat/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml new file mode 100644 index 0000000..5ca1514 --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + ubuntu-server-10044-x64: + roles: + - master + platform: ubuntu-10.04-amd64 + box : ubuntu-server-10044-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-10044-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/concat/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml b/modules/concat/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml new file mode 100644 index 0000000..d065b30 --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + ubuntu-server-12042-x64: + roles: + - master + platform: ubuntu-12.04-amd64 + box : ubuntu-server-12042-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-12042-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/concat/spec/acceptance/nodesets/ubuntu-server-1404-x64.yml b/modules/concat/spec/acceptance/nodesets/ubuntu-server-1404-x64.yml new file mode 100644 index 0000000..cba1cd0 --- /dev/null +++ b/modules/concat/spec/acceptance/nodesets/ubuntu-server-1404-x64.yml @@ -0,0 +1,11 @@ +HOSTS: + ubuntu-server-1404-x64: + roles: + - master + platform: ubuntu-14.04-amd64 + box : puppetlabs/ubuntu-14.04-64-nocm + box_url : https://vagrantcloud.com/puppetlabs/ubuntu-14.04-64-nocm + hypervisor : vagrant +CONFIG: + log_level : debug + type: git diff --git a/modules/concat/spec/acceptance/order_spec.rb b/modules/concat/spec/acceptance/order_spec.rb new file mode 100644 index 0000000..8bcb713 --- /dev/null +++ b/modules/concat/spec/acceptance/order_spec.rb @@ -0,0 +1,137 @@ +require 'spec_helper_acceptance' + +describe 'concat order' do + before(:all) do + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + shell('mkdir -p /tmp/concat') + end + + context '=> alpha' do + pp = <<-EOS + concat { '/tmp/concat/foo': + order => 'alpha' + } + concat::fragment { '1': + target => '/tmp/concat/foo', + content => 'string1', + } + concat::fragment { '2': + target => '/tmp/concat/foo', + content => 'string2', + } + concat::fragment { '10': + target => '/tmp/concat/foo', + content => 'string10', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/foo') do + it { should be_file } + it { should contain "string10\nstring1\nsring2" } + end + end + + context '=> numeric' do + pp = <<-EOS + concat { '/tmp/concat/foo': + order => 'numeric' + } + concat::fragment { '1': + target => '/tmp/concat/foo', + content => 'string1', + } + concat::fragment { '2': + target => '/tmp/concat/foo', + content => 'string2', + } + concat::fragment { '10': + target => '/tmp/concat/foo', + content => 'string10', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/foo') do + it { should be_file } + it { should contain "string1\nstring2\nsring10" } + end + end +end # concat order + +describe 'concat::fragment order' do + before(:all) do + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + shell('mkdir -p /tmp/concat') + end + + context '=> reverse order' do + pp = <<-EOS + concat { '/tmp/concat/foo': } + concat::fragment { '1': + target => '/tmp/concat/foo', + content => 'string1', + order => '15', + } + concat::fragment { '2': + target => '/tmp/concat/foo', + content => 'string2', + # default order 10 + } + concat::fragment { '3': + target => '/tmp/concat/foo', + content => 'string3', + order => '1', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/foo') do + it { should be_file } + it { should contain "string3\nstring2\nsring1" } + end + end + + context '=> normal order' do + pp = <<-EOS + concat { '/tmp/concat/foo': } + concat::fragment { '1': + target => '/tmp/concat/foo', + content => 'string1', + order => '01', + } + concat::fragment { '2': + target => '/tmp/concat/foo', + content => 'string2', + order => '02' + } + concat::fragment { '3': + target => '/tmp/concat/foo', + content => 'string3', + order => '03', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/foo') do + it { should be_file } + it { should contain "string1\nstring2\nsring3" } + end + end +end # concat::fragment order diff --git a/modules/concat/spec/acceptance/quoted_paths_spec.rb b/modules/concat/spec/acceptance/quoted_paths_spec.rb new file mode 100644 index 0000000..d1a2b5f --- /dev/null +++ b/modules/concat/spec/acceptance/quoted_paths_spec.rb @@ -0,0 +1,33 @@ +require 'spec_helper_acceptance' + +describe 'quoted paths' do + before(:all) do + shell('rm -rf "/tmp/concat test" /var/lib/puppet/concat') + shell('mkdir -p "/tmp/concat test"') + end + + context 'path with blanks' do + pp = <<-EOS + concat { '/tmp/concat test/foo': + } + concat::fragment { '1': + target => '/tmp/concat test/foo', + content => 'string1', + } + concat::fragment { '2': + target => '/tmp/concat test/foo', + content => 'string2', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat test/foo') do + it { should be_file } + it { should contain "string1\nsring2" } + end + end +end diff --git a/modules/concat/spec/acceptance/replace_spec.rb b/modules/concat/spec/acceptance/replace_spec.rb new file mode 100644 index 0000000..7b31e09 --- /dev/null +++ b/modules/concat/spec/acceptance/replace_spec.rb @@ -0,0 +1,241 @@ +require 'spec_helper_acceptance' + +describe 'replacement of' do + context 'file' do + context 'should not succeed' do + before(:all) do + shell('mkdir -p /tmp/concat') + shell('echo "file exists" > /tmp/concat/file') + end + after(:all) do + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + end + + pp = <<-EOS + concat { '/tmp/concat/file': + replace => false, + } + + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + } + + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain 'file exists' } + it { should_not contain '1' } + it { should_not contain '2' } + end + end + + context 'should succeed' do + before(:all) do + shell('mkdir -p /tmp/concat') + shell('echo "file exists" > /tmp/concat/file') + end + after(:all) do + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + end + + pp = <<-EOS + concat { '/tmp/concat/file': + replace => true, + } + + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + } + + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should_not contain 'file exists' } + it { should contain '1' } + it { should contain '2' } + end + end + end # file + + context 'symlink' do + context 'should not succeed' do + # XXX the core puppet file type will replace a symlink with a plain file + # when using ensure => present and source => ... but it will not when using + # ensure => present and content => ...; this is somewhat confusing behavior + before(:all) do + shell('mkdir -p /tmp/concat') + shell('ln -s /tmp/concat/dangling /tmp/concat/file') + end + after(:all) do + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + end + + pp = <<-EOS + concat { '/tmp/concat/file': + replace => false, + } + + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + } + + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_linked_to '/tmp/concat/dangling' } + end + + describe file('/tmp/concat/dangling') do + # XXX serverspec does not have a matcher for 'exists' + it { should_not be_file } + it { should_not be_directory } + end + end + + context 'should succeed' do + # XXX the core puppet file type will replace a symlink with a plain file + # when using ensure => present and source => ... but it will not when using + # ensure => present and content => ...; this is somewhat confusing behavior + before(:all) do + shell('mkdir -p /tmp/concat') + shell('ln -s /tmp/concat/dangling /tmp/concat/file') + end + after(:all) do + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + end + + pp = <<-EOS + concat { '/tmp/concat/file': + replace => true, + } + + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + } + + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain '1' } + it { should contain '2' } + end + end + end # symlink + + context 'directory' do + context 'should not succeed' do + before(:all) do + shell('mkdir -p /tmp/concat/file') + end + after(:all) do + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + end + + pp = <<-EOS + concat { '/tmp/concat/file': } + + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + } + + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + } + EOS + + it 'applies the manifest twice with stderr for changing to file' do + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/change from directory to file failed/) + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/change from directory to file failed/) + end + + describe file('/tmp/concat/file') do + it { should be_directory } + end + end + + # XXX concat's force param currently enables the creation of empty files + # when there are no fragments, and the replace param will only replace + # files and symlinks, not directories. The semantics either need to be + # changed, extended, or a new param introduced to control directory + # replacement. + context 'should succeed', :pending => 'not yet implemented' do + before(:all) do + shell('mkdir -p /tmp/concat/file') + end + after(:all) do + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + end + + pp = <<-EOS + concat { '/tmp/concat/file': + force => true, + } + + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + } + + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain '1' } + end + end + end # directory +end diff --git a/modules/concat/spec/acceptance/symbolic_name_spec.rb b/modules/concat/spec/acceptance/symbolic_name_spec.rb new file mode 100644 index 0000000..7267f5e --- /dev/null +++ b/modules/concat/spec/acceptance/symbolic_name_spec.rb @@ -0,0 +1,32 @@ +require 'spec_helper_acceptance' + +describe 'symbolic name' do + pp = <<-EOS + concat { 'not_abs_path': + path => '/tmp/concat/file', + } + + concat::fragment { '1': + target => 'not_abs_path', + content => '1', + order => '01', + } + + concat::fragment { '2': + target => 'not_abs_path', + content => '2', + order => '02', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain '1' } + it { should contain '2' } + end +end diff --git a/modules/concat/spec/acceptance/warn_spec.rb b/modules/concat/spec/acceptance/warn_spec.rb new file mode 100644 index 0000000..cb0b743 --- /dev/null +++ b/modules/concat/spec/acceptance/warn_spec.rb @@ -0,0 +1,97 @@ +require 'spec_helper_acceptance' + +describe 'concat warn =>' do + context 'true should enable default warning message' do + pp = <<-EOS + concat { '/tmp/concat/file': + warn => true, + } + + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + order => '01', + } + + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + order => '02', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain '# This file is managed by Puppet. DO NOT EDIT.' } + it { should contain '1' } + it { should contain '2' } + end + end + context 'false should not enable default warning message' do + pp = <<-EOS + concat { '/tmp/concat/file': + warn => false, + } + + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + order => '01', + } + + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + order => '02', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should_not contain '# This file is managed by Puppet. DO NOT EDIT.' } + it { should contain '1' } + it { should contain '2' } + end + end + context '# foo should overide default warning message' do + pp = <<-EOS + concat { '/tmp/concat/file': + warn => '# foo', + } + + concat::fragment { '1': + target => '/tmp/concat/file', + content => '1', + order => '01', + } + + concat::fragment { '2': + target => '/tmp/concat/file', + content => '2', + order => '02', + } + EOS + + it 'applies the manifest twice with no stderr' do + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq("") + expect(apply_manifest(pp, :catch_changes => true).stderr).to eq("") + end + + describe file('/tmp/concat/file') do + it { should be_file } + it { should contain '# foo' } + it { should contain '1' } + it { should contain '2' } + end + end +end diff --git a/modules/concat/spec/spec_helper.rb b/modules/concat/spec/spec_helper.rb new file mode 100644 index 0000000..2c6f566 --- /dev/null +++ b/modules/concat/spec/spec_helper.rb @@ -0,0 +1 @@ +require 'puppetlabs_spec_helper/module_spec_helper' diff --git a/modules/concat/spec/spec_helper_acceptance.rb b/modules/concat/spec/spec_helper_acceptance.rb new file mode 100644 index 0000000..22bd72f --- /dev/null +++ b/modules/concat/spec/spec_helper_acceptance.rb @@ -0,0 +1,39 @@ +require 'beaker-rspec/spec_helper' +require 'beaker-rspec/helpers/serverspec' + +unless ENV['RS_PROVISION'] == 'no' or ENV['BEAKER_provision'] == 'no' + if hosts.first.is_pe? + install_pe + else + install_puppet + end + hosts.each do |host| + on hosts, "mkdir -p #{host['distmoduledir']}" + end +end + +RSpec.configure do |c| + # Project root + proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) + + # Readable test descriptions + c.formatter = :documentation + + # Configure all nodes in nodeset + c.before :suite do + # Install module and dependencies + puppet_module_install(:source => proj_root, :module_name => 'concat') + hosts.each do |host| + on host, puppet('module','install','puppetlabs-stdlib'), { :acceptable_exit_codes => [0,1] } + end + end + + c.before(:all) do + shell('mkdir -p /tmp/concat') + end + c.after(:all) do + shell('rm -rf /tmp/concat /var/lib/puppet/concat') + end + + c.treat_symbols_as_metadata_keys_with_true_values = true +end diff --git a/modules/concat/spec/unit/classes/concat_setup_spec.rb b/modules/concat/spec/unit/classes/concat_setup_spec.rb new file mode 100644 index 0000000..bba455a --- /dev/null +++ b/modules/concat/spec/unit/classes/concat_setup_spec.rb @@ -0,0 +1,42 @@ +require 'spec_helper' + +describe 'concat::setup', :type => :class do + + shared_examples 'setup' do |concatdir| + concatdir = '/foo' if concatdir.nil? + + let(:facts) {{ :concat_basedir => concatdir }} + + it do + should contain_file("#{concatdir}/bin/concatfragments.sh").with({ + :mode => '0755', + :source => 'puppet:///modules/concat/concatfragments.sh', + :backup => false, + }) + end + + [concatdir, "#{concatdir}/bin"].each do |file| + it do + should contain_file(file).with({ + :ensure => 'directory', + :mode => '0755', + :backup => false, + }) + end + end + end + + context 'facts' do + context 'concat_basedir =>' do + context '/foo' do + it_behaves_like 'setup', '/foo' + end + end + end # facts + + context 'deprecated as a public class' do + it 'should create a warning' do + pending('rspec-puppet support for testing warning()') + end + end +end diff --git a/modules/concat/spec/unit/defines/concat_fragment_spec.rb b/modules/concat/spec/unit/defines/concat_fragment_spec.rb new file mode 100644 index 0000000..3b5269e --- /dev/null +++ b/modules/concat/spec/unit/defines/concat_fragment_spec.rb @@ -0,0 +1,267 @@ +require 'spec_helper' + +describe 'concat::fragment', :type => :define do + + shared_examples 'fragment' do |title, params| + params = {} if params.nil? + + p = { + :content => nil, + :source => nil, + :order => 10, + :ensure => 'present', + }.merge(params) + + safe_name = title.gsub(/[\/\n]/, '_') + safe_target_name = p[:target].gsub(/[\/\n]/, '_') + concatdir = '/var/lib/puppet/concat' + fragdir = "#{concatdir}/#{safe_target_name}" + id = 'root' + if p[:ensure] == 'absent' + safe_ensure = p[:ensure] + else + safe_ensure = 'file' + end + + let(:title) { title } + let(:facts) {{ :concat_basedir => concatdir, :id => id }} + let(:params) { params } + let(:pre_condition) do + "concat{ '#{p[:target]}': }" + end + + it do + should contain_class('concat::setup') + should contain_concat(p[:target]) + should contain_file("#{fragdir}/fragments/#{p[:order]}_#{safe_name}").with({ + :ensure => safe_ensure, + :owner => id, + :mode => '0640', + :source => p[:source], + :content => p[:content], + :alias => "concat_fragment_#{title}", + :backup => false, + }) + end + end + + context 'title' do + ['0', '1', 'a', 'z'].each do |title| + it_behaves_like 'fragment', title, { + :target => '/etc/motd', + } + end + end # title + + context 'target =>' do + ['./etc/motd', 'etc/motd', 'motd_header'].each do |target| + context target do + it_behaves_like 'fragment', target, { + :target => '/etc/motd', + } + end + end + + context 'false' do + let(:title) { 'motd_header' } + let(:facts) {{ :concat_basedir => '/tmp' }} + let(:params) {{ :target => false }} + + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a string/) + end + end + end # target => + + context 'ensure =>' do + ['present', 'absent'].each do |ens| + context ens do + it_behaves_like 'fragment', 'motd_header', { + :ensure => ens, + :target => '/etc/motd', + } + end + end + + context 'any value other than \'present\' or \'absent\'' do + let(:title) { 'motd_header' } + let(:facts) {{ :concat_basedir => '/tmp' }} + let(:params) {{ :ensure => 'invalid', :target => '/etc/motd' }} + + it 'should create a warning' do + pending('rspec-puppet support for testing warning()') + end + end + end # ensure => + + context 'content =>' do + ['', 'ashp is our hero'].each do |content| + context content do + it_behaves_like 'fragment', 'motd_header', { + :content => content, + :target => '/etc/motd', + } + end + end + + context 'false' do + let(:title) { 'motd_header' } + let(:facts) {{ :concat_basedir => '/tmp' }} + let(:params) {{ :content => false, :target => '/etc/motd' }} + + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a string/) + end + end + end # content => + + context 'source =>' do + ['', '/foo/bar', ['/foo/bar', '/foo/baz']].each do |source| + context source do + it_behaves_like 'fragment', 'motd_header', { + :source => source, + :target => '/etc/motd', + } + end + end + + context 'false' do + let(:title) { 'motd_header' } + let(:facts) {{ :concat_basedir => '/tmp' }} + let(:params) {{ :source => false, :target => '/etc/motd' }} + + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a string or an Array/) + end + end + end # source => + + context 'order =>' do + ['', '42', 'a', 'z'].each do |order| + context '\'\'' do + it_behaves_like 'fragment', 'motd_header', { + :order => order, + :target => '/etc/motd', + } + end + end + + context 'false' do + let(:title) { 'motd_header' } + let(:facts) {{ :concat_basedir => '/tmp' }} + let(:params) {{ :order => false, :target => '/etc/motd' }} + + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a string/) + end + end + end # order => + + context 'more than one content source' do + error_msg = 'You cannot specify more than one of $content, $source, $ensure => /target' + + context 'ensure => target and source' do + let(:title) { 'motd_header' } + let(:facts) {{ :concat_basedir => '/tmp' }} + let(:params) do + { + :target => '/etc/motd', + :ensure => '/foo', + :source => '/bar', + } + end + + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /#{Regexp.escape(error_msg)}/m) + end + end + + context 'ensure => target and content' do + let(:title) { 'motd_header' } + let(:facts) {{ :concat_basedir => '/tmp' }} + let(:params) do + { + :target => '/etc/motd', + :ensure => '/foo', + :content => 'bar', + } + end + + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /#{Regexp.escape(error_msg)}/m) + end + end + + context 'source and content' do + let(:title) { 'motd_header' } + let(:facts) {{ :concat_basedir => '/tmp' }} + let(:params) do + { + :target => '/etc/motd', + :source => '/foo', + :content => 'bar', + } + end + + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /#{Regexp.escape(error_msg)}/m) + end + end + + end # more than one content source + + describe 'deprecated parameter' do + context 'mode =>' do + context '1755' do + it_behaves_like 'fragment', 'motd_header', { + :mode => '1755', + :target => '/etc/motd', + } + + it 'should create a warning' do + pending('rspec-puppet support for testing warning()') + end + end + end # mode => + + context 'owner =>' do + context 'apenny' do + it_behaves_like 'fragment', 'motd_header', { + :owner => 'apenny', + :target => '/etc/motd', + } + + it 'should create a warning' do + pending('rspec-puppet support for testing warning()') + end + end + end # owner => + + context 'group =>' do + context 'apenny' do + it_behaves_like 'fragment', 'motd_header', { + :group => 'apenny', + :target => '/etc/motd', + } + + it 'should create a warning' do + pending('rspec-puppet support for testing warning()') + end + end + end # group => + + context 'backup =>' do + context 'foo' do + it_behaves_like 'fragment', 'motd_header', { + :backup => 'foo', + :target => '/etc/motd', + } + + it 'should create a warning' do + pending('rspec-puppet support for testing warning()') + end + end + end # backup => + end # deprecated params + +end diff --git a/modules/concat/spec/unit/defines/concat_spec.rb b/modules/concat/spec/unit/defines/concat_spec.rb new file mode 100644 index 0000000..9fdd7b2 --- /dev/null +++ b/modules/concat/spec/unit/defines/concat_spec.rb @@ -0,0 +1,380 @@ +require 'spec_helper' + +describe 'concat', :type => :define do + + shared_examples 'concat' do |title, params, id| + params = {} if params.nil? + id = 'root' if id.nil? + + # default param values + p = { + :ensure => 'present', + :path => title, + :owner => nil, + :group => nil, + :mode => '0644', + :warn => false, + :force => false, + :backup => 'puppet', + :replace => true, + :order => 'alpha', + :ensure_newline => false, + }.merge(params) + + safe_name = title.gsub('/', '_') + concatdir = '/var/lib/puppet/concat' + fragdir = "#{concatdir}/#{safe_name}" + concat_name = 'fragments.concat.out' + default_warn_message = '# This file is managed by Puppet. DO NOT EDIT.' + + file_defaults = { + :backup => false, + } + + let(:title) { title } + let(:params) { params } + let(:facts) {{ :concat_basedir => concatdir, :id => id }} + + if p[:ensure] == 'present' + it do + should contain_file(fragdir).with(file_defaults.merge({ + :ensure => 'directory', + :mode => '0750', + })) + end + + it do + should contain_file("#{fragdir}/fragments").with(file_defaults.merge({ + :ensure => 'directory', + :mode => '0750', + :force => true, + :ignore => ['.svn', '.git', '.gitignore'], + :purge => true, + :recurse => true, + })) + end + + [ + "#{fragdir}/fragments.concat", + "#{fragdir}/#{concat_name}", + ].each do |file| + it do + should contain_file(file).with(file_defaults.merge({ + :ensure => 'present', + :mode => '0640', + })) + end + end + + it do + should contain_file(title).with(file_defaults.merge({ + :ensure => 'present', + :owner => p[:owner], + :group => p[:group], + :mode => p[:mode], + :replace => p[:replace], + :path => p[:path], + :alias => "concat_#{title}", + :source => "#{fragdir}/#{concat_name}", + :backup => p[:backup], + })) + end + + cmd = "#{concatdir}/bin/concatfragments.sh " + + "-o \"#{concatdir}/#{safe_name}/fragments.concat.out\" " + + "-d \"#{concatdir}/#{safe_name}\"" + + # flag order: fragdir, warnflag, forceflag, orderflag, newlineflag + if p.has_key?(:warn) + case p[:warn] + when TrueClass + message = default_warn_message + when 'true', 'yes', 'on' + # should generate a stringified boolean warning + message = default_warn_message + when FalseClass + message = nil + when 'false', 'no', 'off' + # should generate a stringified boolean warning + message = nil + else + message = p[:warn] + end + + unless message.nil? + cmd += " -w \'#{message}\'" + end + end + + cmd += " -f" if p[:force] + cmd += " -n" if p[:order] == 'numeric' + cmd += " -l" if p[:ensure_newline] == true + + it do + should contain_exec("concat_#{title}").with({ + :alias => "concat_#{fragdir}", + :command => cmd, + :unless => "#{cmd} -t", + }) + end + else + [ + fragdir, + "#{fragdir}/fragments", + "#{fragdir}/fragments.concat", + "#{fragdir}/#{concat_name}", + ].each do |file| + it do + should contain_file(file).with(file_defaults.merge({ + :ensure => 'absent', + :backup => false, + :force => true, + })) + end + end + + it do + should contain_file(title).with(file_defaults.merge({ + :ensure => 'absent', + :backup => p[:backup], + })) + end + + it do + should contain_exec("concat_#{title}").with({ + :alias => "concat_#{fragdir}", + :command => 'true', + :path => '/bin:/usr/bin', + }) + end + end + end + + context 'title' do + context 'without path param' do + # title/name is the default value for the path param. therefore, the + # title must be an absolute path unless path is specified + ['/foo', '/foo/bar', '/foo/bar/baz'].each do |title| + context title do + it_behaves_like 'concat', '/etc/foo.bar' + end + end + + ['./foo', 'foo', 'foo/bar'].each do |title| + context title do + let(:title) { title } + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not an absolute path/) + end + end + end + end + + context 'with path param' do + ['./foo', 'foo', 'foo/bar'].each do |title| + context title do + it_behaves_like 'concat', title, { :path => '/etc/foo.bar' } + end + end + end + end # title => + + context 'as non-root user' do + it_behaves_like 'concat', '/etc/foo.bar', {}, 'bob' + end + + context 'ensure =>' do + ['present', 'absent'].each do |ens| + context ens do + it_behaves_like 'concat', '/etc/foo.bar', { :ensure => ens } + end + end + + context 'invalid' do + let(:title) { '/etc/foo.bar' } + let(:params) {{ :ensure => 'invalid' }} + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /#{Regexp.escape('does not match "^present$|^absent$"')}/) + end + end + end # ensure => + + context 'path =>' do + context '/foo' do + it_behaves_like 'concat', '/etc/foo.bar', { :path => '/foo' } + end + + ['./foo', 'foo', 'foo/bar', false].each do |path| + context path do + let(:title) { '/etc/foo.bar' } + let(:params) {{ :path => path }} + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not an absolute path/) + end + end + end + end # path => + + context 'owner =>' do + context 'apenney' do + it_behaves_like 'concat', '/etc/foo.bar', { :owner => 'apenny' } + end + + context 'false' do + let(:title) { '/etc/foo.bar' } + let(:params) {{ :owner => false }} + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a string/) + end + end + end # owner => + + context 'group =>' do + context 'apenney' do + it_behaves_like 'concat', '/etc/foo.bar', { :group => 'apenny' } + end + + context 'false' do + let(:title) { '/etc/foo.bar' } + let(:params) {{ :group => false }} + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a string/) + end + end + end # group => + + context 'mode =>' do + context '1755' do + it_behaves_like 'concat', '/etc/foo.bar', { :mode => '1755' } + end + + context 'false' do + let(:title) { '/etc/foo.bar' } + let(:params) {{ :mode => false }} + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a string/) + end + end + end # mode => + + context 'warn =>' do + [true, false, '# foo'].each do |warn| + context warn do + it_behaves_like 'concat', '/etc/foo.bar', { :warn => warn } + end + end + + context '(stringified boolean)' do + ['true', 'yes', 'on', 'false', 'no', 'off'].each do |warn| + context warn do + it_behaves_like 'concat', '/etc/foo.bar', { :warn => warn } + + it 'should create a warning' do + pending('rspec-puppet support for testing warning()') + end + end + end + end + + context '123' do + let(:title) { '/etc/foo.bar' } + let(:params) {{ :warn => 123 }} + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a string or boolean/) + end + end + end # warn => + + context 'force =>' do + [true, false].each do |force| + context force do + it_behaves_like 'concat', '/etc/foo.bar', { :force => force } + end + end + + context '123' do + let(:title) { '/etc/foo.bar' } + let(:params) {{ :force => 123 }} + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a boolean/) + end + end + end # force => + + context 'backup =>' do + context 'reverse' do + it_behaves_like 'concat', '/etc/foo.bar', { :backup => 'reverse' } + end + + context 'false' do + let(:title) { '/etc/foo.bar' } + let(:params) {{ :backup => false }} + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a string/) + end + end + end # backup => + + context 'replace =>' do + [true, false].each do |replace| + context replace do + it_behaves_like 'concat', '/etc/foo.bar', { :replace => replace } + end + end + + context '123' do + let(:title) { '/etc/foo.bar' } + let(:params) {{ :replace => 123 }} + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a boolean/) + end + end + end # replace => + + context 'order =>' do + ['alpha', 'numeric'].each do |order| + context order do + it_behaves_like 'concat', '/etc/foo.bar', { :order => order } + end + end + + context 'invalid' do + let(:title) { '/etc/foo.bar' } + let(:params) {{ :order => 'invalid' }} + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /#{Regexp.escape('does not match "^alpha$|^numeric$"')}/) + end + end + end # order => + + context 'ensure_newline =>' do + [true, false].each do |ensure_newline| + context 'true' do + it_behaves_like 'concat', '/etc/foo.bar', { :ensure_newline => ensure_newline} + end + end + + context '123' do + let(:title) { '/etc/foo.bar' } + let(:params) {{ :ensure_newline => 123 }} + it 'should fail' do + expect { should }.to raise_error(Puppet::Error, /is not a boolean/) + end + end + end # ensure_newline => + + describe 'deprecated parameter' do + context 'gnu =>' do + context 'foo' do + it_behaves_like 'concat', '/etc/foo.bar', { :gnu => 'foo'} + + it 'should create a warning' do + pending('rspec-puppet support for testing warning()') + end + end + end + end + +end + +# vim:sw=2:ts=2:expandtab:textwidth=79 diff --git a/modules/concat/spec/unit/facts/concat_basedir_spec.rb b/modules/concat/spec/unit/facts/concat_basedir_spec.rb new file mode 100644 index 0000000..41bc90f --- /dev/null +++ b/modules/concat/spec/unit/facts/concat_basedir_spec.rb @@ -0,0 +1,18 @@ +require 'spec_helper' + +describe 'concat_basedir', :type => :fact do + before(:each) { Facter.clear } + + context 'Puppet[:vardir] ==' do + it '/var/lib/puppet' do + Puppet.stubs(:[]).with(:vardir).returns('/var/lib/puppet') + Facter.fact(:concat_basedir).value.should == '/var/lib/puppet/concat' + end + + it '/home/apenny/.puppet/var' do + Puppet.stubs(:[]).with(:vardir).returns('/home/apenny/.puppet/var') + Facter.fact(:concat_basedir).value.should == '/home/apenny/.puppet/var/concat' + end + end + +end diff --git a/modules/concat/tests/fragment.pp b/modules/concat/tests/fragment.pp new file mode 100644 index 0000000..a2dfaca --- /dev/null +++ b/modules/concat/tests/fragment.pp @@ -0,0 +1,19 @@ +concat { 'testconcat': + ensure => present, + path => '/tmp/concat', + owner => 'root', + group => 'root', + mode => '0664', +} + +concat::fragment { '1': + target => 'testconcat', + content => '1', + order => '01', +} + +concat::fragment { '2': + target => 'testconcat', + content => '2', + order => '02', +} diff --git a/modules/concat/tests/init.pp b/modules/concat/tests/init.pp new file mode 100644 index 0000000..fd21427 --- /dev/null +++ b/modules/concat/tests/init.pp @@ -0,0 +1,7 @@ +concat { '/tmp/concat': + ensure => present, + force => true, + owner => 'root', + group => 'root', + mode => '0644', +} diff --git a/modules/kannel/.project b/modules/kannel/.project new file mode 100644 index 0000000..52b8311 --- /dev/null +++ b/modules/kannel/.project @@ -0,0 +1,23 @@ + + + kannel + + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + com.puppetlabs.geppetto.pp.dsl.ui.modulefileBuilder + + + + + + com.puppetlabs.geppetto.pp.dsl.ui.puppetNature + org.eclipse.xtext.ui.shared.xtextNature + + diff --git a/modules/kannel/README.markdown b/modules/kannel/README.markdown new file mode 100644 index 0000000..bd506d1 --- /dev/null +++ b/modules/kannel/README.markdown @@ -0,0 +1,3 @@ +# kannel # + +This is the kannel module. It provides... diff --git a/modules/kannel/Rakefile b/modules/kannel/Rakefile new file mode 100644 index 0000000..14f1c24 --- /dev/null +++ b/modules/kannel/Rakefile @@ -0,0 +1,2 @@ +require 'rubygems' +require 'puppetlabs_spec_helper/rake_tasks' diff --git a/modules/kannel/files/kannel-default b/modules/kannel/files/kannel-default new file mode 100644 index 0000000..adb0f48 --- /dev/null +++ b/modules/kannel/files/kannel-default @@ -0,0 +1,2 @@ +#START_WAPBOX=1 +START_SMSBOX=1 diff --git a/modules/kannel/manifests/init.pp b/modules/kannel/manifests/init.pp new file mode 100644 index 0000000..e3b3e1d --- /dev/null +++ b/modules/kannel/manifests/init.pp @@ -0,0 +1,39 @@ +# Class: kannel +# +# This module manages kannel +# +# Parameters: none +# +# Actions: +# +# Requires: see Modulefile +# +# Sample Usage: +# +class kannel ( + $kannel_bind_address = hiera('rhizo::vpn_address') +) { + + package { 'kannel': + ensure => present, + } + + file { '/etc/kannel/kannel.conf': + ensure => present, + content => template("kannel/kannel.conf.erb"), + require => Package['kannel'], + notify => Service['kannel'], + } + + file { '/etc/default/kannel': + ensure => present, + source => ['puppet:///modules/kannel/kannel-default'], + notify => Service['kannel'], + } + + service { 'kannel': + ensure => running, + enable => true, + require => Package['kannel'], + } +} diff --git a/modules/kannel/metadata.json b/modules/kannel/metadata.json new file mode 100644 index 0000000..487a78f --- /dev/null +++ b/modules/kannel/metadata.json @@ -0,0 +1,13 @@ +{ + "name": "ciaby-kannel", + "version": "0.1.0", + "summary": "", + "author": "", + "description": "", + "dependencies": [], + "types": [], + "checksums": {}, + "source": "", + "project_page": "", + "license": "" +} \ No newline at end of file diff --git a/modules/kannel/spec/spec.opts b/modules/kannel/spec/spec.opts new file mode 100644 index 0000000..91cd642 --- /dev/null +++ b/modules/kannel/spec/spec.opts @@ -0,0 +1,6 @@ +--format +s +--colour +--loadby +mtime +--backtrace diff --git a/modules/kannel/spec/spec_helper.rb b/modules/kannel/spec/spec_helper.rb new file mode 100644 index 0000000..dc7e9f4 --- /dev/null +++ b/modules/kannel/spec/spec_helper.rb @@ -0,0 +1,2 @@ +require 'rubygems' +require 'puppetlabs_spec_helper/module_spec_helper' diff --git a/modules/kannel/templates/kannel.conf.erb b/modules/kannel/templates/kannel.conf.erb new file mode 100644 index 0000000..044c2a9 --- /dev/null +++ b/modules/kannel/templates/kannel.conf.erb @@ -0,0 +1,85 @@ +group = core +admin-port = 14000 +admin-password = <%= @kannel_admin_password %> +log-file = "/var/log/kannel/bearerbox.log" +log-level = 0 +access-log = "/var/log/kannel/bearerbox_access.log" +# Smsbox related +smsbox-port = 14001 +#box-deny-ip = "*.*.*.*" +#box-allow-ip = "127.0.0.1" +#sms-resend-retry = 2 + +# SMSC SMPP +group = smsc +smsc = smpp +smsc-id = KSMPP +host = 127.0.0.1 +port = 2775 +#receive-port = 2775 +interface-version=34 +alt-charset = ISO-8859-1 +enquire-link-interval = 298 +connect-allow-ip = 127.0.0.1 +transceiver-mode = 0 +smsc-username = OSMPP +smsc-password = <%= @smsc_password %> +system-type = kannel +#source-addr-ton = 2 +#source-addr-npi = 1 +#dest-addr-ton = 1 +#dest-addr-npi = 1 + +# SMSC SMPP +group = smsc +smsc = smpp +smsc-id = KSMPP +host = 127.0.0.1 +port = 0 +receive-port = 2775 +interface-version=34 +#alt-charset = ISO-8859-1 +enquire-link-interval = 298 +connect-allow-ip = 127.0.0.1 +transceiver-mode = false +smsc-username = OSMPP +smsc-password = <%= @smsc_password %> +system-type = kannel +#source-addr-ton = 2 +#source-addr-npi = 1 +#dest-addr-ton = 1 +#dest-addr-npi = 1 + + +group = smsbox-route +smsbox-id = mysm +smsc-id = KSMPP + +# receive SMS +group = sms-service +#keyword = +keyword-regex = .* +catch-all = yes +max-messages = 0 +post-url = "http://localhost:8085/sms?source=%p&destination=%P&charset=%C&coding=%c&text=%a" + +# send to web cgi +group = sendsms-user +default-smsc = KSMPP +username = rhizomatica +password = <%= @kannel_sendsms_password %> +concatenation = true +max-messages = 3 + +# SMSBOX SETUP +group = smsbox +#smsbox-port = 14001 +sendsms-port = 14002 +smsbox-id = mysm +#mo-recode=true +#immediate-sendsms-reply = true +bearerbox-host = 127.0.0.1 +bearerbox-port = 14001 +log-file = "/var/log/kannel/smsbox.log" +log-level = 0 +access-log = "/var/log/kannel/smsbox_access.log" diff --git a/modules/kannel/tests/init.pp b/modules/kannel/tests/init.pp new file mode 100644 index 0000000..38779a4 --- /dev/null +++ b/modules/kannel/tests/init.pp @@ -0,0 +1 @@ +include kannel diff --git a/modules/ntp/CHANGELOG.md b/modules/ntp/CHANGELOG.md new file mode 100644 index 0000000..08d9a87 --- /dev/null +++ b/modules/ntp/CHANGELOG.md @@ -0,0 +1,177 @@ +##2014-06-06 - Release 3.1.1 +###Summary + +This is a bugfix release to get around dependency issues in PMT 3.6. This +version has a dependency on puppetlabs-stdlib >= 4 so PE3.2.x is no longer +supported. + +####Bugfixes +- Remove deprecated Modulefile as it was causing duplicate dependencies with PMT. + +##2014-05-14 - Release 3.1.0 +###Summary + +This release adds `disable_monitor` so you can disable the monitor functionality +of NTP, which was recently used in NTP amplification attacks. It also adds +support for RHEL7 and Ubuntu 14.04. + +####Features +- Add `disable_monitor` + +####Bugfixes + +#####Known Bugs +* No known bugs + +##2014-04-09 - Supported Release 3.0.4 +###Summary +This is a supported release. + +The only functional change in this release is to split up the restrict +defaults to be per operating system so that we can provide safer defaults +for AIX, to resolve cases where IPv6 are disabled. + +####Features +- Rework restrict defaults. + +####Bugfixes +- Fix up a comment. +- Fix a test to work better on PE. + +#####Known Bugs +* No known bugs + +##2014-03-04 - Supported Release 3.0.3 +###Summary +This is a supported release. Correct stdlib compatibility + +####Bugfixes +- Remove `dirname()` call for correct stdlib compatibility. +- Improved tests + +####Known Bugs +* No known bugs + + +## 2014-02-13 - Release 3.0.2 +###Summary + +No functional changes: Update the README and allow custom gem sources. + +## 2013-12-17 - Release 3.0.1 +### Summary + +Work around a packaging bug with symlinks, no other functional changes. + +## 2013-12-13 - Release 3.0.0 +### Summary + +Final release of 3.0, enjoy! + + +## 2013-10-14 - Version 3.0.0-rc1 + +###Summary + +This release changes the behavior of restrict and adds AIX osfamily support. + +####Backwards-incompatible Changes: + +`restrict` no longer requires you to pass in parameters as: + +restrict => [ 'restrict x', 'restrict y' ] + +but just as: + +restrict => [ 'x', 'y' ] + +As the template now prefixes each line with restrict. + +####Features +- Change the behavior of `restrict` so you no longer need the restrict +keyword. +- Add `udlc` parameter to enable undisciplined local clock regardless of the +machines status as a virtual machine. +- Add AIX support. + +####Fixes +- Use class{} instead of including and then anchoring. (style) +- Extend Gentoo coverage to Facter 1.7. + +--- +##2013-09-05 - Version 2.0.1 + +###Summary + +Correct the LICENSE file. + +####Bugfixes +- Add in the appropriate year and name in LICENSE. + + +##2013-07-31 - Version 2.0.0 + +###Summary + +The 2.0 release focuses on merging all the distro specific +templates into a single reusable template across all platforms. + +To aid in that goal we now allow you to change the driftfile, +ntp keys, and perferred_servers. + +####Backwards-incompatible changes + +As all the distro specific templates have been removed and a +unified one created you may be missing functionality you +previously relied on. Please test carefully before rolling +out globally. + +Configuration directives that might possibly be affected: +- `filegen` +- `fudge` (for virtual machines) +- `keys` +- `logfile` +- `restrict` +- `restrictkey` +- `statistics` +- `trustedkey` + +####Features: +- All templates merged into a single template. +- NTP Keys support added. +- Add preferred servers support. +- Parameters in `ntp` class: + - `driftfile`: path for the ntp driftfile. + - `keys_enable`: Enable NTP keys feature. + - `keys_file`: Path for the NTP keys file. + - `keys_trusted`: Which keys to trust. + - `keys_controlkey`: Which key to use for the control key. + - `keys_requestkey`: Which key to use for the request key. + - `preferred_servers`: Array of servers to prefer. + - `restrict`: Array of restriction options to apply. + +--- +###2013-07-15 - Version 1.0.1 +####Bugfixes +- Fix deprecated warning in `autoupdate` parameter. +- Correctly quote is_virtual fact. + + +##2013-07-08 - Version 1.0.0 +####Features +- Completely refactored to split across several classes. +- rspec-puppet tests rewritten to cover more options. +- rspec-system tests added. +- ArchLinux handled via osfamily instead of special casing. +- parameters in `ntp` class: + - `autoupdate`: deprecated in favor of directly setting package_ensure. + - `panic`: set to false if you wish to allow large clock skews. + +--- +##2011-11-10 Dan Bode - 0.0.4 +* Add Amazon Linux as a supported platform +* Add unit tests + + +##2011-06-16 Jeff McCune - 0.0.3 +* Initial release under puppetlabs diff --git a/modules/ntp/CONTRIBUTING.md b/modules/ntp/CONTRIBUTING.md new file mode 100644 index 0000000..a2b1d77 --- /dev/null +++ b/modules/ntp/CONTRIBUTING.md @@ -0,0 +1,9 @@ +Puppet Labs modules on the Puppet Forge are open projects, and community contributions +are essential for keeping them great. We can’t access the huge number of platforms and +myriad of hardware, software, and deployment configurations that Puppet is intended to serve. + +We want to keep it as easy as possible to contribute changes so that our modules work +in your environment. There are a few guidelines that we need contributors to follow so +that we can have a chance of keeping on top of things. + +You can read the complete module contribution guide [on the Puppet Labs wiki.](http://projects.puppetlabs.com/projects/module-site/wiki/Module_contributing) diff --git a/modules/ntp/Gemfile b/modules/ntp/Gemfile new file mode 100644 index 0000000..7f86b2d --- /dev/null +++ b/modules/ntp/Gemfile @@ -0,0 +1,19 @@ +source ENV['GEM_SOURCE'] || "https://rubygems.org" + +group :development, :test do + gem 'rake', :require => false + gem 'puppetlabs_spec_helper', :require => false + gem 'puppet-lint', :require => false + gem 'serverspec', :require => false + gem 'beaker', :require => false + gem 'beaker-rspec', :require => false + gem 'specinfra', '>=0.7.0' +end + +if puppetversion = ENV['PUPPET_GEM_VERSION'] + gem 'puppet', puppetversion, :require => false +else + gem 'puppet', :require => false +end + +# vim:ft=ruby diff --git a/modules/ntp/Gemfile.lock b/modules/ntp/Gemfile.lock new file mode 100644 index 0000000..9f52452 --- /dev/null +++ b/modules/ntp/Gemfile.lock @@ -0,0 +1,144 @@ +GEM + remote: https://rubygems.org/ + specs: + CFPropertyList (2.2.7) + addressable (2.3.6) + autoparse (0.3.3) + addressable (>= 2.3.1) + extlib (>= 0.9.15) + multi_json (>= 1.0.0) + aws-sdk (1.39.0) + json (~> 1.4) + nokogiri (>= 1.4.4) + beaker (1.10.0) + aws-sdk (~> 1.38) + blimpy (~> 0.6) + fission (~> 0.4) + google-api-client (~> 0.6.4) + inifile (~> 2.0) + json (~> 1.8) + mime-types (~> 1.25) + net-scp (~> 1.1) + net-ssh (~> 2.6) + nokogiri (= 1.5.10) + rbvmomi (= 1.8.1) + unf (~> 0.1) + beaker-rspec (2.2.3) + beaker (~> 1.10.0) + rspec (~> 2.14) + serverspec (~> 1.0.0) + specinfra (~> 1.0.0) + blimpy (0.6.7) + fog + minitar + thor + builder (3.2.2) + diff-lcs (1.2.5) + excon (0.31.0) + extlib (0.9.16) + facter (2.0.1) + CFPropertyList (~> 2.2.6) + faraday (0.8.9) + multipart-post (~> 1.2.0) + fission (0.5.0) + CFPropertyList (~> 2.2) + fog (1.19.0) + builder + excon (~> 0.31.0) + formatador (~> 0.2.0) + mime-types + multi_json (~> 1.0) + net-scp (~> 1.1) + net-ssh (>= 2.1.3) + nokogiri (~> 1.5) + ruby-hmac + formatador (0.2.4) + google-api-client (0.6.4) + addressable (>= 2.3.2) + autoparse (>= 0.3.3) + extlib (>= 0.9.15) + faraday (~> 0.8.4) + jwt (>= 0.1.5) + launchy (>= 2.1.1) + multi_json (>= 1.0.0) + signet (~> 0.4.5) + uuidtools (>= 2.1.0) + hiera (1.3.2) + json_pure + highline (1.6.21) + inifile (2.0.2) + json (1.8.1) + json_pure (1.8.1) + jwt (0.1.11) + multi_json (>= 1.5) + launchy (2.4.2) + addressable (~> 2.3) + metaclass (0.0.4) + mime-types (1.25.1) + minitar (0.5.4) + mocha (1.0.0) + metaclass (~> 0.0.1) + multi_json (1.9.3) + multipart-post (1.2.0) + net-scp (1.2.1) + net-ssh (>= 2.6.5) + net-ssh (2.9.0) + nokogiri (1.5.10) + puppet (3.5.1) + facter (> 1.6, < 3) + hiera (~> 1.0) + json_pure + rgen (~> 0.6.5) + puppet-lint (0.3.2) + puppetlabs_spec_helper (0.4.1) + mocha (>= 0.10.5) + rake + rspec (>= 2.9.0) + rspec-puppet (>= 0.1.1) + rake (10.3.1) + rbvmomi (1.8.1) + builder + nokogiri (>= 1.4.1) + trollop + rgen (0.6.6) + rspec (2.14.1) + rspec-core (~> 2.14.0) + rspec-expectations (~> 2.14.0) + rspec-mocks (~> 2.14.0) + rspec-core (2.14.8) + rspec-expectations (2.14.5) + diff-lcs (>= 1.1.3, < 2.0) + rspec-mocks (2.14.6) + rspec-puppet (1.0.1) + rspec + ruby-hmac (0.4.0) + serverspec (1.0.0) + highline + net-ssh + rspec (~> 2.13) + specinfra (>= 1.0.0) + signet (0.4.5) + addressable (>= 2.2.3) + faraday (~> 0.8.1) + jwt (>= 0.1.5) + multi_json (>= 1.0.0) + specinfra (1.0.5) + thor (0.19.1) + trollop (2.0) + unf (0.1.4) + unf_ext + unf_ext (0.0.6) + uuidtools (2.1.4) + +PLATFORMS + ruby + +DEPENDENCIES + beaker + beaker-rspec + puppet + puppet-lint + puppetlabs_spec_helper + rake + serverspec + specinfra (>= 0.7.0) diff --git a/modules/ntp/LICENSE b/modules/ntp/LICENSE new file mode 100644 index 0000000..bc1c718 --- /dev/null +++ b/modules/ntp/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2013] [Puppet Labs] + + 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/modules/ntp/README.markdown b/modules/ntp/README.markdown new file mode 100644 index 0000000..7d96b14 --- /dev/null +++ b/modules/ntp/README.markdown @@ -0,0 +1,231 @@ +#ntp + +####Table of Contents + +1. [Overview](#overview) +2. [Module Description - What the module does and why it is useful](#module-description) +3. [Setup - The basics of getting started with ntp](#setup) + * [What ntp affects](#what-ntp-affects) + * [Setup requirements](#setup-requirements) + * [Beginning with ntp](#beginning-with-ntp) +4. [Usage - Configuration options and additional functionality](#usage) +5. [Reference - An under-the-hood peek at what the module is doing and how](#reference) +5. [Limitations - OS compatibility, etc.](#limitations) +6. [Development - Guide for contributing to the module](#development) + +##Overview + +The ntp module installs, configures, and manages the NTP service. + +##Module Description + +The ntp module handles installing, configuring, and running NTP across a range of operating systems and distributions. + +##Setup + +###What ntp affects + +* ntp package. +* ntp configuration file. +* ntp service. + +###Beginning with ntp + +`include '::ntp'` is enough to get you up and running. If you wish to pass in +parameters specifying which servers to use, then: + +```puppet +class { '::ntp': + servers => [ 'ntp1.corp.com', 'ntp2.corp.com' ], +} +``` + +##Usage + +All interaction with the ntp module can do be done through the main ntp class. +This means you can simply toggle the options in `::ntp` to have full functionality of the module. + +###I just want NTP, what's the minimum I need? + +```puppet +include '::ntp' +``` + +###I just want to tweak the servers, nothing else. + +```puppet +class { '::ntp': + servers => [ 'ntp1.corp.com', 'ntp2.corp.com' ], +} +``` + +###I'd like to make sure I restrict who can connect as well. + +```puppet +class { '::ntp': + servers => [ 'ntp1.corp.com', 'ntp2.corp.com' ], + restrict => ['127.0.0.1'], +} +``` + +###I'd like to opt out of having the service controlled; we use another tool for that. + +```puppet +class { '::ntp': + servers => [ 'ntp1.corp.com', 'ntp2.corp.com' ], + restrict => ['127.0.0.1'], + service_manage => false, +} +``` + +###Looks great! But I'd like a different template; we need to do something unique here. + +```puppet +class { '::ntp': + servers => [ 'ntp1.corp.com', 'ntp2.corp.com' ], + restrict => ['127.0.0.1'], + service_manage => false, + config_template => 'different/module/custom.template.erb', +} +``` + +##Reference + +###Classes + +####Public Classes + +* ntp: Main class, includes all other classes. + +####Private Classes + +* ntp::install: Handles the packages. +* ntp::config: Handles the configuration file. +* ntp::service: Handles the service. + +###Parameters + +The following parameters are available in the ntp module: + +####`autoupdate` + +**Deprecated:** This parameter determined whether the ntp module should be +automatically updated to the latest version available. Replaced by `package_ensure`. + +####`config` + +Sets the file that ntp configuration is written into. + +####`config_template` + +Determines which template Puppet should use for the ntp configuration. + +####`disable_monitor` + +Disables monitoring of ntp. + +####`driftfile` + +Sets the location of the drift file for ntp. + +####`keys_controlkey` + +The key to use as the control key. + +####`keys_enable` + +Whether the ntp keys functionality is enabled. + +####`keys_file` + +Location of the keys file. + +####`keys_requestkey` + +Which of the keys is the request key. + +#### `keys_trusted` + +Array of trusted keys. + +####`package_ensure` + +Sets the ntp package to be installed. Can be set to 'present', 'latest', or a specific version. + +####`package_name` + +Determines the name of the package to install. + +####`panic` + +Determines if ntp should 'panic' in the event of a very large clock skew. +This defaults to false for virtual machines, as they don't do a great job with keeping time. + +####`preferred_servers` + +List of ntp servers to prefer. Will append 'prefer' for any server in this list +that also appears in the servers list. + +####`restrict` + +Sets the restrict options in the ntp configuration. The lines are +prefixed with 'restrict', so you just need to list the rest of the restriction. + +####`servers` + +Selects the servers to use for ntp peers. + +####`service_enable` + +Determines if the service should be enabled at boot. + +####`service_ensure` + +Determines if the service should be running or not. + +####`service_manage` + +Selects whether Puppet should manage the service. + +####`service_name` + +Selects the name of the ntp service for Puppet to manage. + +####`udlc` + +Enables configs for undisciplined local clock, regardless of +status as a virtual machine. + + +##Limitations + +This module has been built on and tested against Puppet 2.7 and higher. + +The module has been tested on: + +* RedHat Enterprise Linux 5/6 +* Debian 6/7 +* CentOS 5/6 +* Ubuntu 12.04 +* Gentoo +* Arch Linux +* FreeBSD + +Testing on other platforms has been light and cannot be guaranteed. + +##Development + +Puppet Labs modules on the Puppet Forge are open projects, and community +contributions are essential for keeping them great. We can’t access the +huge number of platforms and myriad of hardware, software, and deployment +configurations that Puppet is intended to serve. + +We want to keep it as easy as possible to contribute changes so that our +modules work in your environment. There are a few guidelines that we need +contributors to follow so that we can have a chance of keeping on top of things. + +You can read the complete module contribution guide [on the Puppet Labs wiki.](http://projects.puppetlabs.com/projects/module-site/wiki/Module_contributing) + +###Contributors + +The list of contributors can be found at: [https://github.com/puppetlabs/puppetlabs-ntp/graphs/contributors](https://github.com/puppetlabs/puppetlabs-ntp/graphs/contributors) diff --git a/modules/ntp/Rakefile b/modules/ntp/Rakefile new file mode 100644 index 0000000..cd3d379 --- /dev/null +++ b/modules/ntp/Rakefile @@ -0,0 +1 @@ +require 'puppetlabs_spec_helper/rake_tasks' diff --git a/modules/ntp/checksums.json b/modules/ntp/checksums.json new file mode 100644 index 0000000..0235517 --- /dev/null +++ b/modules/ntp/checksums.json @@ -0,0 +1,41 @@ +{ + "CHANGELOG.md": "43274ffb7445185b6efe8e6d4d181068", + "CONTRIBUTING.md": "2ef1d6f4417dde9af6c7f46f5c8a864b", + "Gemfile": "bbc819d69940a071a13963659787748a", + "Gemfile.lock": "86b33786b77d2497e910ed2b10cdfd58", + "LICENSE": "f0b6fdc310531526f257378d7bad0044", + "README.markdown": "29d76544eaf8c6669c5a3c1ea9137b89", + "Rakefile": "0254db5d3fc38c67a2c160d7296a24f8", + "manifests/config.pp": "8d9afb6e4327277c96c5617ad687043a", + "manifests/init.pp": "81c730134da0066aecb0e0048c7e15ba", + "manifests/install.pp": "ac33c5733f4321a9af7a4735265c1986", + "manifests/params.pp": "8570440dcda436999ce22514c2bd9dd7", + "manifests/service.pp": "350238b50e9cb896d270a2c76a64334f", + "metadata.json": "dc2dd0958bd17d382d0bed52693c06e9", + "spec/acceptance/class_spec.rb": "5c23f02ba486f3efd0cab3933ae35027", + "spec/acceptance/disable_monitoring_spec.rb": "059972f633098dbc5d20739c28733847", + "spec/acceptance/nodesets/centos-64-x64-pe.yml": "ec075d95760df3d4702abea1ce0a829b", + "spec/acceptance/nodesets/centos-64-x64.yml": "092dd2c588a9f87fa1fb12997c0723ef", + "spec/acceptance/nodesets/centos-65-x64.yml": "3e5c36e6aa5a690229e720f4048bb8af", + "spec/acceptance/nodesets/default.yml": "092dd2c588a9f87fa1fb12997c0723ef", + "spec/acceptance/nodesets/fedora-18-x64.yml": "80e41b1ee16ea489f53164bfdae58855", + "spec/acceptance/nodesets/sles-11-x64.yml": "44e4c6c15c018333bfa9840a5e702f66", + "spec/acceptance/nodesets/ubuntu-server-10044-x64.yml": "75e86400b7889888dc0781c0ae1a1297", + "spec/acceptance/nodesets/ubuntu-server-12042-x64.yml": "d30d73e34cd50b043c7d14e305955269", + "spec/acceptance/ntp_config_spec.rb": "3f8cac3f5ed32aab916567125f758bea", + "spec/acceptance/ntp_install_spec.rb": "dd2d6705eb13303fdcf84044bc36fd7c", + "spec/acceptance/ntp_parameters_spec.rb": "ed410a9251fb4eb28fd60c5b86b0d4d3", + "spec/acceptance/ntp_service_spec.rb": "8dc705e7e0cdc97d6f7f0c2735a74ffa", + "spec/acceptance/preferred_servers_spec.rb": "598861b69ac517785f85ad86a00b7e51", + "spec/acceptance/restrict_spec.rb": "e987b3c98857a9389ef9627aa72d23e7", + "spec/acceptance/unsupported_spec.rb": "46473b42539794169b7d5c6a0b10f089", + "spec/classes/ntp_spec.rb": "b93bd5752fa06a5074ee5b5df6a82a7c", + "spec/fixtures/modules/my_ntp/templates/ntp.conf.erb": "566e373728e9b13eda516115ff0a9fb0", + "spec/spec.opts": "a600ded995d948e393fbe2320ba8e51c", + "spec/spec_helper.rb": "0db89c9a486df193c0e40095422e19dc", + "spec/spec_helper_acceptance.rb": "fa2d2f453059310a815d3fb46112af1c", + "spec/unit/puppet/provider/README.markdown": "e52668944ee6af2fb5d5b9e798342645", + "spec/unit/puppet/type/README.markdown": "de26a7643813abd6c2e7e28071b1ef94", + "templates/ntp.conf.erb": "8ca9b49cee58ebd2676e7864a7348628", + "tests/init.pp": "d398e7687ec1d893ef23d1b7d2afc094" +} \ No newline at end of file diff --git a/modules/ntp/manifests/config.pp b/modules/ntp/manifests/config.pp new file mode 100644 index 0000000..1c8963d --- /dev/null +++ b/modules/ntp/manifests/config.pp @@ -0,0 +1,23 @@ +# +class ntp::config inherits ntp { + + if $keys_enable { + $directory = dirname($keys_file) + file { $directory: + ensure => directory, + owner => 0, + group => 0, + mode => '0755', + recurse => true, + } + } + + file { $config: + ensure => file, + owner => 0, + group => 0, + mode => '0644', + content => template($config_template), + } + +} diff --git a/modules/ntp/manifests/init.pp b/modules/ntp/manifests/init.pp new file mode 100644 index 0000000..467a01d --- /dev/null +++ b/modules/ntp/manifests/init.pp @@ -0,0 +1,60 @@ +class ntp ( + $autoupdate = $ntp::params::autoupdate, + $config = $ntp::params::config, + $config_template = $ntp::params::config_template, + $disable_monitor = $ntp::params::disable_monitor, + $driftfile = $ntp::params::driftfile, + $logfile = $ntp::params::logfile, + $keys_enable = $ntp::params::keys_enable, + $keys_file = $ntp::params::keys_file, + $keys_controlkey = $ntp::params::keys_controlkey, + $keys_requestkey = $ntp::params::keys_requestkey, + $keys_trusted = $ntp::params::keys_trusted, + $package_ensure = $ntp::params::package_ensure, + $package_name = $ntp::params::package_name, + $panic = $ntp::params::panic, + $preferred_servers = $ntp::params::preferred_servers, + $restrict = $ntp::params::restrict, + $servers = $ntp::params::servers, + $service_enable = $ntp::params::service_enable, + $service_ensure = $ntp::params::service_ensure, + $service_manage = $ntp::params::service_manage, + $service_name = $ntp::params::service_name, + $udlc = $ntp::params::udlc +) inherits ntp::params { + + validate_absolute_path($config) + validate_string($config_template) + validate_bool($disable_monitor) + validate_absolute_path($driftfile) + if $logfile { validate_absolute_path($logfile) } + validate_bool($keys_enable) + validate_re($keys_controlkey, ['^\d+$', '']) + validate_re($keys_requestkey, ['^\d+$', '']) + validate_array($keys_trusted) + validate_string($package_ensure) + validate_array($package_name) + validate_bool($panic) + validate_array($preferred_servers) + validate_array($restrict) + validate_array($servers) + validate_bool($service_enable) + validate_string($service_ensure) + validate_bool($service_manage) + validate_string($service_name) + validate_bool($udlc) + + if $autoupdate { + notice('autoupdate parameter has been deprecated and replaced with package_ensure. Set this to latest for the same behavior as autoupdate => true.') + } + + # Anchor this as per #8040 - this ensures that classes won't float off and + # mess everything up. You can read about this at: + # http://docs.puppetlabs.com/puppet/2.7/reference/lang_containment.html#known-issues + anchor { 'ntp::begin': } -> + class { '::ntp::install': } -> + class { '::ntp::config': } ~> + class { '::ntp::service': } -> + anchor { 'ntp::end': } + +} diff --git a/modules/ntp/manifests/install.pp b/modules/ntp/manifests/install.pp new file mode 100644 index 0000000..098949c --- /dev/null +++ b/modules/ntp/manifests/install.pp @@ -0,0 +1,9 @@ +# +class ntp::install inherits ntp { + + package { 'ntp': + ensure => $package_ensure, + name => $package_name, + } + +} diff --git a/modules/ntp/manifests/params.pp b/modules/ntp/manifests/params.pp new file mode 100644 index 0000000..456b321 --- /dev/null +++ b/modules/ntp/manifests/params.pp @@ -0,0 +1,182 @@ +class ntp::params { + + $autoupdate = false + $config_template = 'ntp/ntp.conf.erb' + $disable_monitor = false + $keys_enable = false + $keys_controlkey = '' + $keys_requestkey = '' + $keys_trusted = [] + $package_ensure = 'present' + $preferred_servers = [] + $service_enable = true + $service_ensure = 'running' + $service_manage = true + $udlc = false + + # On virtual machines allow large clock skews. + $panic = str2bool($::is_virtual) ? { + true => false, + default => true, + } + + $default_config = '/etc/ntp.conf' + $default_keys_file = '/etc/ntp/keys' + $default_driftfile = '/var/lib/ntp/drift' + $default_package_name = ['ntp'] + $default_service_name = 'ntpd' + + case $::osfamily { + 'AIX': { + $keys_file = '/etc/ntp.keys' + $driftfile = '/etc/ntp.drift' + $package_name = [ 'bos.net.tcp.client' ] + $restrict = [ + 'default nomodify notrap nopeer noquery', + '127.0.0.1', + ] + $service_name = 'xntpd' + $servers = [ + '0.debian.pool.ntp.org iburst', + '1.debian.pool.ntp.org iburst', + '2.debian.pool.ntp.org iburst', + '3.debian.pool.ntp.org iburst', + ] + } + 'Debian': { + $restrict = [ + 'default kod nomodify notrap nopeer noquery', + '-6 default kod nomodify notrap nopeer noquery', + '127.0.0.1', + '-6 ::1', + ] + $service_name = 'ntp' + $servers = [ + '0.debian.pool.ntp.org iburst', + '1.debian.pool.ntp.org iburst', + '2.debian.pool.ntp.org iburst', + '3.debian.pool.ntp.org iburst', + ] + } + 'RedHat': { + $restrict = [ + 'default kod nomodify notrap nopeer noquery', + '-6 default kod nomodify notrap nopeer noquery', + '127.0.0.1', + '-6 ::1', + ] + $servers = [ + '0.centos.pool.ntp.org', + '1.centos.pool.ntp.org', + '2.centos.pool.ntp.org', + ] + } + 'SuSE': { + $driftfile = '/var/lib/ntp/drift/ntp.drift' + $restrict = [ + 'default kod nomodify notrap nopeer noquery', + '-6 default kod nomodify notrap nopeer noquery', + '127.0.0.1', + '-6 ::1', + ] + $service_name = 'ntp' + $servers = [ + '0.opensuse.pool.ntp.org', + '1.opensuse.pool.ntp.org', + '2.opensuse.pool.ntp.org', + '3.opensuse.pool.ntp.org', + ] + } + 'FreeBSD': { + $driftfile = '/var/db/ntpd.drift' + $package_name = ['net/ntp'] + $restrict = [ + 'default kod nomodify notrap nopeer noquery', + '-6 default kod nomodify notrap nopeer noquery', + '127.0.0.1', + '-6 ::1', + ] + $servers = [ + '0.freebsd.pool.ntp.org iburst maxpoll 9', + '1.freebsd.pool.ntp.org iburst maxpoll 9', + '2.freebsd.pool.ntp.org iburst maxpoll 9', + '3.freebsd.pool.ntp.org iburst maxpoll 9', + ] + } + 'Archlinux': { + $restrict = [ + 'default kod nomodify notrap nopeer noquery', + '-6 default kod nomodify notrap nopeer noquery', + '127.0.0.1', + '-6 ::1', + ] + $servers = [ + '0.pool.ntp.org', + '1.pool.ntp.org', + '2.pool.ntp.org', + ] + } + # Gentoo was added as its own $::osfamily in Facter 1.7.0 + 'Gentoo': { + $package_name = ['net-misc/ntp'] + $restrict = [ + 'default kod nomodify notrap nopeer noquery', + '-6 default kod nomodify notrap nopeer noquery', + '127.0.0.1', + '-6 ::1', + ] + $servers = [ + '0.gentoo.pool.ntp.org', + '1.gentoo.pool.ntp.org', + '2.gentoo.pool.ntp.org', + '3.gentoo.pool.ntp.org', + ] + } + 'Linux': { + # Account for distributions that don't have $::osfamily specific settings. + # Before Facter 1.7.0 Gentoo did not have its own $::osfamily + case $::operatingsystem { + 'Gentoo': { + $package_name = ['net-misc/ntp'] + $restrict = [ + 'default kod nomodify notrap nopeer noquery', + '-6 default kod nomodify notrap nopeer noquery', + '127.0.0.1', + '-6 ::1', + ] + $servers = [ + '0.gentoo.pool.ntp.org', + '1.gentoo.pool.ntp.org', + '2.gentoo.pool.ntp.org', + '3.gentoo.pool.ntp.org', + ] + } + default: { + fail("The ${module_name} module is not supported on an ${::operatingsystem} distribution.") + } + } + } + default: { + fail("The ${module_name} module is not supported on an ${::osfamily} based system.") + } + } + if $config == undef { + $config = $default_config + } + if $keys_file == undef { + $keys_file = $default_keys_file + } + if $drfitfile == undef { + $driftfile = $default_driftfile + } + if $package_name == undef { + $package_name = $default_package_name + } + if $service_name == undef { + $service_name = $default_service_name + } + + + + +} diff --git a/modules/ntp/manifests/service.pp b/modules/ntp/manifests/service.pp new file mode 100644 index 0000000..3f1ada0 --- /dev/null +++ b/modules/ntp/manifests/service.pp @@ -0,0 +1,18 @@ +# +class ntp::service inherits ntp { + + if ! ($service_ensure in [ 'running', 'stopped' ]) { + fail('service_ensure parameter must be running or stopped') + } + + if $service_manage == true { + service { 'ntp': + ensure => $service_ensure, + enable => $service_enable, + name => $service_name, + hasstatus => true, + hasrestart => true, + } + } + +} diff --git a/modules/ntp/metadata.json b/modules/ntp/metadata.json new file mode 100644 index 0000000..8e1b7d7 --- /dev/null +++ b/modules/ntp/metadata.json @@ -0,0 +1,87 @@ +{ + "name": "puppetlabs-ntp", + "version": "3.1.1", + "author": "Puppet Labs", + "summary": "NTP Module", + "license": "Apache Version 2.0", + "source": "git://github.com/puppetlabs/puppetlabs-ntp", + "project_page": "http://github.com/puppetlabs/puppetlabs-ntp", + "issues_url": "https://github.com/puppetlabs/puppetlabs-ntp/issues", + "operatingsystem_support": [ + { + "operatingsystem": "RedHat", + "operatingsystemrelease": [ + "5", + "6", + "7" + ] + }, + { + "operatingsystem": "CentOS", + "operatingsystemrelease": [ + "5", + "6" + ] + }, + { + "operatingsystem": "OracleLinux", + "operatingsystemrelease": [ + "5", + "6" + ] + }, + { + "operatingsystem": "Scientific", + "operatingsystemrelease": [ + "5", + "6" + ] + }, + { + "operatingsystem": "SLES", + "operatingsystemrelease": [ + "11 SP1" + ] + }, + { + "operatingsystem": "Debian", + "operatingsystemrelease": [ + "6", + "7" + ] + }, + { + "operatingsystem": "Ubuntu", + "operatingsystemrelease": [ + "10.04", + "12.04", + "14.04" + ] + }, + { + "operatingsystem": "AIX", + "operatingsystemrelease": [ + "5.3", + "6.1", + "7.1" + ] + } + ], + "requirements": [ + { + "name": "pe", + "version_requirement": "3.3.x" + }, + { + "name": "puppet", + "version_requirement": "3.x" + } + ], + "description": "NTP Module for Debian, Ubuntu, CentOS, RHEL, OEL, Fedora, FreeBSD, ArchLinux and Gentoo.", + "dependencies": [ + { + "name": "puppetlabs/stdlib", + "version_requirement": ">= 4.0.0" + } + ] +} diff --git a/modules/ntp/spec/acceptance/class_spec.rb b/modules/ntp/spec/acceptance/class_spec.rb new file mode 100644 index 0000000..41f5b71 --- /dev/null +++ b/modules/ntp/spec/acceptance/class_spec.rb @@ -0,0 +1,37 @@ +require 'spec_helper_acceptance' + +describe 'ntp class:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + it 'should run successfully' do + pp = "class { 'ntp': }" + + # Apply twice to ensure no errors the second time. + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stderr).not_to match(/error/i) + end + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stderr).not_to eq(/error/i) + + expect(r.exit_code).to be_zero + end + end + + context 'service_ensure => stopped:' do + it 'runs successfully' do + pp = "class { 'ntp': service_ensure => stopped }" + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stderr).not_to match(/error/i) + end + end + end + + context 'service_ensure => running:' do + it 'runs successfully' do + pp = "class { 'ntp': service_ensure => running }" + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stderr).not_to match(/error/i) + end + end + end +end diff --git a/modules/ntp/spec/acceptance/disable_monitoring_spec.rb b/modules/ntp/spec/acceptance/disable_monitoring_spec.rb new file mode 100644 index 0000000..709010b --- /dev/null +++ b/modules/ntp/spec/acceptance/disable_monitoring_spec.rb @@ -0,0 +1,30 @@ +require 'spec_helper_acceptance' + +describe "ntp class with disable_monitor:", :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + context 'should run successfully' do + pp = "class { 'ntp': disable_monitor => true }" + + it 'runs twice' do + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end + + describe file('/etc/ntp.conf') do + it { should contain('disable monitor') } + end + end + + context 'should run successfully' do + pp = "class { 'ntp': disable_monitor => false }" + + it 'runs twice' do + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end + + describe file('/etc/ntp.conf') do + it { should_not contain('disable monitor') } + end + end + +end diff --git a/modules/ntp/spec/acceptance/nodesets/centos-64-x64-pe.yml b/modules/ntp/spec/acceptance/nodesets/centos-64-x64-pe.yml new file mode 100644 index 0000000..7d9242f --- /dev/null +++ b/modules/ntp/spec/acceptance/nodesets/centos-64-x64-pe.yml @@ -0,0 +1,12 @@ +HOSTS: + centos-64-x64: + roles: + - master + - database + - dashboard + platform: el-6-x86_64 + box : centos-64-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: pe diff --git a/modules/ntp/spec/acceptance/nodesets/centos-64-x64.yml b/modules/ntp/spec/acceptance/nodesets/centos-64-x64.yml new file mode 100644 index 0000000..05540ed --- /dev/null +++ b/modules/ntp/spec/acceptance/nodesets/centos-64-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-64-x64: + roles: + - master + platform: el-6-x86_64 + box : centos-64-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/ntp/spec/acceptance/nodesets/centos-65-x64.yml b/modules/ntp/spec/acceptance/nodesets/centos-65-x64.yml new file mode 100644 index 0000000..4e2cb80 --- /dev/null +++ b/modules/ntp/spec/acceptance/nodesets/centos-65-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-65-x64: + roles: + - master + platform: el-6-x86_64 + box : centos-65-x64-vbox436-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-65-x64-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/ntp/spec/acceptance/nodesets/default.yml b/modules/ntp/spec/acceptance/nodesets/default.yml new file mode 100644 index 0000000..05540ed --- /dev/null +++ b/modules/ntp/spec/acceptance/nodesets/default.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-64-x64: + roles: + - master + platform: el-6-x86_64 + box : centos-64-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/ntp/spec/acceptance/nodesets/fedora-18-x64.yml b/modules/ntp/spec/acceptance/nodesets/fedora-18-x64.yml new file mode 100644 index 0000000..1361649 --- /dev/null +++ b/modules/ntp/spec/acceptance/nodesets/fedora-18-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + fedora-18-x64: + roles: + - master + platform: fedora-18-x86_64 + box : fedora-18-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/fedora-18-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/ntp/spec/acceptance/nodesets/sles-11-x64.yml b/modules/ntp/spec/acceptance/nodesets/sles-11-x64.yml new file mode 100644 index 0000000..41abe21 --- /dev/null +++ b/modules/ntp/spec/acceptance/nodesets/sles-11-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + sles-11-x64.local: + roles: + - master + platform: sles-11-x64 + box : sles-11sp1-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/sles-11sp1-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/ntp/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml b/modules/ntp/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml new file mode 100644 index 0000000..5ca1514 --- /dev/null +++ b/modules/ntp/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + ubuntu-server-10044-x64: + roles: + - master + platform: ubuntu-10.04-amd64 + box : ubuntu-server-10044-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-10044-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/ntp/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml b/modules/ntp/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml new file mode 100644 index 0000000..d065b30 --- /dev/null +++ b/modules/ntp/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + ubuntu-server-12042-x64: + roles: + - master + platform: ubuntu-12.04-amd64 + box : ubuntu-server-12042-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-12042-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/ntp/spec/acceptance/ntp_config_spec.rb b/modules/ntp/spec/acceptance/ntp_config_spec.rb new file mode 100644 index 0000000..196ba76 --- /dev/null +++ b/modules/ntp/spec/acceptance/ntp_config_spec.rb @@ -0,0 +1,36 @@ +require 'spec_helper_acceptance' + +case fact('osfamily') +when 'FreeBSD' + line = '0.freebsd.pool.ntp.org iburst maxpoll 9' +when 'Debian' + line = '0.debian.pool.ntp.org iburst' +when 'RedHat' + line = '0.centos.pool.ntp.org' +when 'SuSE' + line = '0.opensuse.pool.ntp.org' +when 'Gentoo' + line = '0.gentoo.pool.ntp.org' +when 'Linux' + case fact('operatingsystem') + when 'ArchLinux' + line = '0.pool.ntp.org' + when 'Gentoo' + line = '0.gentoo.pool.ntp.org' + end +when 'AIX' + line = '0.debian.pool.ntp.org iburst' +end + +describe 'ntp::config class', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + it 'sets up ntp.conf' do + apply_manifest(%{ + class { 'ntp': } + }, :catch_failures => true) + end + + describe file('/etc/ntp.conf') do + it { should be_file } + it { should contain line } + end +end diff --git a/modules/ntp/spec/acceptance/ntp_install_spec.rb b/modules/ntp/spec/acceptance/ntp_install_spec.rb new file mode 100644 index 0000000..1a451bb --- /dev/null +++ b/modules/ntp/spec/acceptance/ntp_install_spec.rb @@ -0,0 +1,31 @@ +require 'spec_helper_acceptance' + +case fact('osfamily') +when 'FreeBSD' + packagename = 'net/ntp' +when 'Gentoo' + packagename = 'net-misc/ntp' +when 'Linux' + case fact('operatingsystem') + when 'ArchLinux' + packagename = 'ntp' + when 'Gentoo' + packagename = 'net-misc/ntp' + end +when 'AIX' + packagename = 'bos.net.tcp.client' +else + packagename = 'ntp' +end + +describe 'ntp::install class', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + it 'installs the package' do + apply_manifest(%{ + class { 'ntp': } + }, :catch_failures => true) + end + + describe package(packagename) do + it { should be_installed } + end +end diff --git a/modules/ntp/spec/acceptance/ntp_parameters_spec.rb b/modules/ntp/spec/acceptance/ntp_parameters_spec.rb new file mode 100644 index 0000000..48e6cfd --- /dev/null +++ b/modules/ntp/spec/acceptance/ntp_parameters_spec.rb @@ -0,0 +1,165 @@ +require 'spec_helper_acceptance' + +case fact('osfamily') +when 'FreeBSD' + packagename = 'net/ntp' +when 'Gentoo' + packagename = 'net-misc/ntp' +when 'Linux' + case fact('operatingsystem') + when 'ArchLinux' + packagename = 'ntp' + when 'Gentoo' + packagename = 'net-misc/ntp' + end +when 'AIX' + packagename = 'bos.net.tcp.client' +else + packagename = 'ntp' +end + +describe "ntp class:", :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + it 'applies successfully' do + pp = "class { 'ntp': }" + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stderr).not_to match(/error/i) + end + end + + describe 'autoconfig' do + it 'raises a deprecation warning' do + pp = "class { 'ntp': autoupdate => true }" + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/autoupdate parameter has been deprecated and replaced with package_ensure/) + end + end + end + + describe 'config' do + it 'sets the ntp.conf location' do + pp = "class { 'ntp': config => '/etc/antp.conf' }" + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/antp.conf') do + it { should be_file } + end + end + + describe 'config_template' do + it 'sets up template' do + modulepath = default['distmoduledir'] + shell("mkdir -p #{modulepath}/test/templates") + shell("echo 'testcontent' >> #{modulepath}/test/templates/ntp.conf") + end + + it 'sets the ntp.conf location' do + pp = "class { 'ntp': config_template => 'test/ntp.conf' }" + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/ntp.conf') do + it { should be_file } + it { should contain 'testcontent' } + end + end + + describe 'driftfile' do + it 'sets the driftfile location' do + pp = "class { 'ntp': driftfile => '/tmp/driftfile' }" + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/ntp.conf') do + it { should be_file } + it { should contain 'driftfile /tmp/driftfile' } + end + end + + describe 'keys' do + it 'enables the key parameters' do + pp = <<-EOS + class { 'ntp': + keys_enable => true, + keys_file => '/etc/ntp/keys', + keys_controlkey => '/etc/ntp/controlkey', + keys_requestkey => '1', + keys_trusted => [ '1', '2' ], + } + EOS + # Rely on a shell command instead of a file{} here to avoid loops + # within puppet when it tries to manage /etc/ntp/keys before /etc/ntp. + shell("mkdir -p /etc/ntp && echo '1 M AAAABBBB' >> /etc/ntp/keys") + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/ntp.conf') do + it { should be_file } + it { should contain 'keys /etc/ntp/keys' } + it { should contain 'controlkey /etc/ntp/controlkey' } + it { should contain 'requestkey 1' } + it { should contain 'trustedkey 1 2' } + end + end + + describe 'package' do + it 'installs the right package' do + pp = <<-EOS + class { 'ntp': + package_ensure => present, + package_name => ['#{packagename}'], + } + EOS + apply_manifest(pp, :catch_failures => true) + end + + describe package(packagename) do + it { should be_installed } + end + end + + describe 'panic => false' do + it 'enables the tinker panic setting' do + pp = <<-EOS + class { 'ntp': + panic => false, + } + EOS + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/ntp.conf') do + it { should contain 'tinker panic' } + end + end + + describe 'panic => true' do + it 'disables the tinker panic setting' do + pp = <<-EOS + class { 'ntp': + panic => true, + } + EOS + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/ntp.conf') do + it { should_not contain 'tinker panic 0' } + end + end + + describe 'udlc' do + it 'adds a udlc' do + pp = "class { 'ntp': udlc => true }" + apply_manifest(pp, :catch_failures => true) + end + + describe file('/etc/ntp.conf') do + it { should be_file } + it { should contain '127.127.1.0' } + end + end + +end diff --git a/modules/ntp/spec/acceptance/ntp_service_spec.rb b/modules/ntp/spec/acceptance/ntp_service_spec.rb new file mode 100644 index 0000000..cac12de --- /dev/null +++ b/modules/ntp/spec/acceptance/ntp_service_spec.rb @@ -0,0 +1,63 @@ +require 'spec_helper_acceptance' + +case fact('osfamily') +when 'RedHat', 'FreeBSD', 'Linux', 'Gentoo' + servicename = 'ntpd' +when 'AIX' + servicename = 'xntpd' +else + servicename = 'ntp' +end + +describe 'ntp::service class', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + describe 'basic test' do + it 'sets up the service' do + apply_manifest(%{ + class { 'ntp': } + }, :catch_failures => true) + end + + describe service(servicename) do + it { should be_enabled } + it { should be_running } + end + end + + describe 'service parameters' do + it 'starts the service' do + pp = <<-EOS + class { 'ntp': + service_enable => true, + service_ensure => running, + service_manage => true, + service_name => '#{servicename}' + } + EOS + apply_manifest(pp, :catch_failures => true) + end + + describe service(servicename) do + it { should be_running } + it { should be_enabled } + end + end + + describe 'service is unmanaged' do + it 'shouldnt stop the service' do + pp = <<-EOS + class { 'ntp': + service_enable => false, + service_ensure => stopped, + service_manage => false, + service_name => '#{servicename}' + } + EOS + apply_manifest(pp, :catch_failures => true) + end + + describe service(servicename) do + it { should be_running } + it { should be_enabled } + end + end +end diff --git a/modules/ntp/spec/acceptance/preferred_servers_spec.rb b/modules/ntp/spec/acceptance/preferred_servers_spec.rb new file mode 100644 index 0000000..8db82ec --- /dev/null +++ b/modules/ntp/spec/acceptance/preferred_servers_spec.rb @@ -0,0 +1,24 @@ +require 'spec_helper_acceptance' + +describe 'preferred servers', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + pp = <<-EOS + class { '::ntp': + servers => ['a', 'b', 'c', 'd'], + preferred_servers => ['c', 'd'], + } + EOS + + it 'applies cleanly' do + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stderr).not_to match(/error/i) + end + end + + describe file('/etc/ntp.conf') do + it { should be_file } + it { should contain 'server a' } + it { should contain 'server b' } + it { should contain 'server c prefer' } + it { should contain 'server d prefer' } + end +end diff --git a/modules/ntp/spec/acceptance/restrict_spec.rb b/modules/ntp/spec/acceptance/restrict_spec.rb new file mode 100644 index 0000000..e07400a --- /dev/null +++ b/modules/ntp/spec/acceptance/restrict_spec.rb @@ -0,0 +1,20 @@ +require 'spec_helper_acceptance' + +describe "ntp class with restrict:", :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + context 'should run successfully' do + pp = "class { 'ntp': restrict => ['test restrict']}" + + it 'runs twice' do + 2.times do + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stderr).not_to match(/error/i) + end + end + end + end + + describe file('/etc/ntp.conf') do + it { should contain('test restrict') } + end + +end diff --git a/modules/ntp/spec/acceptance/unsupported_spec.rb b/modules/ntp/spec/acceptance/unsupported_spec.rb new file mode 100644 index 0000000..5f4490d --- /dev/null +++ b/modules/ntp/spec/acceptance/unsupported_spec.rb @@ -0,0 +1,10 @@ +require 'spec_helper_acceptance' + +describe 'unsupported distributions and OSes', :if => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + it 'should fail' do + pp = <<-EOS + class { 'ntp': } + EOS + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/is not supported on an/i) + end +end diff --git a/modules/ntp/spec/classes/ntp_spec.rb b/modules/ntp/spec/classes/ntp_spec.rb new file mode 100644 index 0000000..49d6712 --- /dev/null +++ b/modules/ntp/spec/classes/ntp_spec.rb @@ -0,0 +1,272 @@ +require 'spec_helper' + +describe 'ntp' do + + ['Debian', 'RedHat','SuSE', 'FreeBSD', 'Archlinux', 'Gentoo', 'Gentoo (Facter < 1.7)'].each do |system| + if system == 'Gentoo (Facter < 1.7)' + let(:facts) {{ :osfamily => 'Linux', :operatingsystem => 'Gentoo' }} + else + let(:facts) {{ :osfamily => system }} + end + + it { should contain_class('ntp::install') } + it { should contain_class('ntp::config') } + it { should contain_class('ntp::service') } + + describe "ntp::config on #{system}" do + it { should contain_file('/etc/ntp.conf').with_owner('0') } + it { should contain_file('/etc/ntp.conf').with_group('0') } + it { should contain_file('/etc/ntp.conf').with_mode('0644') } + + describe 'allows template to be overridden' do + let(:params) {{ :config_template => 'my_ntp/ntp.conf.erb' }} + it { should contain_file('/etc/ntp.conf').with({ + 'content' => /server foobar/}) + } + end + + describe "keys for osfamily #{system}" do + context "when enabled" do + let(:params) {{ + :keys_enable => true, + :keys_file => '/etc/ntp/ntp.keys', + :keys_trusted => ['1', '2', '3'], + :keys_controlkey => '2', + :keys_requestkey => '3', + }} + + it { should contain_file('/etc/ntp').with({ + 'ensure' => 'directory'}) + } + it { should contain_file('/etc/ntp.conf').with({ + 'content' => /trustedkey 1 2 3/}) + } + it { should contain_file('/etc/ntp.conf').with({ + 'content' => /controlkey 2/}) + } + it { should contain_file('/etc/ntp.conf').with({ + 'content' => /requestkey 3/}) + } + end + end + + context "when disabled" do + let(:params) {{ + :keys_enable => false, + :keys_file => '/etc/ntp/ntp.keys', + :keys_trusted => ['1', '2', '3'], + :keys_controlkey => '2', + :keys_requestkey => '3', + }} + + it { should_not contain_file('/etc/ntp').with({ + 'ensure' => 'directory'}) + } + it { should_not contain_file('/etc/ntp.conf').with({ + 'content' => /trustedkey 1 2 3/}) + } + it { should_not contain_file('/etc/ntp.conf').with({ + 'content' => /controlkey 2/}) + } + it { should_not contain_file('/etc/ntp.conf').with({ + 'content' => /requestkey 3/}) + } + end + + describe 'preferred servers' do + context "when set" do + let(:params) {{ + :servers => ['a', 'b', 'c', 'd'], + :preferred_servers => ['a', 'b'] + }} + + it { should contain_file('/etc/ntp.conf').with({ + 'content' => /server a prefer\nserver b prefer\nserver c\nserver d/}) + } + end + context "when not set" do + let(:params) {{ + :servers => ['a', 'b', 'c', 'd'], + :preferred_servers => [] + }} + + it { should_not contain_file('/etc/ntp.conf').with({ + 'content' => /server a prefer/}) + } + end + end + + describe "ntp::install on #{system}" do + let(:params) {{ :package_ensure => 'present', :package_name => ['ntp'], }} + + it { should contain_package('ntp').with( + :ensure => 'present', + :name => 'ntp' + )} + + describe 'should allow package ensure to be overridden' do + let(:params) {{ :package_ensure => 'latest', :package_name => ['ntp'] }} + it { should contain_package('ntp').with_ensure('latest') } + end + + describe 'should allow the package name to be overridden' do + let(:params) {{ :package_ensure => 'present', :package_name => ['hambaby'] }} + it { should contain_package('ntp').with_name('hambaby') } + end + end + + describe 'ntp::service' do + let(:params) {{ + :service_manage => true, + :service_enable => true, + :service_ensure => 'running', + :service_name => 'ntp' + }} + + describe 'with defaults' do + it { should contain_service('ntp').with( + :enable => true, + :ensure => 'running', + :name => 'ntp' + )} + end + + describe 'service_ensure' do + describe 'when overridden' do + let(:params) {{ :service_name => 'ntp', :service_ensure => 'stopped' }} + it { should contain_service('ntp').with_ensure('stopped') } + end + end + + describe 'service_manage' do + let(:params) {{ + :service_manage => false, + :service_enable => true, + :service_ensure => 'running', + :service_name => 'ntpd', + }} + + it 'when set to false' do + should_not contain_service('ntp').with({ + 'enable' => true, + 'ensure' => 'running', + 'name' => 'ntpd' + }) + end + end + end + end + + context 'ntp::config' do + describe "for operating system Gentoo (Facter < 1.7)" do + let(:facts) {{ :operatingsystem => 'Gentoo', + :osfamily => 'Linux' }} + + it 'uses the NTP pool servers by default' do + should contain_file('/etc/ntp.conf').with({ + 'content' => /server \d.gentoo.pool.ntp.org/, + }) + end + end + + describe "on osfamily Gentoo" do + let(:facts) {{ :osfamily => 'Gentoo' }} + + it 'uses the NTP pool servers by default' do + should contain_file('/etc/ntp.conf').with({ + 'content' => /server \d.gentoo.pool.ntp.org/, + }) + end + end + + describe "on osfamily Debian" do + let(:facts) {{ :osfamily => 'debian' }} + + it 'uses the debian ntp servers by default' do + should contain_file('/etc/ntp.conf').with({ + 'content' => /server \d.debian.pool.ntp.org iburst/, + }) + end + end + + describe "on osfamily RedHat" do + let(:facts) {{ :osfamily => 'RedHat' }} + + it 'uses the redhat ntp servers by default' do + should contain_file('/etc/ntp.conf').with({ + 'content' => /server \d.centos.pool.ntp.org/, + }) + end + end + + describe "on osfamily SuSE" do + let(:facts) {{ :osfamily => 'SuSE' }} + + it 'uses the opensuse ntp servers by default' do + should contain_file('/etc/ntp.conf').with({ + 'content' => /server \d.opensuse.pool.ntp.org/, + }) + end + end + + describe "on osfamily FreeBSD" do + let(:facts) {{ :osfamily => 'FreeBSD' }} + + it 'uses the freebsd ntp servers by default' do + should contain_file('/etc/ntp.conf').with({ + 'content' => /server \d.freebsd.pool.ntp.org iburst maxpoll 9/, + }) + end + end + + describe "on osfamily ArchLinux" do + let(:facts) {{ :osfamily => 'ArchLinux' }} + + it 'uses the NTP pool servers by default' do + should contain_file('/etc/ntp.conf').with({ + 'content' => /server \d.pool.ntp.org/, + }) + end + end + + describe "for operating system family unsupported" do + let(:facts) {{ + :osfamily => 'unsupported', + }} + + it { expect{ subject }.to raise_error( + /^The ntp module is not supported on an unsupported based system./ + )} + end + end + + describe 'for virtual machines' do + let(:facts) {{ :osfamily => 'Archlinux', + :is_virtual => 'true' }} + + it 'should not use local clock as a time source' do + should_not contain_file('/etc/ntp.conf').with({ + 'content' => /server.*127.127.1.0.*fudge.*127.127.1.0 stratum 10/, + }) + end + + it 'allows large clock skews' do + should contain_file('/etc/ntp.conf').with({ + 'content' => /tinker panic 0/, + }) + end + end + + describe 'for physical machines' do + let(:facts) {{ :osfamily => 'Archlinux', + :is_virtual => 'false' }} + + it 'disallows large clock skews' do + should_not contain_file('/etc/ntp.conf').with({ + 'content' => /tinker panic 0/, + }) + end + end + end + +end diff --git a/modules/ntp/spec/fixtures/modules/my_ntp/templates/ntp.conf.erb b/modules/ntp/spec/fixtures/modules/my_ntp/templates/ntp.conf.erb new file mode 100644 index 0000000..40cf67c --- /dev/null +++ b/modules/ntp/spec/fixtures/modules/my_ntp/templates/ntp.conf.erb @@ -0,0 +1,4 @@ +#my uber ntp config +# + +server foobar diff --git a/modules/ntp/spec/spec.opts b/modules/ntp/spec/spec.opts new file mode 100644 index 0000000..91cd642 --- /dev/null +++ b/modules/ntp/spec/spec.opts @@ -0,0 +1,6 @@ +--format +s +--colour +--loadby +mtime +--backtrace diff --git a/modules/ntp/spec/spec_helper.rb b/modules/ntp/spec/spec_helper.rb new file mode 100644 index 0000000..2c6f566 --- /dev/null +++ b/modules/ntp/spec/spec_helper.rb @@ -0,0 +1 @@ +require 'puppetlabs_spec_helper/module_spec_helper' diff --git a/modules/ntp/spec/spec_helper_acceptance.rb b/modules/ntp/spec/spec_helper_acceptance.rb new file mode 100644 index 0000000..0a59525 --- /dev/null +++ b/modules/ntp/spec/spec_helper_acceptance.rb @@ -0,0 +1,32 @@ +require 'beaker-rspec' + +UNSUPPORTED_PLATFORMS = [ 'windows', 'Solaris' ] + +unless ENV['RS_PROVISION'] == 'no' or ENV['BEAKER_provision'] == 'no' + if hosts.first.is_pe? + install_pe + else + install_puppet + end + hosts.each do |host| + on hosts, "mkdir -p #{host['distmoduledir']}" + end +end + +RSpec.configure do |c| + # Project root + proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) + + # Readable test descriptions + c.formatter = :documentation + + # Configure all nodes in nodeset + c.before :suite do + # Install module and dependencies + puppet_module_install(:source => proj_root, :module_name => 'ntp') + hosts.each do |host| + shell("/bin/touch #{default['puppetpath']}/hiera.yaml") + shell('puppet module install puppetlabs-stdlib', :acceptable_exit_codes => [0,1]) + end + end +end diff --git a/modules/ntp/spec/unit/puppet/provider/README.markdown b/modules/ntp/spec/unit/puppet/provider/README.markdown new file mode 100644 index 0000000..7025850 --- /dev/null +++ b/modules/ntp/spec/unit/puppet/provider/README.markdown @@ -0,0 +1,4 @@ +Provider Specs +============== + +Define specs for your providers under this directory. diff --git a/modules/ntp/spec/unit/puppet/type/README.markdown b/modules/ntp/spec/unit/puppet/type/README.markdown new file mode 100644 index 0000000..1ee19ac --- /dev/null +++ b/modules/ntp/spec/unit/puppet/type/README.markdown @@ -0,0 +1,4 @@ +Resource Type Specs +=================== + +Define specs for your resource types in this directory. diff --git a/modules/ntp/templates/ntp.conf.erb b/modules/ntp/templates/ntp.conf.erb new file mode 100644 index 0000000..83652ac --- /dev/null +++ b/modules/ntp/templates/ntp.conf.erb @@ -0,0 +1,53 @@ +# ntp.conf: Managed by puppet. +# +<% if @panic == false -%> +# Keep ntpd from panicking in the event of a large clock skew +# when a VM guest is suspended and resumed. +tinker panic 0 +<% end -%> + +<% if @disable_monitor == true -%> +disable monitor +<% end -%> + +<% if @restrict != [] -%> +# Permit time synchronization with our time source, but do not +# permit the source to query or modify the service on this system. +<% @restrict.flatten.each do |restrict| -%> +restrict <%= restrict %> +<% end %> +<% end -%> + +<% [@servers].flatten.each do |server| -%> +server <%= server %><% if @preferred_servers.include?(server) -%> prefer<% end %> +<% end -%> + +<% if scope.lookupvar('::is_virtual') == "false" or @udlc -%> +# Undisciplined Local Clock. This is a fake driver intended for backup +# and when no outside source of synchronized time is available. +server 127.127.1.0 +fudge 127.127.1.0 stratum 10 +restrict 127.127.1.0 +<% end -%> + +# Driftfile. +driftfile <%= @driftfile %> + +<% unless @logfile.nil? %> +# Logfile +logfile = <%= @logfile %> +<% end %> + +<% if @keys_enable -%> +keys <%= @keys_file %> +<% unless @keys_trusted.empty? -%> +trustedkey <%= @keys_trusted.join(' ') %> +<% end -%> +<% if @keys_requestkey != '' -%> +requestkey <%= @keys_requestkey %> +<% end -%> +<% if @keys_controlkey != '' -%> +controlkey <%= @keys_controlkey %> +<% end -%> + +<% end -%> diff --git a/modules/ntp/tests/init.pp b/modules/ntp/tests/init.pp new file mode 100644 index 0000000..e6d9b53 --- /dev/null +++ b/modules/ntp/tests/init.pp @@ -0,0 +1,11 @@ +node default { + + notify { 'enduser-before': } + notify { 'enduser-after': } + + class { 'ntp': + require => Notify['enduser-before'], + before => Notify['enduser-after'], + } + +} diff --git a/modules/postgresql/CHANGELOG.md b/modules/postgresql/CHANGELOG.md new file mode 100644 index 0000000..5f70a34 --- /dev/null +++ b/modules/postgresql/CHANGELOG.md @@ -0,0 +1,550 @@ +##2014-03-04 - Supported Release 3.3.3 +###Summary + +This is a supported release. This release removes a testing symlink that can +cause trouble on systems where /var is on a seperate filesystem from the +modulepath. + +####Features +####Bugfixes +####Known Bugs +* SLES is not supported. + +##2014-03-04 - Supported Release 3.3.2 +###Summary +This is a supported release. It fixes a problem with updating passwords on postgresql.org distributed versions of PostgreSQL. + +####Bugfixes +- Correct psql path when setting password on custom versions. +- Documentation updates +- Test updates + +####Known Bugs +* SLES is not supported. + + +##2014-02-12 - Version 3.3.1 +####Bugfix: +- Allow dynamic rubygems host + + +##2014-01-28 - Version 3.3.0 + +###Summary + +This release rolls up a bunch of bugfixes our users have found and fixed for +us over the last few months. This improves things for 9.1 users, and makes +this module usable on FreeBSD. + +This release is dedicated to 'bma', who's suffering with Puppet 3.4.1 issues +thanks to Puppet::Util::SUIDManager.run_and_capture. + +####Features + - Add lc_ config entry settings + - Can pass template at database creation. + - Add FreeBSD support. + - Add support for customer `xlogdir` parameter. + - Switch tests from rspec-system to beaker. (This isn't really a feature) + +####Bugfixes + - Properly fix the deprecated Puppet::Util::SUIDManager.run_and_capture errors. + - Fix NOREPLICATION option for Postgres 9.1 + - Wrong parameter name: manage_pg_conf -> manage_pg_hba_conf + - Add $postgresql::server::client_package_name, referred to by install.pp + - Add missing service_provider/service_name descriptions in ::globals. + - Fix several smaller typos/issues throughout. + - Exec['postgresql_initdb'] needs to be done after $datadir exists + - Prevent defined resources from floating in the catalog. + - Fix granting all privileges on a table. + - Add some missing privileges. + - Remove deprecated and unused concat::fragment parameters. + + +##2013-11-05 - Version 3.2.0 + +###Summary + +Add's support for Ubuntu 13.10 (and 14.04) as well as x, y, z. + +####Features +- Add versions for Ubuntu 13.10 and 14.04. +- Use default_database in validate_db_connection instead of a hardcoded +'postgres' +- Add globals/params layering for default_database. +- Allow specification of default database name. + +####Bugs +- Fixes to the README. + + +##2013-10-25 - Version 3.1.0 + +###Summary + +This is a minor feature and bug fix release. + +Firstly, the postgresql_psql type now includes a new parameter `search_path` which is equivalent to using `set search_path` which allows you to change the default schema search path. + +The default version of Fedora 17 has now been added, so that Fedora 17 users can enjoy the module. + +And finally we've extended the capabilities of the defined type postgresql::validate_db_connection so that now it can handle retrying and sleeping between retries. This feature has been monopolized to fix a bug we were seeing with startup race conditions, but it can also be used by remote systems to 'wait' for PostgreSQL to start before their Puppet run continues. + +####Features +- Defined $default_version for Fedora 17 (Bret Comnes) +- add search_path attribute to postgresql_psql resource (Jeremy Kitchen) +- (GH-198) Add wait and retry capability to validate_db_connection (Ken Barber) + +####Bugs +- enabling defined postgres user password without resetting on every puppet run (jonoterc) +- periods are valid in configuration variables also (Jeremy Kitchen) +- Add zero length string to join() function (Jarl Stefansson) +- add require of install to reload class (cdenneen) +- (GH-198) Fix race condition on postgresql startup (Ken Barber) +- Remove concat::setup for include in preparation for the next concat release (Ken Barber) + + +##2013-10-14 - Version 3.0.0 + +Final release of 3.0, enjoy! + + +##2013-10-14 - Version 3.0.0-rc3 + +###Summary + +Add a parameter to unmanage pg_hba.conf to fix a regression from 2.5, as well +as allowing owner to be passed into x. + +####Features +- `manage_pg_hba_conf` parameter added to control pg_hba.conf management. +- `owner` parameter added to server::db. + + +##2013-10-09 - Version 3.0.0-rc2 + +###Summary + +A few bugfixes have been found since -rc1. + +####Fixes +- Special case for $datadir on Amazon +- Fix documentation about username/password for the postgresql_hash function + + +##2013-10-01 - Version 3.0.0-rc1 + +###Summary + +Version 3 was a major rewrite to fix some internal dependency issues, and to +make the new Public API more clear. As a consequence a lot of things have +changed for version 3 and older revisions that we will try to outline here. + +(NOTE: The format of this CHANGELOG differs to normal in an attempt to +explain the scope of changes) + +* Server specific objects now moved under `postgresql::server::` namespace: + +To restructure server specific elements under the `postgresql::server::` +namespaces the following objects were renamed as such: + +`postgresql::database` -> `postgresql::server::database` +`postgresql::database_grant` -> `postgresql::server::database_grant` +`postgresql::db` -> `postgresql::server::db` +`postgresql::grant` -> `postgresql::server::grant` +`postgresql::pg_hba_rule` -> `postgresql::server::pg_hba_rule` +`postgresql::plperl` -> `postgresql::server::plperl` +`postgresql::contrib` -> `postgresql::server::contrib` +`postgresql::role` -> `postgresql::server::role` +`postgresql::table_grant` -> `postgresql::server::table_grant` +`postgresql::tablespace` -> `postgresql::server::tablespace` + +* New `postgresql::server::config_entry` resource for managing configuration: + +Previously we used the `file_line` resource to modify `postgresql.conf`. This +new revision now adds a new resource named `postgresql::server::config_entry` +for managing this file. For example: + +```puppet + postgresql::server::config_entry { 'check_function_bodies': + value => 'off', + } +``` + +If you were using `file_line` for this purpose, you should change to this new +methodology. + +* `postgresql_puppet_extras.conf` has been removed: + +Now that we have a methodology for managing `postgresql.conf`, and due to +concerns over the file management methodology using an `exec { 'touch ...': }` +as a way to create an empty file the existing postgresql\_puppet\_extras.conf +file is no longer managed by this module. + +If you wish to recreate this methodology yourself, use this pattern: + +```puppet + class { 'postgresql::server': } + + $extras = "/tmp/include.conf" + + file { $extras: + content => 'max_connections = 123', + notify => Class['postgresql::server::service'], + }-> + postgresql::server::config_entry { 'include': + value => $extras, + } +``` + +* All uses of the parameter `charset` changed to `encoding`: + +Since PostgreSQL uses the terminology `encoding` not `charset` the parameter +has been made consisent across all classes and resources. + +* The `postgresql` base class is no longer how you set globals: + +The old global override pattern was less then optimal so it has been fixed, +however we decided to demark this properly by specifying these overrides in +the class `postgresql::global`. Consult the documentation for this class now +to see what options are available. + +Also, some parameter elements have been moved between this and the +`postgresql::server` class where it made sense. + +* `config_hash` parameter collapsed for the `postgresql::server` class: + +Because the `config_hash` was really passing data through to what was in +effect an internal class (`postgresql::config`). And since we don't want this +kind of internal exposure the parameters were collapsed up into the +`postgresql::server` class directly. + +* Lots of changes to 'private' or 'undocumented' classes: + +If you were using these before, these have changed names. You should only use +what is documented in this README.md, and if you don't have what you need you +should raise a patch to add that feature to a public API. All internal classes +now have a comment at the top indicating them as private to make sure the +message is clear that they are not supported as Public API. + +* `pg_hba_conf_defaults` parameter included to turn off default pg\_hba rules: + +The defaults should be good enough for most cases (if not raise a bug) but if +you simply need an escape hatch, this setting will turn off the defaults. If +you want to do this, it may affect the rest of the module so make sure you +replace the rules with something that continues operation. + +* `postgresql::database_user` has now been removed: + +Use `postgresql::server::role` instead. + +* `postgresql::psql` resource has now been removed: + +Use `postgresql_psql` instead. In the future we may recreate this as a wrapper +to add extra capability, but it will not match the old behaviour. + +* `postgresql_default_version` fact has now been removed: + +It didn't make sense to have this logic in a fact any more, the logic has been +moved into `postgresql::params`. + +* `ripienaar/concat` is no longer used, instead we use `puppetlabs/concat`: + +The older concat module is now deprecated and moved into the +`puppetlabs/concat` namespace. Functionality is more or less identical, but +you may need to intervene during the installing of this package - as both use +the same `concat` namespace. + +--- +##2013-09-09 Release 2.5.0 + +###Summary + +The focus of this release is primarily to capture the fixes done to the +types and providers to make sure refreshonly works properly and to set +the stage for the large scale refactoring work of 3.0.0. + +####Features + + +####Bugfixes +- Use boolean for refreshonly. +- Fix postgresql::plperl documentation. +- Add two missing parameters to config::beforeservice +- Style fixes + + +##2013-08-01 Release 2.4.1 + +###Summary + +This minor bugfix release solves an idempotency issue when using plain text +passwords for the password_hash parameter for the postgresql::role defined +type. Without this, users would continually see resource changes everytime +your run Puppet. + +####Bugfixes +- Alter role call not idempotent with cleartext passwords (Ken Barber) + + +##2013-07-19 Release 2.4.0 + +###Summary + +This updates adds the ability to change permissions on tables, create template +databases from normal databases, manage PL-Perl's postgres package, and +disable the management of `pg_hba.conf`. + +####Features +- Add `postgresql::table_grant` defined resource +- Add `postgresql::plperl` class +- Add `manage_pg_hba_conf` parameter to the `postgresql::config` class +- Add `istemplate` parameter to the `postgresql::database` define + +####Bugfixes +- Update `postgresql::role` class to be able to update roles when modified +instead of only on creation. +- Update tests +- Fix documentation of `postgresql::database_grant` + + +##2.3.0 + +This feature release includes the following changes: + +* Add a new parameter `owner` to the `database` type. This can be used to + grant ownership of a new database to a specific user. (Bruno Harbulot) +* Add support for operating systems other than Debian/RedHat, as long as the + user supplies custom values for all of the required paths, package names, etc. + (Chris Price) +* Improved integration testing (Ken Barber) + + +##2.2.1 + +This release fixes a bug whereby one of our shell commands (psql) were not ran from a globally accessible directory. This was causing permission denied errors when the command attempted to change user without changing directory. + +Users of previous versions might have seen this error: + + Error: Error executing SQL; psql returned 256: 'could not change directory to "/root" + +This patch should correct that. + +#### Detail Changes + +* Set /tmp as default CWD for postgresql_psql + + +##2.2.0 + +This feature release introduces a number of new features and bug fixes. + +First of all it includes a new class named `postgresql::python` which provides you with a convenient way of install the python Postgresql client libraries. + + class { 'postgresql::python': + } + +You are now able to use `postgresql::database_user` without having to specify a password_hash, useful for different authentication mechanisms that do not need passwords (ie. cert, local etc.). + +We've also provided a lot more advanced custom parameters now for greater control of your Postgresql installation. Consult the class documentation for PuppetDB in the README. + +This release in particular has largely been contributed by the community members below, a big thanks to one and all. + +#### Detailed Changes + +* Add support for psycopg installation (Flaper Fesp and Dan Prince) +* Added default PostgreSQL version for Ubuntu 13.04 (Kamil Szymanski) +* Add ability to create users without a password (Bruno Harbulot) +* Three Puppet 2.6 fixes (Dominic Cleal) +* Add explicit call to concat::setup when creating concat file (Dominic Cleal) +* Fix readme typo (Jordi Boggiano) +* Update postgres_default_version for Ubuntu (Kamil Szymanski) +* Allow to set connection for noew role (Kamil Szymanski) +* Fix pg_hba_rule for postgres local access (Kamil Szymanski) +* Fix versions for travis-ci (Ken Barber) +* Add replication support (Jordi Boggiano) +* Cleaned up and added unit tests (Ken Barber) +* Generalization to provide more flexability in postgresql configuration (Karel Brezina) +* Create dependent directory for sudoers so tests work on Centos 5 (Ken Barber) +* Allow SQL commands to be run against a specific DB (Carlos Villela) +* Drop trailing comma to support Puppet 2.6 (Michael Arnold) + + +##2.1.1 + + +This release provides a bug fix for RHEL 5 and Centos 5 systems, or specifically systems using PostgreSQL 8.1 or older. On those systems one would have received the error: + + Error: Could not start Service[postgresqld]: Execution of ‘/sbin/service postgresql start’ returned 1: + +And the postgresql log entry: + + FATAL: unrecognized configuration parameter "include" + +This bug is due to a new feature we had added in 2.1.0, whereby the `include` directive in `postgresql.conf` was not compatible. As a work-around we have added checks in our code to make sure systems running PostgreSQL 8.1 or older do not have this directive added. + +#### Detailed Changes + +2013-01-21 - Ken Barber +* Only install `include` directive and included file on PostgreSQL >= 8.2 +* Add system tests for Centos 5 + + +##2.1.0 + +This release is primarily a feature release, introducing some new helpful constructs to the module. + +For starters, we've added the line `include 'postgresql_conf_extras.conf'` by default so extra parameters not managed by the module can be added by other tooling or by Puppet itself. This provides a useful escape-hatch for managing settings that are not currently managed by the module today. + +We've added a new defined resource for managing your tablespace, so you can now create new tablespaces using the syntax: + + postgresql::tablespace { 'dbspace': + location => '/srv/dbspace', + } + +We've added a locale parameter to the `postgresql` class, to provide a default. Also the parameter has been added to the `postgresql::database` and `postgresql::db` defined resources for changing the locale per database: + + postgresql::db { 'mydatabase': + user => 'myuser', + password => 'mypassword', + encoding => 'UTF8', + locale => 'en_NG', + } + +There is a new class for installing the necessary packages to provide the PostgreSQL JDBC client jars: + + class { 'postgresql::java': } + +And we have a brand new defined resource for managing fine-grained rule sets within your pg_hba.conf access lists: + + postgresql::pg_hba { 'Open up postgresql for access from 200.1.2.0/24': + type => 'host', + database => 'app', + user => 'app', + address => '200.1.2.0/24', + auth_method => 'md5', + } + +Finally, we've also added Travis-CI support and unit tests to help us iterate faster with tests to reduce regression. The current URL for these tests is here: https://travis-ci.org/puppetlabs/puppet-postgresql. Instructions on how to run the unit tests available are provided in the README for the module. + +A big thanks to all those listed below who made this feature release possible :-). + +#### Detailed Changes + +2013-01-18 - Simão Fontes & Flaper Fesp +* Remove trailing commas from params.pp property definition for Puppet 2.6.0 compatibility + +2013-01-18 - Lauren Rother +* Updated README.md to conform with best practices template + +2013-01-09 - Adrien Thebo +* Update postgresql_default_version to 9.1 for Debian 7.0 + +2013-01-28 - Karel Brezina +* Add support for tablespaces + +2013-01-16 - Chris Price & Karel Brezina +* Provide support for an 'include' config file 'postgresql_conf_extras.conf' that users can modify manually or outside of the module. + +2013-01-31 - jv +* Fix typo in README.pp for postgresql::db example + +2013-02-03 - Ken Barber +* Add unit tests and travis-ci support + +2013-02-02 - Ken Barber +* Add locale parameter support to the 'postgresql' class + +2013-01-21 - Michael Arnold +* Add a class for install the packages containing the PostgreSQL JDBC jar + +2013-02-06 - fhrbek +* Coding style fixes to reduce warnings in puppet-lint and Geppetto + +2013-02-10 - Ken Barber +* Provide new defined resource for managing pg_hba.conf + +2013-02-11 - Ken Barber +* Fix bug with reload of Postgresql on Redhat/Centos + +2013-02-15 - Erik Dalén +* Fix more style issues to reduce warnings in puppet-lint and Geppetto + +2013-02-15 - Erik Dalén +* Fix case whereby we were modifying a hash after creation + + +##2.0.1 + +Minor bugfix release. + +2013-01-16 - Chris Price + * Fix revoke command in database.pp to support postgres 8.1 (43ded42) + +2013-01-15 - Jordi Boggiano + * Add support for ubuntu 12.10 status (3504405) + +##2.0.0 + +Many thanks to the following people who contributed patches to this +release: + +* Adrien Thebo +* Albert Koch +* Andreas Ntaflos +* Brett Porter +* Chris Price +* dharwood +* Etienne Pelletier +* Florin Broasca +* Henrik +* Hunter Haugen +* Jari Bakken +* Jordi Boggiano +* Ken Barber +* nzakaria +* Richard Arends +* Spenser Gilliland +* stormcrow +* William Van Hevelingen + +Notable features: + + * Add support for versions of postgres other than the system default version + (which varies depending on OS distro). This includes optional support for + automatically managing the package repo for the "official" postgres yum/apt + repos. (Major thanks to Etienne Pelletier and + Ken Barber for their tireless efforts and patience on this + feature set!) For example usage see `tests/official-postgresql-repos.pp`. + + * Add some support for Debian Wheezy and Ubuntu Quantal + + * Add new `postgres_psql` type with a Ruby provider, to replace the old + exec-based `psql` type. This gives us much more flexibility around + executing SQL statements and controlling their logging / reports output. + + * Major refactor of the "spec" tests--which are actually more like + acceptance tests. We now support testing against multiple OS distros + via vagrant, and the framework is in place to allow us to very easily add + more distros. Currently testing against Cent6 and Ubuntu 10.04. + + * Fixed a bug that was preventing multiple databases from being owned by the + same user + (9adcd182f820101f5e4891b9f2ff6278dfad495c - Etienne Pelletier ) + + * Add support for ACLs for finer-grained control of user/interface access + (b8389d19ad78b4fb66024897097b4ed7db241930 - dharwood ) + + * Many other bug fixes and improvements! + +--- +##1.0.0 + +2012-09-17 - Version 0.3.0 released + +2012-09-14 - Chris Price + * Add a type for validating a postgres connection (ce4a049) + +2012-08-25 - Jari Bakken + * Remove trailing commas. (e6af5e5) + +2012-08-16 - Version 0.2.0 released diff --git a/modules/postgresql/Gemfile b/modules/postgresql/Gemfile new file mode 100644 index 0000000..cb5deec --- /dev/null +++ b/modules/postgresql/Gemfile @@ -0,0 +1,20 @@ +source ENV['GEM_SOURCE'] || "https://rubygems.org" + +group :development, :test do + gem 'rake' + gem 'pry', :require => false + gem 'puppetlabs_spec_helper', :require => false + gem 'rspec-puppet', '< 1.0' + gem 'puppet-lint', '~> 0.3.2' + gem 'beaker', :require => false + gem 'beaker-rspec', :require => false + gem 'serverspec', :require => false +end + +if puppetversion = ENV['PUPPET_GEM_VERSION'] + gem 'puppet', puppetversion, :require => false +else + gem 'puppet', :require => false +end + +# vim:ft=ruby diff --git a/modules/postgresql/Gemfile.lock b/modules/postgresql/Gemfile.lock new file mode 100644 index 0000000..8214eac --- /dev/null +++ b/modules/postgresql/Gemfile.lock @@ -0,0 +1,116 @@ +GEM + remote: https://rubygems.org/ + specs: + CFPropertyList (2.2.7) + beaker (1.7.0) + blimpy (~> 0.6) + fission (~> 0.4) + inifile (~> 2.0) + json (~> 1.8) + mime-types (~> 1.25) + net-scp (~> 1.1) + net-ssh (~> 2.6) + nokogiri (= 1.5.10) + rbvmomi (= 1.8.1) + unf (~> 0.1) + beaker-rspec (2.1.1) + beaker (~> 1.3) + rspec (~> 2.14) + serverspec (~> 0.14) + specinfra (~> 0.3) + blimpy (0.6.7) + fog + minitar + thor + builder (3.2.2) + coderay (1.1.0) + diff-lcs (1.2.5) + excon (0.31.0) + facter (1.7.5) + fission (0.5.0) + CFPropertyList (~> 2.2) + fog (1.19.0) + builder + excon (~> 0.31.0) + formatador (~> 0.2.0) + mime-types + multi_json (~> 1.0) + net-scp (~> 1.1) + net-ssh (>= 2.1.3) + nokogiri (~> 1.5) + ruby-hmac + formatador (0.2.4) + hiera (1.3.2) + json_pure + highline (1.6.21) + inifile (2.0.2) + json (1.8.1) + json_pure (1.8.1) + metaclass (0.0.4) + method_source (0.8.2) + mime-types (1.25.1) + minitar (0.5.4) + mocha (1.0.0) + metaclass (~> 0.0.1) + multi_json (1.8.4) + net-scp (1.1.2) + net-ssh (>= 2.6.5) + net-ssh (2.8.0) + nokogiri (1.5.10) + pry (0.9.12.6) + coderay (~> 1.0) + method_source (~> 0.8) + slop (~> 3.4) + puppet (3.4.3) + facter (~> 1.6) + hiera (~> 1.0) + rgen (~> 0.6.5) + puppet-lint (0.3.2) + puppetlabs_spec_helper (0.4.1) + mocha (>= 0.10.5) + rake + rspec (>= 2.9.0) + rspec-puppet (>= 0.1.1) + rake (10.1.1) + rbvmomi (1.8.1) + builder + nokogiri (>= 1.4.1) + trollop + rgen (0.6.6) + rspec (2.14.1) + rspec-core (~> 2.14.0) + rspec-expectations (~> 2.14.0) + rspec-mocks (~> 2.14.0) + rspec-core (2.14.8) + rspec-expectations (2.14.5) + diff-lcs (>= 1.1.3, < 2.0) + rspec-mocks (2.14.6) + rspec-puppet (0.1.6) + rspec + ruby-hmac (0.4.0) + serverspec (0.15.3) + highline + net-ssh + rspec (>= 2.13.0) + specinfra (>= 0.5.8) + slop (3.4.7) + specinfra (0.7.0) + thor (0.18.1) + trollop (2.0) + unf (0.1.3) + unf_ext + unf_ext (0.0.6) + +PLATFORMS + ruby + +DEPENDENCIES + beaker + beaker-rspec + pry + puppet + puppet-lint (~> 0.3.2) + puppetlabs_spec_helper + rake + rspec-puppet (< 1.0) + serverspec diff --git a/modules/postgresql/LICENSE b/modules/postgresql/LICENSE new file mode 100644 index 0000000..7a29c73 --- /dev/null +++ b/modules/postgresql/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2013 Puppet Labs + + 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/modules/postgresql/Modulefile b/modules/postgresql/Modulefile new file mode 100644 index 0000000..e0e9354 --- /dev/null +++ b/modules/postgresql/Modulefile @@ -0,0 +1,13 @@ +name 'puppetlabs-postgresql' +version '3.3.3' +source 'git://github.com/puppetlabs/puppet-postgresql.git' +author 'Inkling/Puppet Labs' +description 'PostgreSQL defined resource types' +summary 'PostgreSQL defined resource types' +license 'ASL 2.0' +project_page 'https://github.com/puppetlabs/puppet-postgresql' + +dependency 'puppetlabs/stdlib', '>=3.2.0 <5.0.0' +dependency 'puppetlabs/firewall', '>= 0.0.4' +dependency 'puppetlabs/apt', '>=1.1.0 <2.0.0' +dependency 'puppetlabs/concat', '>= 1.0.0 <2.0.0' diff --git a/modules/postgresql/NOTICE b/modules/postgresql/NOTICE new file mode 100644 index 0000000..c01b463 --- /dev/null +++ b/modules/postgresql/NOTICE @@ -0,0 +1,14 @@ +Puppetlabs postgresql module + +Copyright 2012 Inkling Systems Inc +Copyright 2012-2013 Puppet Labs Inc +Copyright 2012-2013 Camptocamp SA. + +This product includes software developed by: + The Puppet Labs Inc (http://www.puppetlabs.com/). + +This product includes also software developed by: + Camptocamp SA (http://www.camptocamp.com/) + +This product includes also software developed by: + Inkling Systems Inc (https://www.inkling.com/) diff --git a/modules/postgresql/README.md b/modules/postgresql/README.md new file mode 100644 index 0000000..7a26cb9 --- /dev/null +++ b/modules/postgresql/README.md @@ -0,0 +1,901 @@ +postgresql +========== + +Table of Contents +----------------- + +1. [Overview - What is the PostgreSQL module?](#overview) +2. [Module Description - What does the module do?](#module-description) +3. [Setup - The basics of getting started with PostgreSQL module](#setup) + * [PE 3.2 supported module](#pe-3.2-supported-module) + * [Configuring the server](#configuring-the-server) +4. [Usage - How to use the module for various tasks](#usage) +5. [Upgrading - Guide for upgrading from older revisions of this module](#upgrading) +6. [Reference - The classes, defines,functions and facts available in this module](#reference) +7. [Limitations - OS compatibility, etc.](#limitations) +8. [Development - Guide for contributing to the module](#development) +9. [Disclaimer - Licensing information](#disclaimer) +10. [Transfer Notice - Notice of authorship change](#transfer-notice) +11. [Contributors - List of module contributors](#contributors) + +Overview +-------- + +The PostgreSQL module allows you to easily manage postgres databases with Puppet. + +Module Description +------------------- + +PostgreSQL is a high-performance, free, open-source relational database server. The postgresql module allows you to manage PostgreSQL packages and services on several operating systems, while also supporting basic management of PostgreSQL databases and users. The module offers support for managing firewall for postgres ports on RedHat-based distros, as well as support for basic management of common security settings. + +Setup +----- + +**What puppetlabs-PostgreSQL affects:** + +* package/service/configuration files for PostgreSQL +* listened-to ports +* system firewall (optional) +* IP and mask (optional) + +**Introductory Questions** + +The postgresql module offers many security configuration settings. Before getting started, you will want to consider: + +* Do you want/need to allow remote connections? + * If yes, what about TCP connections? +* Would you prefer to work around your current firewall settings or overwrite some of them? +* How restrictive do you want the database superuser's permissions to be? + +Your answers to these questions will determine which of the module's parameters you'll want to specify values for. + +###PE 3.2 supported module + +PE 3.2 introduces Puppet Labs supported modules. The version of the postgresql module that ships within PE 3.2 is supported via normal [Puppet Enterprise support](http://puppetlabs.com/services/customer-support) channels. If you would like to access the [supported module](http://forge.puppetlabs.com/supported) version, you will need to uninstall the shipped module and install the supported version from the Puppet Forge. You can do this by first running + + # puppet module uninstall puppetlabs-postgresql +and then running + + # puppet module install puppetlabs/postgresql + +###Configuring the server + +The main configuration you'll need to do will be around the `postgresql::server` class. The default parameters are reasonable, but fairly restrictive regarding permissions for who can connect and from where. To manage a PostgreSQL server with sane defaults: + + class { 'postgresql::server': } + +For a more customized configuration: + + class { 'postgresql::server': + ip_mask_deny_postgres_user => '0.0.0.0/32', + ip_mask_allow_all_users => '0.0.0.0/0', + listen_addresses => '*', + ipv4acls => ['hostssl all johndoe 192.168.0.0/24 cert'], + manage_firewall => true, + postgres_password => 'TPSrep0rt!', + } + +Once you've completed your configuration of `postgresql::server`, you can test out your settings from the command line: + + $ psql -h localhost -U postgres + $ psql -h my.postgres.server -U + +If you get an error message from these commands, it means that your permissions are set in a way that restricts access from where you're trying to connect. That might be a good thing or a bad thing, depending on your goals. + +For more details about server configuration parameters consult the [PostgreSQL Runtime Configuration docs](http://www.postgresql.org/docs/9.2/static/runtime-config.html). + +Usage +----- + +###Creating a database + +There are many ways to set up a postgres database using the `postgresql::server::db` class. For instance, to set up a database for PuppetDB: + + class { 'postgresql::server': } + + postgresql::server::db { 'mydatabasename': + user => 'mydatabaseuser', + password => postgresql_password('mydatabaseuser', 'mypassword'), + } + +###Managing users, roles and permissions + +To manage users, roles and permissions: + + class { 'postgresql::server': } + + postgresql::server::role { 'marmot': + password_hash => postgresql_password('marmot', 'mypasswd'), + } + + postgresql::server::database_grant { 'test1': + privilege => 'ALL', + db => 'test1', + role => 'marmot', + } + + postgresql::server::table_grant { 'my_table of test2': + privilege => 'ALL', + table => 'my_table', + db => 'test2', + role => 'marmot', + } + +In this example, you would grant ALL privileges on the test1 database and on the `my_table` table of the test2 database to the user or group specified by dan. + +At this point, you would just need to plunk these database name/username/password values into your PuppetDB config files, and you are good to go. + +Upgrading +--------- + +###Upgrading from 2.x to version 3 + +*Note:* if you are upgrading for 2.x, you *must* read this, as just about everything has changed. + +Version 3 was a major rewrite to fix some internal dependency issues, and to make the new Public API more clear. As a consequence a lot of things have changed for version 3 and older revisions that we will try to outline here. + +####Server specific objects now moved under `postgresql::server::` namespace + +To restructure server specific elements under the `postgresql::server::` namespaces the following objects were renamed as such: + +* `postgresql::database` -> `postgresql::server::database` +* `postgresql::database_grant` -> `postgresql::server::database_grant` +* `postgresql::db` -> `postgresql::server::db` +* `postgresql::grant` -> `postgresql::server::grant` +* `postgresql::pg_hba_rule` -> `postgresql::server::pg_hba_rule` +* `postgresql::plperl` -> `postgresql::server::plperl` +* `postgresql::contrib` -> `postgresql::server::contrib` +* `postgresql::role` -> `postgresql::server::role` +* `postgresql::table_grant` -> `postgresql::server::table_grant` +* `postgresql::tablespace` -> `postgresql::server::tablespace` + +####New `postgresql::server::config_entry` resource for managing configuration + +Previously we used the `file_line` resource to modify `postgresql.conf`. This new revision now adds a new resource named `postgresql::server::config_entry` for managing this file. For example: + + postgresql::server::config_entry { 'check_function_bodies': + value => 'off', + } + +If you were using `file_line` for this purpose, you should change to this new methodology. + +####`postgresql_puppet_extras.conf` has been removed + +Now that we have a methodology for managing `postgresql.conf`, and due to concerns over the file management methodology using an `exec { 'touch ...': }` as a way to create an empty file the existing postgresql\_puppet\_extras.conf file is no longer managed by this module. + +If you wish to recreate this methodology yourself, use this pattern: + + class { 'postgresql::server': } + + $extras = "/tmp/include.conf" + + file { $extras: + content => 'max_connections = 123', + notify => Class['postgresql::server::service'], + }-> + postgresql::server::config_entry { 'include': + value => $extras, + } + +####All uses of the parameter `charset` changed to `encoding` + +Since PostgreSQL uses the terminology `encoding` not `charset` the parameter has been made consisent across all classes and resources. + +####The `postgresql` base class is no longer how you set globals + +The old global override pattern was less then optimal so it has been fixed, however we decided to demark this properly by specifying these overrides in the class `postgresql::globals`. Consult the documentation for this class now to see what options are available. + +Also, some parameter elements have been moved between this and the `postgresql::server` class where it made sense. + +####`config_hash` parameter collapsed for the `postgresql::server` class + +Because the `config_hash` was really passing data through to what was in effect an internal class (`postgresql::config`). And since we don't want this kind of internal exposure the parameters were collapsed up into the `postgresql::server` class directly. + +####Lots of changes to 'private' or 'undocumented' classes + +If you were using these before, these have changed names. You should only use what is documented in this README.md, and if you don't have what you need you should raise a patch to add that feature to a public API. All internal classes now have a comment at the top indicating them as private to make sure the message is clear that they are not supported as Public API. + +####`pg_hba_conf_defaults` parameter included to turn off default pg\_hba rules + +The defaults should be good enough for most cases (if not raise a bug) but if you simply need an escape hatch, this setting will turn off the defaults. If you want to do this, it may affect the rest of the module so make sure you replace the rules with something that continues operation. + +####`postgresql::database_user` has now been removed + +Use `postgresql::server::role` instead. + +####`postgresql::psql` resource has now been removed + +Use `postgresql_psql` instead. In the future we may recreate this as a wrapper to add extra capability, but it will not match the old behaviour. + +####`postgresql_default_version` fact has now been removed + +It didn't make sense to have this logic in a fact any more, the logic has been moved into `postgresql::params`. + +####`ripienaar/concat` is no longer used, instead we use `puppetlabs/concat` + +The older concat module is now deprecated and moved into the `puppetlabs/concat` namespace. Functionality is more or less identical, but you may need to intervene during the installing of this package - as both use the same `concat` namespace. + +Reference +--------- + +The postgresql module comes with many options for configuring the server. While you are unlikely to use all of the below settings, they allow you a decent amount of control over your security settings. + +Classes: + +* [postgresql::client](#class-postgresqlclient) +* [postgresql::globals](#class-postgresqlglobals) +* [postgresql::lib::devel](#class-postgresqllibdevel) +* [postgresql::lib::java](#class-postgresqllibjava) +* [postgresql::lib::python](#class-postgresqllibpython) +* [postgresql::server](#class-postgresqlserver) +* [postgresql::server::plperl](#class-postgresqlserverplperl) +* [postgresql::server::contrib](#class-postgresqlservercontrib) + +Resources: + +* [postgresql::server::config_entry](#resource-postgresqlserverconfigentry) +* [postgresql::server::db](#resource-postgresqlserverdb) +* [postgresql::server::database](#resource-postgresqlserverdatabase) +* [postgresql::server::database_grant](#resource-postgresqlserverdatabasegrant) +* [postgresql::server::pg_hba_rule](#resource-postgresqlserverpghbarule) +* [postgresql::server::role](#resource-postgresqlserverrole) +* [postgresql::server::table_grant](#resource-postgresqlservertablegrant) +* [postgresql::server::tablespace](#resource-postgresqlservertablespace) +* [postgresql::validate_db_connection](#resource-postgresqlvalidatedbconnection) + +Functions: + +* [postgresql\_password](#function-postgresqlpassword) +* [postgresql\_acls\_to\_resources\_hash](#function-postgresqlaclstoresourceshashaclarray-id-orderoffset) + + +###Class: postgresql::globals +*Note:* most server specific defaults should be overriden in the `postgresql::server` class. This class should only be used if you are using a non-standard OS or if you are changing elements such as `version` or `manage_package_repo` that can only be changed here. + +This class allows you to configure the main settings for this module in a global way, to be used by the other classes and defined resources. On its own it does nothing. + +For example, if you wanted to overwrite the default `locale` and `encoding` for all classes you could use the following combination: + + class { 'postgresql::globals': + encoding => 'UTF8', + locale => 'en_NG', + }-> + class { 'postgresql::server': + } + +That would make the `encoding` and `locale` the default for all classes and defined resources in this module. + +If you want to use the upstream PostgreSQL packaging, and be specific about the version you wish to download, you could use something like this: + + class { 'postgresql::globals': + manage_package_repo => true, + version => '9.2', + }-> + class { 'postgresql::server': } + +####`client_package_name` +This setting can be used to override the default postgresql client package name. If not specified, the module will use whatever package name is the default for your OS distro. + +####`server_package_name` +This setting can be used to override the default postgresql server package name. If not specified, the module will use whatever package name is the default for your OS distro. + +####`contrib_package_name` +This setting can be used to override the default postgresql contrib package name. If not specified, the module will use whatever package name is the default for your OS distro. + +####`devel_package_name` +This setting can be used to override the default postgresql devel package name. If not specified, the module will use whatever package name is the default for your OS distro. + +####`java_package_name` +This setting can be used to override the default postgresql java package name. If not specified, the module will use whatever package name is the default for your OS distro. + +####`plperl_package_name` +This setting can be used to override the default postgresql PL/perl package name. If not specified, the module will use whatever package name is the default for your OS distro. + +####`python_package_name` +This setting can be used to override the default postgresql Python package name. If not specified, the module will use whatever package name is the default for your OS distro. + +####`service_name` +This setting can be used to override the default postgresql service name. If not specified, the module will use whatever service name is the default for your OS distro. + +####`service_provider` +This setting can be used to override the default postgresql service provider. If not specified, the module will use whatever service provider is the default for your OS distro. + +####`service_status` +This setting can be used to override the default status check command for your PostgreSQL service. If not specified, the module will use whatever service status is the default for your OS distro. + +####`default_database` +This setting is used to specify the name of the default database to connect with. On most systems this will be "postgres". + +####`initdb_path` +Path to the `initdb` command. + +####`createdb_path` +Path to the `createdb` command. + +####`psql_path` +Path to the `psql` command. + +####`pg_hba_conf_path` +Path to your `pg\_hba.conf` file. + +####`postgresql_conf_path` +Path to your `postgresql.conf` file. + +####`pg_hba_conf_defaults` +If false, disables the defaults supplied with the module for `pg\_hba.conf`. This is useful if you disagree with the defaults and wish to override them yourself. Be sure that your changes of course align with the rest of the module, as some access is required to perform basic `psql` operations for example. + +####`datadir` +This setting can be used to override the default postgresql data directory for the target platform. If not specified, the module will use whatever directory is the default for your OS distro. + +####`confdir` +This setting can be used to override the default postgresql configuration directory for the target platform. If not specified, the module will use whatever directory is the default for your OS distro. + +####`bindir` +This setting can be used to override the default postgresql binaries directory for the target platform. If not specified, the module will use whatever directory is the default for your OS distro. + +####`xlogdir` +This setting can be used to override the default postgresql xlog directory. If not specified the module will use initdb's default path. + +####`user` +This setting can be used to override the default postgresql super user and owner of postgresql related files in the file system. If not specified, the module will use the user name 'postgres'. + +####`group` +This setting can be used to override the default postgresql user group to be used for related files in the file system. If not specified, the module will use the group name 'postgres'. + +####`version` +The version of PostgreSQL to install/manage. This is a simple way of providing a specific version such as '9.2' or '8.4' for example. + +Defaults to your operating system default. + +####`needs_initdb` +This setting can be used to explicitly call the initdb operation after server package is installed and before the postgresql service is started. If not specified, the module will decide whether to call initdb or not depending on your OS distro. + +####`encoding` +This will set the default encoding encoding for all databases created with this module. On certain operating systems this will be used during the `template1` initialization as well so it becomes a default outside of the module as well. Defaults to the operating system default. + +####`locale` +This will set the default database locale for all databases created with this module. On certain operating systems this will be used during the `template1` initialization as well so it becomes a default outside of the module as well. Defaults to `undef` which is effectively `C`. + +#####Debian + +On Debian you'll need to ensure that the 'locales-all' package is installed for full functionality of Postgres. + +####`firewall_supported` +This allows you to override the automated detection to see if your OS supports the `firewall` module. + +####`manage_package_repo` +If `true` this will setup the official PostgreSQL repositories on your host. Defaults to `false`. + +###Class: postgresql::server +The following list are options that you can set in the `config_hash` parameter of `postgresql::server`. + +####`ensure` +This value default to `present`. When set to `absent` it will remove all packages, configuration and data so use this with extreme caution. + +####`version` +This will set the version of the PostgreSQL software to install. Defaults to your operating systems default. + +####`postgres_password` +This value defaults to `undef`, meaning the super user account in the postgres database is a user called `postgres` and this account does not have a password. If you provide this setting, the module will set the password for the `postgres` user to your specified value. + +####`package_name` +The name of the package to use for installing the server software. Defaults to the default for your OS distro. + +####`package_ensure` +Value to pass through to the `package` resource when creating the server instance. Defaults to `undef`. + +####`plperl_package_name` +This sets the default package name for the PL/Perl extension. Defaults to utilising the operating system default. + +####`service_name` +This setting can be used to override the default postgresql service name. If not specified, the module will use whatever service name is the default for your OS distro. + +####`service_name` +This setting can be used to override the default postgresql service provider. If not specified, the module will use whatever service name is the default for your OS distro. + +####`service_status` +This setting can be used to override the default status check command for your PostgreSQL service. If not specified, the module will use whatever service name is the default for your OS distro. + +####`default_database` +This setting is used to specify the name of the default database to connect with. On most systems this will be "postgres". + +####`listen_addresses` +This value defaults to `localhost`, meaning the postgres server will only accept connections from localhost. If you'd like to be able to connect to postgres from remote machines, you can override this setting. A value of `*` will tell postgres to accept connections from any remote machine. Alternately, you can specify a comma-separated list of hostnames or IP addresses. (For more info, have a look at the `postgresql.conf` file from your system's postgres package). + +####`ip_mask_deny_postgres_user` +This value defaults to `0.0.0.0/0`. Sometimes it can be useful to block the superuser account from remote connections if you are allowing other database users to connect remotely. Set this to an IP and mask for which you want to deny connections by the postgres superuser account. So, e.g., the default value of `0.0.0.0/0` will match any remote IP and deny access, so the postgres user won't be able to connect remotely at all. Conversely, a value of `0.0.0.0/32` would not match any remote IP, and thus the deny rule will not be applied and the postgres user will be allowed to connect. + +####`ip_mask_allow_all_users` +This value defaults to `127.0.0.1/32`. By default, Postgres does not allow any database user accounts to connect via TCP from remote machines. If you'd like to allow them to, you can override this setting. You might set it to `0.0.0.0/0` to allow database users to connect from any remote machine, or `192.168.0.0/16` to allow connections from any machine on your local 192.168 subnet. + +####`ipv4acls` +List of strings for access control for connection method, users, databases, IPv4 addresses; see [postgresql documentation](http://www.postgresql.org/docs/9.2/static/auth-pg-hba-conf.html) about `pg_hba.conf` for information (please note that the link will take you to documentation for the most recent version of Postgres, however links for earlier versions can be found on that page). + +####`ipv6acls` +List of strings for access control for connection method, users, databases, IPv6 addresses; see [postgresql documentation](http://www.postgresql.org/docs/9.2/static/auth-pg-hba-conf.html) about `pg_hba.conf` for information (please note that the link will take you to documentation for the most recent version of Postgres, however links for earlier versions can be found on that page). + +####`initdb_path` +Path to the `initdb` command. + +####`createdb_path` +Path to the `createdb` command. + +####`psql_path` +Path to the `psql` command. + +####`pg_hba_conf_path` +Path to your `pg\_hba.conf` file. + +####`postgresql_conf_path` +Path to your `postgresql.conf` file. + +####`pg_hba_conf_defaults` +If false, disables the defaults supplied with the module for `pg\_hba.conf`. This is useful if you di +sagree with the defaults and wish to override them yourself. Be sure that your changes of course alig +n with the rest of the module, as some access is required to perform basic `psql` operations for exam +ple. + +####`user` +This setting can be used to override the default postgresql super user and owner of postgresql related files in the file system. If not specified, the module will use the user name 'postgres'. + +####`group` +This setting can be used to override the default postgresql user group to be used for related files in the file system. If not specified, the module will use the group name 'postgres'. + +####`needs_initdb` +This setting can be used to explicitly call the initdb operation after server package is installed and before the postgresql service is started. If not specified, the module will decide whether to call initdb or not depending on your OS distro. + +####`encoding` +This will set the default encoding encoding for all databases created with this module. On certain operating systems this will be used during the `template1` initialization as well so it becomes a default outside of the module as well. Defaults to the operating system default. + +####`locale` +This will set the default database locale for all databases created with this module. On certain operating systems this will be used during the `template1` initialization as well so it becomes a default outside of the module as well. Defaults to `undef` which is effectively `C`. + +#####Debian + +On Debian you'll need to ensure that the 'locales-all' package is installed for full functionality of Postgres. + +####`manage_firewall` +This value defaults to `false`. Many distros ship with a fairly restrictive firewall configuration which will block the port that postgres tries to listen on. If you'd like for the puppet module to open this port for you (using the [puppetlabs-firewall](http://forge.puppetlabs.com/puppetlabs/firewall) module), change this value to true. Check the documentation for `puppetlabs/firewall` to ensure the rest of the global setup is applied, to ensure things like persistence and global rules are set correctly. + +####`manage_pg_hba_conf` +This value defaults to `true`. Whether or not manage the pg_hba.conf. If set to `true`, puppet will overwrite this file. If set to `false`, puppet will not modify the file. + + +###Class: postgresql::client + +This class installs postgresql client software. Alter the following parameters if you have a custom version you would like to install (Note: don't forget to make sure to add any necessary yum or apt repositories if specifying a custom version): + +####`package_name` +The name of the postgresql client package. + +####`package_ensure` +The ensure parameter passed on to postgresql client package resource. + + +###Class: postgresql::server::contrib +Installs the postgresql contrib package. + +####`package_name` +The name of the postgresql contrib package. + +####`package_ensure` +The ensure parameter passed on to postgresql contrib package resource. + + +###Class: postgresql::lib::devel +Installs the packages containing the development libraries for PostgreSQL. + +####`package_ensure` +Override for the `ensure` parameter during package installation. Defaults to `present`. + +####`package_name` +Overrides the default package name for the distribution you are installing to. Defaults to `postgresql-devel` or `postgresql-devel` depending on your distro. + + +###Class: postgresql::lib::java +This class installs postgresql bindings for Java (JDBC). Alter the following parameters if you have a custom version you would like to install (Note: don't forget to make sure to add any necessary yum or apt repositories if specifying a custom version): + +####`package_name` +The name of the postgresql java package. + +####`package_ensure` +The ensure parameter passed on to postgresql java package resource. + + +###Class: postgresql::lib::python +This class installs the postgresql Python libraries. For customer requirements you can customise the following parameters: + +####`package_name` +The name of the postgresql python package. + +####`package_ensure` +The ensure parameter passed on to postgresql python package resource. + + +###Class: postgresql::server::plperl +This class installs the PL/Perl procedural language for postgresql. + +####`package_name` +The name of the postgresql PL/Perl package. + +####`package_ensure` +The ensure parameter passed on to postgresql PL/Perl package resource. + + +###Resource: postgresql::server::config\_entry +This resource can be used to modify your `postgresql.conf` configuration file. + +Each resource maps to a line inside your `postgresql.conf` file, for example: + + postgresql::server::config_entry { 'check_function_bodies': + value => 'off', + } + +####`namevar` +Name of the setting to change. + +####`ensure` +Set to `absent` to remove an entry. + +####`value` +Value for the setting. + + +###Resource: postgresql::server::db +This is a convenience resource that creates a database, user and assigns necessary permissions in one go. + +For example, to create a database called `test1` with a corresponding user of the same name, you can use: + + postgresql::server::db { 'test1': + user => 'test1', + password => 'test1', + } + +####`namevar` +The namevar for the resource designates the name of the database. + +####`user` +User to create and assign access to the database upon creation. Mandatory. + +####`password` +Password for the created user. Mandatory. + +####`encoding` +Override the character set during creation of the database. Defaults to the default defined during installation. + +####`locale` +Override the locale during creation of the database. Defaults to the default defined during installation. + +####`grant` +Grant permissions during creation. Defaults to `ALL`. + +####`tablespace` +The name of the tablespace to allocate this database to. If not specifies, it defaults to the PostgreSQL default. + +####`istemplate` +Define database as a template. Defaults to `false`. + + +###Resource: postgresql::server::database +This defined type can be used to create a database with no users and no permissions, which is a rare use case. + +####`namevar` +The name of the database to create. + +####`dbname` +The name of the database, defaults to the namevar. + +####`owner` +Name of the database user who should be set as the owner of the database. Defaults to the $user variable set in `postgresql::server` or `postgresql::globals`. + +####`tablespace` +Tablespace for where to create this database. Defaults to the defaults defined during PostgreSQL installation. + +####`encoding` +Override the character set during creation of the database. Defaults to the default defined during installation. + +####`locale` +Override the locale during creation of the database. Defaults to the default defined during installation. + +####`istemplate` +Define database as a template. Defaults to `false`. + + +###Resource: postgresql::server::database\_grant +This defined type manages grant based access privileges for users, wrapping the `postgresql::server::database_grant` for database specific permissions. Consult the PostgreSQL documentation for `grant` for more information. + +####`namevar` +Used to uniquely identify this resource, but functionality not used during grant. + +####`privilege` +Can be one of `SELECT`, `TEMPORARY`, `TEMP`, `CONNECT`. `ALL` is used as a synonym for `CREATE`. If you need to add multiple privileges, a space delimited string can be used. + +####`db` +Database to grant access to. + +####`role` +Role or user whom you are granting access for. + +####`psql_db` +Database to execute the grant against. This should not ordinarily be changed from the default, which is `postgres`. + +####`psql_user` +OS user for running `psql`. Defaults to the default user for the module, usually `postgres`. + + +###Resource: postgresql::server::pg\_hba\_rule +This defined type allows you to create an access rule for `pg_hba.conf`. For more details see the [PostgreSQL documentation](http://www.postgresql.org/docs/8.2/static/auth-pg-hba-conf.html). + +For example: + + postgresql::server::pg_hba_rule { 'allow application network to access app database': + description => "Open up postgresql for access from 200.1.2.0/24", + type => 'host', + database => 'app', + user => 'app', + address => '200.1.2.0/24', + auth_method => 'md5', + } + +This would create a ruleset in `pg_hba.conf` similar to: + + # Rule Name: allow application network to access app database + # Description: Open up postgresql for access from 200.1.2.0/24 + # Order: 150 + host app app 200.1.2.0/24 md5 + +####`namevar` +A unique identifier or short description for this rule. The namevar doesn't provide any functional usage, but it is stored in the comments of the produced `pg_hba.conf` so the originating resource can be identified. + +####`description` +A longer description for this rule if required. Defaults to `none`. This description is placed in the comments above the rule in `pg_hba.conf`. + +####`type` +The type of rule, this is usually one of: `local`, `host`, `hostssl` or `hostnossl`. + +####`database` +A comma separated list of databases that this rule matches. + +####`user` +A comma separated list of database users that this rule matches. + +####`address` +If the type is not 'local' you can provide a CIDR based address here for rule matching. + +####`auth_method` +The `auth_method` is described further in the `pg_hba.conf` documentation, but it provides the method that is used for authentication for the connection that this rule matches. + +####`auth_option` +For certain `auth_method` settings there are extra options that can be passed. Consult the PostgreSQL `pg_hba.conf` documentation for further details. + +####`order` +An order for placing the rule in `pg_hba.conf`. Defaults to `150`. + +####`target` +This provides the target for the rule, and is generally an internal only property. Use with caution. + + +###Resource: postgresql::server::role +This resource creates a role or user in PostgreSQL. + +####`namevar` +The role name to create. + +####`password_hash` +The hash to use during password creation. If the password is not already pre-encrypted in a format that PostgreSQL supports, use the `postgresql_password` function to provide an MD5 hash here, for example: + + postgresql::role { "myusername": + password_hash => postgresql_password('myusername', 'mypassword'), + } + +####`createdb` +Whether to grant the ability to create new databases with this role. Defaults to `false`. + +####`createrole` +Whether to grant the ability to create new roles with this role. Defaults to `false`. + +####`login` +Whether to grant login capability for the new role. Defaults to `false`. + +####`superuser` +Whether to grant super user capability for the new role. Defaults to `false`. + +####`replication` +If `true` provides replication capabilities for this role. Defaults to `false`. + +####`connection_limit` +Specifies how many concurrent connections the role can make. Defaults to `-1` meaning no limit. + +####`username` +The username of the role to create, defaults to `namevar`. + + +###Resource: postgresql::server::table\_grant +This defined type manages grant based access privileges for users. Consult the PostgreSQL documentation for `grant` for more information. + +####`namevar` +Used to uniquely identify this resource, but functionality not used during grant. + +####`privilege` +Can be one of `SELECT`, `INSERT`, `UPDATE`, `REFERENCES`. `ALL` is used as a synonym for `CREATE`. If you need to add multiple privileges, a space delimited string can be used. + +####`table` +Table to grant access on. + +####`db` +Database of table. + +####`role` +Role or user whom you are granting access for. + +####`psql_db` +Database to execute the grant against. This should not ordinarily be changed from the default, which is `postgres`. + +####`psql_user` +OS user for running `psql`. Defaults to the default user for the module, usually `postgres`. + + +###Resource: postgresql::server::tablespace +This defined type can be used to create a tablespace. For example: + + postgresql::tablespace { 'tablespace1': + location => '/srv/space1', + } + +It will create the location if necessary, assigning it the same permissions as your +PostgreSQL server. + +####`namevar` +The tablespace name to create. + +####`location` +The path to locate this tablespace. + +####`owner` +The default owner of the tablespace. + +####`spcname` +Name of the tablespace. Defaults to `namevar`. + + +###Resource: postgresql::validate\_db\_connection +This resource can be utilised inside composite manifests to validate that a client has a valid connection with a remote PostgreSQL database. It can be ran from any node where the PostgreSQL client software is installed to validate connectivity before commencing other dependent tasks in your Puppet manifests, so it is often used when chained to other tasks such as: starting an application server, performing a database migration. + +Example usage: + + postgresql::validate_db_connection { 'validate my postgres connection': + database_host => 'my.postgres.host', + database_username => 'mydbuser', + database_password => 'mydbpassword', + database_name => 'mydbname', + }-> + exec { 'rake db:migrate': + cwd => '/opt/myrubyapp', + } + +####`namevar` +Uniquely identify this resource, but functionally does nothing. + +####`database_host` +The hostname of the database you wish to test. Defaults to 'undef' which generally uses the designated local unix socket. + +####`database_port` +Port to use when connecting. Default to 'undef' which generally defaults to 5432 depending on your PostgreSQL packaging. + +####`database_name` +The name of the database you wish to test. Defaults to 'postgres'. + +####`database_username` +Username to connect with. Defaults to 'undef', which when using a unix socket and ident auth will be the user you are running as. If the host is remote you must provide a username. + +####`database_password` +Password to connect with. Can be left blank, but that is not recommended. + +####`run_as` +The user to run the `psql` command with for authenticiation. This is important when trying to connect to a database locally using Unix sockets and `ident` authentication. It is not needed for remote testing. + +####`sleep` +Upon failure, sets the number of seconds to sleep for before trying again. + +####`tries` +Upon failure, sets the number of attempts before giving up and failing the resource. + +####`create_db_first` +This will ensure the database is created before running the test. This only really works if your test is local. Defaults to `true`. + + +###Function: postgresql\_password +If you need to generate a postgres encrypted password, use `postgresql_password`. You can call it from your production manifests if you don't mind them containing the clear text versions of your passwords, or you can call it from the command line and then copy and paste the encrypted password into your manifest: + + $ puppet apply --execute 'notify { "test": message => postgresql_password("username", "password") }' + +###Function: postgresql\_acls\_to\_resources\_hash(acl\_array, id, order\_offset) +This internal function converts a list of `pg_hba.conf` based acls (passed in as an array of strings) to a format compatible with the `postgresql::pg_hba_rule` resource. + +**This function should only be used internally by the module**. + +Limitations +------------ + +Works with versions of PostgreSQL from 8.1 through 9.2. + +Current it is only actively tested with the following operating systems: + +* Debian 6.x and 7.x +* Centos 5.x and 6.x +* Ubuntu 10.04 and 12.04 + +Although patches are welcome for making it work with other OS distros, it is considered best effort. + +Development +------------ + +Puppet Labs modules on the Puppet Forge are open projects, and community contributions are essential for keeping them great. We can't access the huge number of platforms and myriad of hardware, software, and deployment configurations that Puppet is intended to serve. + +We want to keep it as easy as possible to contribute changes so that our modules work in your environment. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. + +You can read the complete module contribution guide [on the Puppet Labs wiki.](http://projects.puppetlabs.com/projects/module-site/wiki/Module_contributing) + +### Tests + +There are two types of tests distributed with the module. Unit tests with rspec-puppet and system tests using rspec-system. + +For unit testing, make sure you have: + +* rake +* bundler + +Install the necessary gems: + + bundle install --path=vendor + +And then run the unit tests: + + bundle exec rake spec + +The unit tests are ran in Travis-CI as well, if you want to see the results of your own tests regsiter the service hook through Travis-CI via the accounts section for your Github clone of this project. + +If you want to run the system tests, make sure you also have: + +* vagrant > 1.2.x +* Virtualbox > 4.2.10 + +Then run the tests using: + + bundle exec rake spec:system + +To run the tests on different operating systems, see the sets available in .nodeset.yml and run the specific set with the following syntax: + + RSPEC_SET=debian-607-x64 bundle exec rake spec:system + +Transfer Notice +---------------- + +This Puppet module was originally authored by Inkling Systems. The maintainer preferred that Puppet Labs take ownership of the module for future improvement and maintenance as Puppet Labs is using it in the PuppetDB module. Existing pull requests and issues were transferred over, please fork and continue to contribute here instead of Inkling. + +Previously: [https://github.com/inkling/puppet-postgresql](https://github.com/inkling/puppet-postgresql) + +Contributors +------------ + + * Andrew Moon + * [Kenn Knowles](https://github.com/kennknowles) ([@kennknowles](https://twitter.com/KennKnowles)) + * Adrien Thebo + * Albert Koch + * Andreas Ntaflos + * Bret Comnes + * Brett Porter + * Chris Price + * dharwood + * Etienne Pelletier + * Florin Broasca + * Henrik + * Hunter Haugen + * Jari Bakken + * Jordi Boggiano + * Ken Barber + * nzakaria + * Richard Arends + * Spenser Gilliland + * stormcrow + * William Van Hevelingen diff --git a/modules/postgresql/Rakefile b/modules/postgresql/Rakefile new file mode 100644 index 0000000..3e7d005 --- /dev/null +++ b/modules/postgresql/Rakefile @@ -0,0 +1,11 @@ +require 'rubygems' +require 'bundler/setup' + +Bundler.require :default + +require 'puppetlabs_spec_helper/rake_tasks' +require 'puppet-lint/tasks/puppet-lint' + +task :default do + sh %{rake -T} +end diff --git a/modules/postgresql/files/RPM-GPG-KEY-PGDG b/modules/postgresql/files/RPM-GPG-KEY-PGDG new file mode 100644 index 0000000..065274e --- /dev/null +++ b/modules/postgresql/files/RPM-GPG-KEY-PGDG @@ -0,0 +1,30 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- +Version: GnuPG v1.4.7 (GNU/Linux) + +mQGiBEeD8koRBACC1VBRsUwGr9gxFFRho9kZpdRUjBJoPhkeOTvp9LzkdAQMFngr +BFi6N0ov1kCX7LLwBmDG+JPR7N+XcH9YR1coSHpLVg+JNy2kFDd4zAyWxJafjZ3a +9zFg9Yx+0va1BJ2t4zVcmKS4aOfbgQ5KwIOWUujalQW5Y+Fw39Gn86qjbwCg5dIo +tkM0l19h2sx50D027pV5aPsD/2c9pfcFTbMhB0CcKS836GH1qY+NCAdUwPs646ee +Ex/k9Uy4qMwhl3HuCGGGa+N6Plyon7V0TzZuRGp/1742dE8IO+I/KLy2L1d1Fxrn +XOTBZd8qe6nBwh12OMcKrsPBVBxn+iSkaG3ULsgOtx+HHLfa1/p22L5+GzGdxizr +peBuA/90cCp+lYcEwdYaRoFVR501yDOTmmzBc1DrsyWP79QMEGzMqa393G0VnqXt +L4pGmunq66Agw2EhPcIt3pDYiCmEt/obdVtSJH6BtmSDB/zYhbE8u3vLP3jfFDa9 +KXxgtYj0NvuUVoRmxSKm8jtfmj1L7zoKNz3jl+Ba3L0WxIv4+bRBUG9zdGdyZVNR +TCBSUE0gQnVpbGRpbmcgUHJvamVjdCA8cGdzcWxycG1zLWhhY2tlcnNAcGdmb3Vu +ZHJ5Lm9yZz6IYAQTEQIAIAUCR4PySgIbIwYLCQgHAwIEFQIIAwQWAgMBAh4BAheA +AAoJEB8W0uFELfD4jnkAoMqd6ZwwsgYHZ3hP9vt+DJt1uDW7AKDbRwP8ESKFhwdJ +8m91RPBeJW/tMLkCDQRHg/JKEAgA64+ZXgcERPYfZYo4p+yMTJAAa9aqnE3U4Ni6 +ZMB57GPuEy8NfbNya+HiftO8hoozmJdcI6XFyRBCDUVCdZ8SE+PJdOx2FFqZVIu6 +dKnr8ykhgLpNNEFDG3boK9UfLj/5lYQ3Y550Iym1QKOgyrJYeAp6sZ+Nx2PavsP3 +nMFCSD67BqAbcLCVQN7a2dAUXfEbfXJjPHXTbo1/kxtzE+KCRTLdXEbSEe3nHO04 +K/EgTBjeBUOxnciH5RylJ2oGy/v4xr9ed7R1jJtshsDKMdWApwoLlCBJ63jg/4T/ +z/OtXmu4AvmWaJxaTl7fPf2GqSqqb6jLCrQAH7AIhXr9V0zPZwADBQgAlpptNQHl +u7euIdIujFwwcxyQGfee6BG+3zaNSEHMVQMuc6bxuvYmgM9r7aki/b0YMfjJBk8v +OJ3Eh1vDH/woJi2iJ13vQ21ot+1JP3fMd6NPR8/qEeDnmVXu7QAtlkmSKI9Rdnjz +FFSUJrQPHnKsH4V4uvAM+njwYD+VFiwlBPTKNeL8cdBb4tPN2cdVJzoAp57wkZAN +VA2tKxNsTJKBi8wukaLWX8+yPHiWCNWItvyB4WCEp/rZKG4A868NM5sZQMAabpLd +l4fTiGu68OYgK9qUPZvhEAL2C1jPDVHPkLm+ZsD+90Pe66w9vB00cxXuHLzm8Pad +GaCXCY8h3xi6VIhJBBgRAgAJBQJHg/JKAhsMAAoJEB8W0uFELfD4K4cAoJ4yug8y +1U0cZEiF5W25HDzMTtaDAKCaM1m3Cbd+AZ0NGWNg/VvIX9MsPA== +=au6K +-----END PGP PUBLIC KEY BLOCK----- diff --git a/modules/postgresql/files/validate_postgresql_connection.sh b/modules/postgresql/files/validate_postgresql_connection.sh new file mode 100644 index 0000000..f126d99 --- /dev/null +++ b/modules/postgresql/files/validate_postgresql_connection.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash + +# usage is: validate_db_connection 2 50 psql + +SLEEP=$1 +TRIES=$2 +PSQL=$3 + +STATE=1 + +for (( c=1; c<=$TRIES; c++ )) +do + echo $c + if [ $c -gt 1 ] + then + echo 'sleeping' + sleep $SLEEP + fi + + /bin/echo "SELECT 1" | $PSQL + STATE=$? + + if [ $STATE -eq 0 ] + then + exit 0 + fi +done + +echo 'Unable to connect to postgresql' + +exit 1 diff --git a/modules/postgresql/lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb b/modules/postgresql/lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb new file mode 100644 index 0000000..7fa7854 --- /dev/null +++ b/modules/postgresql/lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb @@ -0,0 +1,76 @@ +module Puppet::Parser::Functions + newfunction(:postgresql_acls_to_resources_hash, :type => :rvalue, :doc => <<-EOS + This internal function translates the ipv(4|6)acls format into a resource + suitable for create_resources. It is not intended to be used outside of the + postgresql internal classes/defined resources. + + This function accepts an array of strings that are pg_hba.conf rules. It + will return a hash that can be fed into create_resources to create multiple + individual pg_hba_rule resources. + + The second parameter is an identifier that will be included in the namevar + to provide uniqueness. It must be a string. + + The third parameter is an order offset, so you can start the order at an + arbitrary starting point. + EOS + ) do |args| + func_name = "postgresql_acls_to_resources_hash()" + + raise(Puppet::ParseError, "#{func_name}: Wrong number of arguments " + + "given (#{args.size} for 3)") if args.size != 3 + + acls = args[0] + raise(Puppet::ParseError, "#{func_name}: first argument must be an array") \ + unless acls.instance_of? Array + + id = args[1] + raise(Puppet::ParseError, "#{func_name}: second argument must be a string") \ + unless id.instance_of? String + + offset = args[2].to_i + raise(Puppet::ParseError, "#{func_name}: third argument must be a number") \ + unless offset.instance_of? Fixnum + + resources = {} + acls.each do |acl| + index = acls.index(acl) + + parts = acl.split + + raise(Puppet::ParseError, "#{func_name}: acl line #{index} does not " + + "have enough parts") unless parts.length >= 4 + + resource = { + 'type' => parts[0], + 'database' => parts[1], + 'user' => parts[2], + 'order' => format('%03d', offset + index), + } + if parts[0] == 'local' then + resource['auth_method'] = parts[3] + if parts.length > 4 then + resource['auth_option'] = parts.last(parts.length - 4).join(" ") + end + else + if parts[4] =~ /^\d/ + resource['address'] = parts[3] + ' ' + parts[4] + resource['auth_method'] = parts[5] + + if parts.length > 6 then + resource['auth_option'] = parts.last(parts.length - 6).join(" ") + end + else + resource['address'] = parts[3] + resource['auth_method'] = parts[4] + + if parts.length > 5 then + resource['auth_option'] = parts.last(parts.length - 5).join(" ") + end + end + end + resources["postgresql class generated rule #{id} #{index}"] = resource + end + resources + end +end diff --git a/modules/postgresql/lib/puppet/parser/functions/postgresql_escape.rb b/modules/postgresql/lib/puppet/parser/functions/postgresql_escape.rb new file mode 100644 index 0000000..4089a4e --- /dev/null +++ b/modules/postgresql/lib/puppet/parser/functions/postgresql_escape.rb @@ -0,0 +1,25 @@ +require 'digest/md5' + +module Puppet::Parser::Functions + newfunction(:postgresql_escape, :type => :rvalue, :doc => <<-EOS + Safely escapes a string using $$ using a random tag which should be consistent + EOS + ) do |args| + + raise(Puppet::ParseError, "postgresql_escape(): Wrong number of arguments " + + "given (#{args.size} for 1)") if args.size != 1 + + password = args[0] + + if password !~ /\$\$/ + retval = "$$#{password}$$" + else + escape = Digest::MD5.hexdigest(password)[0..5].gsub(/\d/,'') + until password !~ /#{escape}/ + escape = Digest::MD5.hexdigest(escape)[0..5].gsub(/\d/,'') + end + retval = "$#{escape}$#{password}$#{escape}$" + end + retval + end +end diff --git a/modules/postgresql/lib/puppet/parser/functions/postgresql_password.rb b/modules/postgresql/lib/puppet/parser/functions/postgresql_password.rb new file mode 100644 index 0000000..0689e0e --- /dev/null +++ b/modules/postgresql/lib/puppet/parser/functions/postgresql_password.rb @@ -0,0 +1,18 @@ +# hash a string as mysql's "PASSWORD()" function would do it +require 'digest/md5' + +module Puppet::Parser::Functions + newfunction(:postgresql_password, :type => :rvalue, :doc => <<-EOS + Returns the postgresql password hash from the clear text username / password. + EOS + ) do |args| + + raise(Puppet::ParseError, "postgresql_password(): Wrong number of arguments " + + "given (#{args.size} for 2)") if args.size != 2 + + username = args[0] + password = args[1] + + 'md5' + Digest::MD5.hexdigest(password + username) + end +end diff --git a/modules/postgresql/lib/puppet/provider/postgresql_conf/parsed.rb b/modules/postgresql/lib/puppet/provider/postgresql_conf/parsed.rb new file mode 100644 index 0000000..c9366b5 --- /dev/null +++ b/modules/postgresql/lib/puppet/provider/postgresql_conf/parsed.rb @@ -0,0 +1,37 @@ +require 'puppet/provider/parsedfile' + +Puppet::Type.type(:postgresql_conf).provide( + :parsed, + :parent => Puppet::Provider::ParsedFile, + :default_target => '/etc/postgresql.conf', + :filetype => :flat +) do + desc "Set key/values in postgresql.conf." + + text_line :comment, :match => /^\s*#/ + text_line :blank, :match => /^\s*$/ + + record_line :parsed, + :fields => %w{name value comment}, + :optional => %w{comment}, + :match => /^\s*([\w\.]+)\s*=?\s*(.*?)(?:\s*#\s*(.*))?\s*$/, + :to_line => proc { |h| + + # simple string and numeric values don't need to be enclosed in quotes + dontneedquote = h[:value].match(/^(\w+|[0-9.-]+)$/) + dontneedequal = h[:name].match(/^(include|include_if_exists)$/i) + + str = h[:name].downcase # normalize case + str += dontneedequal ? ' ' : ' = ' + str += "'" unless dontneedquote && !dontneedequal + str += h[:value] + str += "'" unless dontneedquote && !dontneedequal + str += " # #{h[:comment]}" unless (h[:comment].nil? or h[:comment] == :absent) + str + }, + :post_parse => proc { |h| + h[:name].downcase! # normalize case + h[:value].gsub!(/(^'|'$)/, '') # strip out quotes + } + +end diff --git a/modules/postgresql/lib/puppet/provider/postgresql_psql/ruby.rb b/modules/postgresql/lib/puppet/provider/postgresql_psql/ruby.rb new file mode 100644 index 0000000..b86fb62 --- /dev/null +++ b/modules/postgresql/lib/puppet/provider/postgresql_psql/ruby.rb @@ -0,0 +1,93 @@ +Puppet::Type.type(:postgresql_psql).provide(:ruby) do + + def command() + if ((! resource[:unless]) or (resource[:unless].empty?)) + if (resource.refreshonly?) + # So, if there's no 'unless', and we're in "refreshonly" mode, + # we need to return the target command here. If we don't, + # then Puppet will generate an event indicating that this + # property has changed. + return resource[:command] + end + + # if we're not in refreshonly mode, then we return nil, + # which will cause Puppet to sync this property. This + # is what we want if there is no 'unless' value specified. + return nil + end + + if Puppet::PUPPETVERSION.to_f < 4 + output, status = run_unless_sql_command(resource[:unless]) + else + output = run_unless_sql_command(resource[:unless]) + status = output.exitcode + end + + if status != 0 + puts status + self.fail("Error evaluating 'unless' clause: '#{output}'") + end + result_count = output.strip.to_i + if result_count > 0 + # If the 'unless' query returned rows, then we don't want to execute + # the 'command'. Returning the target 'command' here will cause + # Puppet to treat this property as already being 'insync?', so it + # won't call the setter to run the 'command' later. + return resource[:command] + end + + # Returning 'nil' here will cause Puppet to see this property + # as out-of-sync, so it will call the setter later. + nil + end + + def command=(val) + output, status = run_sql_command(val) + + if status != 0 + self.fail("Error executing SQL; psql returned #{status}: '#{output}'") + end + end + + + def run_unless_sql_command(sql) + # for the 'unless' queries, we wrap the user's query in a 'SELECT COUNT', + # which makes it easier to parse and process the output. + run_sql_command('SELECT COUNT(*) FROM (' << sql << ') count') + end + + def run_sql_command(sql) + if resource[:search_path] + sql = "set search_path to #{Array(resource[:search_path]).join(',')}; #{sql}" + end + + command = [resource[:psql_path]] + command.push("-d", resource[:db]) if resource[:db] + command.push("-t", "-c", sql) + + if resource[:cwd] + Dir.chdir resource[:cwd] do + run_command(command, resource[:psql_user], resource[:psql_group]) + end + else + run_command(command, resource[:psql_user], resource[:psql_group]) + end + end + + def run_command(command, user, group) + if Puppet::PUPPETVERSION.to_f < 3.4 + Puppet::Util::SUIDManager.run_and_capture(command, user, group) + else + output = Puppet::Util::Execution.execute(command, { + :uid => user, + :gid => group, + :failonfail => false, + :combine => true, + :override_locale => true, + :custom_environment => {} + }) + [output, $CHILD_STATUS.dup] + end + end + +end diff --git a/modules/postgresql/lib/puppet/type/postgresql_conf.rb b/modules/postgresql/lib/puppet/type/postgresql_conf.rb new file mode 100644 index 0000000..f227fd7 --- /dev/null +++ b/modules/postgresql/lib/puppet/type/postgresql_conf.rb @@ -0,0 +1,31 @@ +module Puppet + newtype(:postgresql_conf) do + + @doc = "This type allows puppet to manage postgresql.conf parameters." + + ensurable + + newparam(:name) do + desc "The postgresql parameter name to manage." + isnamevar + + newvalues(/^[\w\.]+$/) + end + + newproperty(:value) do + desc "The value to set for this parameter." + end + + newproperty(:target) do + desc "The path to postgresql.conf" + defaultto { + if @resource.class.defaultprovider.ancestors.include?(Puppet::Provider::ParsedFile) + @resource.class.defaultprovider.default_target + else + nil + end + } + end + + end +end diff --git a/modules/postgresql/lib/puppet/type/postgresql_psql.rb b/modules/postgresql/lib/puppet/type/postgresql_psql.rb new file mode 100644 index 0000000..8646914 --- /dev/null +++ b/modules/postgresql/lib/puppet/type/postgresql_psql.rb @@ -0,0 +1,89 @@ +Puppet::Type.newtype(:postgresql_psql) do + + newparam(:name) do + desc "An arbitrary tag for your own reference; the name of the message." + isnamevar + end + + newproperty(:command) do + desc 'The SQL command to execute via psql.' + + defaultto { @resource[:name] } + + def sync(refreshing = false) + # We're overriding 'sync' here in order to do some magic + # in support of providing a 'refreshonly' parameter. This + # is kind of hacky because the logic for 'refreshonly' is + # spread between the type and the provider, but this is + # the least horrible way that I could determine to accomplish + # it. + # + # Note that our overridden version of 'sync' takes a parameter, + # 'refreshing', which the parent version doesn't take. This + # allows us to call the sync method directly from the 'refresh' + # method, and then inside of the body of 'sync' we can tell + # whether or not we're refreshing. + + if (!@resource.refreshonly? || refreshing) + # If we're not in 'refreshonly' mode, or we're not currently + # refreshing, then we just call the parent method. + super() + else + # If we get here, it means we're in 'refreshonly' mode and + # we're not being called by the 'refresh' method, so we + # just no-op. We'll be called again by the 'refresh' + # method momentarily. + nil + end + end + end + + newparam(:unless) do + desc "An optional SQL command to execute prior to the main :command; " + + "this is generally intended to be used for idempotency, to check " + + "for the existence of an object in the database to determine whether " + + "or not the main SQL command needs to be executed at all." + end + + newparam(:db) do + desc "The name of the database to execute the SQL command against." + end + + newparam(:search_path) do + desc "The schema search path to use when executing the SQL command" + end + + newparam(:psql_path) do + desc "The path to psql executable." + defaultto("psql") + end + + newparam(:psql_user) do + desc "The system user account under which the psql command should be executed." + defaultto("postgres") + end + + newparam(:psql_group) do + desc "The system user group account under which the psql command should be executed." + defaultto("postgres") + end + + newparam(:cwd, :parent => Puppet::Parameter::Path) do + desc "The working directory under which the psql command should be executed." + defaultto("/tmp") + end + + newparam(:refreshonly, :boolean => true) do + desc "If 'true', then the SQL will only be executed via a notify/subscribe event." + + defaultto(:false) + newvalues(:true, :false) + end + + def refresh() + # All of the magic for this type is attached to the ':command' property, so + # we just need to sync it to accomplish a 'refresh'. + self.property(:command).sync(true) + end + +end diff --git a/modules/postgresql/manifests/client.pp b/modules/postgresql/manifests/client.pp new file mode 100644 index 0000000..bdb821d --- /dev/null +++ b/modules/postgresql/manifests/client.pp @@ -0,0 +1,29 @@ +# Install client cli tool. See README.md for more details. +class postgresql::client ( + $package_name = $postgresql::params::client_package_name, + $package_ensure = 'present' +) inherits postgresql::params { + validate_string($package_name) + + package { 'postgresql-client': + ensure => $package_ensure, + name => $package_name, + tag => 'postgresql', + } + + $file_ensure = $package_ensure ? { + 'present' => 'file', + true => 'file', + 'absent' => 'absent', + false => 'absent', + default => 'file', + } + file { "/usr/local/bin/validate_postgresql_connection.sh": + ensure => $file_ensure, + source => "puppet:///modules/postgresql/validate_postgresql_connection.sh", + owner => 0, + group => 0, + mode => 0755, + } + +} diff --git a/modules/postgresql/manifests/globals.pp b/modules/postgresql/manifests/globals.pp new file mode 100644 index 0000000..ebc117d --- /dev/null +++ b/modules/postgresql/manifests/globals.pp @@ -0,0 +1,94 @@ +# Class for setting cross-class global overrides. See README.md for more +# details. +class postgresql::globals ( + $ensure = undef, + + $client_package_name = undef, + $server_package_name = undef, + $contrib_package_name = undef, + $devel_package_name = undef, + $java_package_name = undef, + $plperl_package_name = undef, + $python_package_name = undef, + + $service_name = undef, + $service_provider = undef, + $service_status = undef, + $default_database = undef, + + $initdb_path = undef, + $createdb_path = undef, + $psql_path = undef, + $pg_hba_conf_path = undef, + $postgresql_conf_path = undef, + + $pg_hba_conf_defaults = undef, + + $datadir = undef, + $confdir = undef, + $bindir = undef, + $xlogdir = undef, + + $user = undef, + $group = undef, + + $version = undef, + + $needs_initdb = undef, + + $encoding = undef, + $locale = undef, + + $manage_firewall = undef, + $manage_pg_hba_conf = undef, + $firewall_supported = undef, + + $manage_package_repo = undef +) { + # We are determining this here, because it is needed by the package repo + # class. + $default_version = $::osfamily ? { + /^(RedHat|Linux)/ => $::operatingsystem ? { + 'Fedora' => $::operatingsystemrelease ? { + /^(18|19|20)$/ => '9.2', + /^(17)$/ => '9.1', + default => undef, + }, + 'Amazon' => '9.2', + default => $::operatingsystemrelease ? { + /^6\./ => '8.4', + /^5\./ => '8.1', + default => undef, + }, + }, + 'Debian' => $::operatingsystem ? { + 'Debian' => $::operatingsystemrelease ? { + /^6\./ => '8.4', + /^(wheezy|7\.)/ => '9.1', + default => undef, + }, + 'Ubuntu' => $::operatingsystemrelease ? { + /^(14.04)$/ => '9.3', + /^(11.10|12.04|12.10|13.04|13.10)$/ => '9.1', + /^(10.04|10.10|11.04)$/ => '8.4', + default => undef, + }, + default => undef, + }, + 'Archlinux' => $::operatingsystem ? { + /Archlinux/ => '9.2', + default => '9.2', + }, + 'FreeBSD' => '93', + default => undef, + } + $globals_version = pick($version, $default_version, 'unknown') + + # Setup of the repo only makes sense globally, so we are doing this here. + if($manage_package_repo) { + class { 'postgresql::repo': + ensure => $ensure, + version => $globals_version + } + } +} diff --git a/modules/postgresql/manifests/lib/devel.pp b/modules/postgresql/manifests/lib/devel.pp new file mode 100644 index 0000000..0c446d4 --- /dev/null +++ b/modules/postgresql/manifests/lib/devel.pp @@ -0,0 +1,15 @@ +# This class installs postgresql development libraries. See README.md for more +# details. +class postgresql::lib::devel( + $package_name = $postgresql::params::devel_package_name, + $package_ensure = 'present' +) inherits postgresql::params { + + validate_string($package_name) + + package { 'postgresql-devel': + ensure => $package_ensure, + name => $package_name, + tag => 'postgresql', + } +} diff --git a/modules/postgresql/manifests/lib/java.pp b/modules/postgresql/manifests/lib/java.pp new file mode 100644 index 0000000..e9ee53d --- /dev/null +++ b/modules/postgresql/manifests/lib/java.pp @@ -0,0 +1,15 @@ +# This class installs the postgresql jdbc connector. See README.md for more +# details. +class postgresql::lib::java ( + $package_name = $postgresql::params::java_package_name, + $package_ensure = 'present' +) inherits postgresql::params { + + validate_string($package_name) + + package { 'postgresql-jdbc': + ensure => $package_ensure, + name => $package_name, + } + +} diff --git a/modules/postgresql/manifests/lib/python.pp b/modules/postgresql/manifests/lib/python.pp new file mode 100644 index 0000000..bfe0585 --- /dev/null +++ b/modules/postgresql/manifests/lib/python.pp @@ -0,0 +1,13 @@ +# This class installs the python libs for postgresql. See README.md for more +# details. +class postgresql::lib::python( + $package_name = $postgresql::params::python_package_name, + $package_ensure = 'present' +) inherits postgresql::params { + + package { 'python-psycopg2': + ensure => $package_ensure, + name => $package_name, + } + +} diff --git a/modules/postgresql/manifests/params.pp b/modules/postgresql/manifests/params.pp new file mode 100644 index 0000000..4f5ae97 --- /dev/null +++ b/modules/postgresql/manifests/params.pp @@ -0,0 +1,175 @@ +# PRIVATE CLASS: do not use directly +class postgresql::params inherits postgresql::globals { + $ensure = true + $version = $globals_version + $listen_addresses = 'localhost' + $ip_mask_deny_postgres_user = '0.0.0.0/0' + $ip_mask_allow_all_users = '127.0.0.1/32' + $ipv4acls = [] + $ipv6acls = [] + $user = pick($user, 'postgres') + $group = pick($group, 'postgres') + $encoding = $encoding + $locale = $locale + $service_provider = $service_provider + $manage_firewall = $manage_firewall + $manage_pg_hba_conf = pick($manage_pg_hba_conf, true) + + # Amazon Linux's OS Family is 'Linux', operating system 'Amazon'. + case $::osfamily { + 'RedHat', 'Linux': { + $needs_initdb = pick($needs_initdb, true) + $firewall_supported = pick($firewall_supported, true) + + if $version == $default_version { + $client_package_name = pick($client_package_name, 'postgresql') + $server_package_name = pick($server_package_name, 'postgresql-server') + $contrib_package_name = pick($contrib_package_name,'postgresql-contrib') + $devel_package_name = pick($devel_package_name, 'postgresql-devel') + $java_package_name = pick($java_package_name, 'postgresql-jdbc') + $plperl_package_name = pick($plperl_package_name, 'postgresql-plperl') + $service_name = pick($service_name, 'postgresql') + $bindir = pick($bindir, '/usr/bin') + $datadir = $::operatingsystem ? { + 'Amazon' => pick($datadir, '/var/lib/pgsql9/data'), + default => pick($datadir, '/var/lib/pgsql/data'), + } + $confdir = pick($confdir, $datadir) + } else { + $version_parts = split($version, '[.]') + $package_version = "${version_parts[0]}${version_parts[1]}" + $client_package_name = pick($client_package_name, "postgresql${package_version}") + $server_package_name = pick($server_package_name, "postgresql${package_version}-server") + $contrib_package_name = pick($contrib_package_name,"postgresql${package_version}-contrib") + $devel_package_name = pick($devel_package_name, "postgresql${package_version}-devel") + $java_package_name = pick($java_package_name, "postgresql${package_version}-jdbc") + $plperl_package_name = pick($plperl_package_name, "postgresql${package_version}-plperl") + $service_name = pick($service_name, "postgresql-${version}") + $bindir = pick($bindir, "/usr/pgsql-${version}/bin") + $datadir = $::operatingsystem ? { + 'Amazon' => pick($datadir, "/var/lib/pgsql9/${version}/data"), + default => pick($datadir, "/var/lib/pgsql/${version}/data"), + } + $confdir = pick($confdir, $datadir) + } + $psql_path = pick($psql_path, "${bindir}/psql") + + $service_status = $service_status + $python_package_name = pick($python_package_name, 'python-psycopg2') + } + + 'Archlinux': { + # Based on the existing version of the firewall module, this is normally + # true for Archlinux, but archlinux users want more control. + # so they can set it themself + $firewall_supported = pick($firewall_supported, true) + $needs_initdb = pick($needs_initdb, true) + + # Archlinux doesn't have a client-package but has a libs package which + # pulls in postgresql server + $client_package_name = pick($client_package_name, 'postgresql') + $server_package_name = pick($server_package_name, 'postgresql-libs') + $java_package_name = pick($java_package_name, 'postgresql-jdbc') + # Archlinux doesn't have develop packages + $devel_package_name = pick($devel_package_name, 'postgresql-devel') + # Archlinux does have postgresql-contrib but it isn't maintained + $contrib_package_name = pick($contrib_package_name,'undef') + # Archlinux postgresql package provides plperl + $plperl_package_name = pick($plperl_package_name, 'undef') + $service_name = pick($service_name, 'postgresql') + $bindir = pick($bindir, '/usr/bin') + $datadir = pick($datadir, '/var/lib/postgres/data') + $confdir = pick($confdir, $datadir) + $psql_path = pick($psql_path, "${bindir}/psql") + + $service_status = $service_status + $python_package_name = pick($python_package_name, 'python-psycopg2') + } + + 'Debian': { + + if $manage_package_repo == true { + $needs_initdb = pick($needs_initdb, true) + $service_name = pick($service_name, 'postgresql') + } else { + $needs_initdb = pick($needs_initdb, false) + $service_name = $::operatingsystem ? { + 'Debian' => pick($service_name, 'postgresql'), + 'Ubuntu' => $::lsbmajdistrelease ? { + '10' => pick($service_name, "postgresql-${version}"), + default => pick($service_name, 'postgresql'), + }, + default => undef + } + } + + $client_package_name = pick($client_package_name, "postgresql-client-${version}") + $server_package_name = pick($server_package_name, "postgresql-${version}") + $contrib_package_name = pick($contrib_package_name, "postgresql-contrib-${version}") + $devel_package_name = pick($devel_package_name, 'libpq-dev') + $java_package_name = pick($java_package_name, 'libpostgresql-jdbc-java') + $plperl_package_name = pick($plperl_package_name, "postgresql-plperl-${version}") + $python_package_name = pick($python_package_name, 'python-psycopg2') + + $bindir = pick($bindir, "/usr/lib/postgresql/${version}/bin") + $datadir = pick($datadir, "/var/lib/postgresql/${version}/main") + $confdir = pick($confdir, "/etc/postgresql/${version}/main") + $service_status = pick($service_status, "/etc/init.d/${service_name} status | /bin/egrep -q 'Running clusters: .+|online'") + $psql_path = pick($psql_path, "/usr/bin/psql") + + $firewall_supported = pick($firewall_supported, true) + } + + 'FreeBSD': { + + $client_package_name = pick($client_package_name, "databases/postgresql${version}-client") + $server_package_name = pick($server_package_name, "databases/postgresql${version}-server") + $contrib_package_name = pick($contrib_package_name, "databases/postgresql${version}-contrib") + $devel_package_name = pick($devel_package_name, 'databases/postgresql-libpqxx3') + $java_package_name = pick($java_package_name, 'databases/postgresql-jdbc') + $plperl_package_name = pick($plperl_package_name, "databases/postgresql${version}-plperl") + $python_package_name = pick($python_package_name, 'databases/py-psycopg2') + + $service_name = pick($service_name, 'postgresql') + $bindir = pick($bindir, '/usr/local/bin') + $datadir = pick($datadir, '/usr/local/pgsql/data') + $confdir = pick($confdir, '/usr/local/share/postgresql') + $service_status = pick($service_status, "/usr/local/etc/rc.d/${service_name} status") + $psql_path = pick($psql_path, "${bindir}/psql") + + $firewall_supported = pick($firewall_supported, false) + $needs_initdb = pick($needs_initdb, true) + } + + default: { + # Based on the existing version of the firewall module, this is normally + # false for other OS, but this allows an escape hatch to override it. + $firewall_supported = pick($firewall_supported, false) + + $psql_path = pick($psql_path, "${bindir}/psql") + + # Since we can't determine defaults on our own, we rely on users setting + # parameters with the postgresql::globals class. Here we are checking + # that the mandatory minimum is set for the module to operate. + $err_prefix = "Module ${module_name} does not provide defaults for osfamily: ${::osfamily} operatingsystem: ${::operatingsystem}; please specify a value for ${module_name}::globals::" + if ($needs_initdb == undef) { fail("${err_prefix}needs_initdb") } + if ($service_name == undef) { fail("${err_prefix}service_name") } + if ($client_package_name == undef) { fail("${err_prefix}client_package_name") } + if ($server_package_name == undef) { fail("${err_prefix}server_package_name") } + if ($bindir == undef) { fail("${err_prefix}bindir") } + if ($datadir == undef) { fail("${err_prefix}datadir") } + if ($confdir == undef) { fail("${err_prefix}confdir") } + } + } + + $initdb_path = pick($initdb_path, "${bindir}/initdb") + $createdb_path = pick($createdb_path, "${bindir}/createdb") + $pg_hba_conf_path = pick($pg_hba_conf_path, "${confdir}/pg_hba.conf") + $pg_hba_conf_defaults = pick($pg_hba_conf_defaults, true) + $postgresql_conf_path = pick($postgresql_conf_path, "${confdir}/postgresql.conf") + $default_database = pick($default_database, 'postgres') + + if($version == 'unknown') { + fail('No preferred version defined or automatically detected.') + } +} diff --git a/modules/postgresql/manifests/repo.pp b/modules/postgresql/manifests/repo.pp new file mode 100644 index 0000000..2e2cbd3 --- /dev/null +++ b/modules/postgresql/manifests/repo.pp @@ -0,0 +1,22 @@ +# PRIVATE CLASS: do not use directly +class postgresql::repo ( + $ensure = $postgresql::params::ensure, + $version = undef +) inherits postgresql::params { + case $::osfamily { + 'RedHat', 'Linux': { + if $version == undef { + fail("The parameter 'version' for 'postgresql::repo' is undefined. You must always define it when osfamily == Redhat or Linux") + } + class { 'postgresql::repo::yum_postgresql_org': } + } + + 'Debian': { + class { 'postgresql::repo::apt_postgresql_org': } + } + + default: { + fail("Unsupported managed repository for osfamily: ${::osfamily}, operatingsystem: ${::operatingsystem}, module ${module_name} currently only supports managing repos for osfamily RedHat and Debian") + } + } +} diff --git a/modules/postgresql/manifests/repo/apt_postgresql_org.pp b/modules/postgresql/manifests/repo/apt_postgresql_org.pp new file mode 100644 index 0000000..610eb47 --- /dev/null +++ b/modules/postgresql/manifests/repo/apt_postgresql_org.pp @@ -0,0 +1,30 @@ +# PRIVATE CLASS: do not use directly +class postgresql::repo::apt_postgresql_org inherits postgresql::repo { + if($ensure == 'present' or $ensure == true) { + # Here we have tried to replicate the instructions on the PostgreSQL site: + # + # http://www.postgresql.org/download/linux/debian/ + # + apt::pin { 'apt.postgresql.org': + originator => 'apt.postgresql.org', + priority => 500, + }-> + apt::source { 'apt.postgresql.org': + location => 'http://apt.postgresql.org/pub/repos/apt/', + release => "${::lsbdistcodename}-pgdg", + repos => "main ${version}", + key => 'ACCC4CF8', + key_source => 'http://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc', + include_src => false, + } + + Apt::Source['apt.postgresql.org']->Package<|tag == 'postgresql'|> + } else { + apt::source { 'apt.postgresql.org': + ensure => absent, + } + apt::pin { 'apt.postgresql.org': + ensure => absent, + } + } +} diff --git a/modules/postgresql/manifests/repo/yum_postgresql_org.pp b/modules/postgresql/manifests/repo/yum_postgresql_org.pp new file mode 100644 index 0000000..9cdfd4a --- /dev/null +++ b/modules/postgresql/manifests/repo/yum_postgresql_org.pp @@ -0,0 +1,38 @@ +# PRIVATE CLASS: do not use directly +class postgresql::repo::yum_postgresql_org inherits postgresql::repo { + $version_parts = split($version, '[.]') + $package_version = "${version_parts[0]}${version_parts[1]}" + $gpg_key_path = "/etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-${package_version}" + + if ($ensure == 'present' or $ensure == true) { + file { $gpg_key_path: + source => 'puppet:///modules/postgresql/RPM-GPG-KEY-PGDG', + before => Yumrepo['yum.postgresql.org'] + } + + if($::operatingsystem == 'Fedora') { + $label1 = 'fedora' + $label2 = $label1 + } else { + $label1 = 'redhat' + $label2 = 'rhel' + } + + yumrepo { 'yum.postgresql.org': + descr => "PostgreSQL ${version} \$releasever - \$basearch", + baseurl => "http://yum.postgresql.org/${version}/${label1}/${label2}-\$releasever-\$basearch", + enabled => 1, + gpgcheck => 1, + gpgkey => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-PGDG-${package_version}", + } + + Yumrepo['yum.postgresql.org'] -> Package<|tag == 'postgresql'|> + } else { + yumrepo { 'yum.postgresql.org': + enabled => absent, + }-> + file { $gpg_key_path: + ensure => absent, + } + } +} diff --git a/modules/postgresql/manifests/server.pp b/modules/postgresql/manifests/server.pp new file mode 100644 index 0000000..4d5baab --- /dev/null +++ b/modules/postgresql/manifests/server.pp @@ -0,0 +1,73 @@ +# This installs a PostgreSQL server. See README.md for more details. +class postgresql::server ( + $ensure = $postgresql::params::ensure, + + $version = $postgresql::params::version, + + $postgres_password = undef, + + $package_name = $postgresql::params::server_package_name, + $client_package_name = $postgresql::params::client_package_name, + $package_ensure = $ensure, + + $plperl_package_name = $postgresql::params::plperl_package_name, + + $service_name = $postgresql::params::service_name, + $service_provider = $postgresql::params::service_provider, + $service_status = $postgresql::params::service_status, + $default_database = $postgresql::params::default_database, + + $listen_addresses = $postgresql::params::listen_addresses, + $ip_mask_deny_postgres_user = $postgresql::params::ip_mask_deny_postgres_user, + $ip_mask_allow_all_users = $postgresql::params::ip_mask_allow_all_users, + $ipv4acls = $postgresql::params::ipv4acls, + $ipv6acls = $postgresql::params::ipv6acls, + + $initdb_path = $postgresql::params::initdb_path, + $createdb_path = $postgresql::params::createdb_path, + $psql_path = $postgresql::params::psql_path, + $pg_hba_conf_path = $postgresql::params::pg_hba_conf_path, + $postgresql_conf_path = $postgresql::params::postgresql_conf_path, + + $datadir = $postgresql::params::datadir, + $xlogdir = $postgresql::params::xlogdir, + + $pg_hba_conf_defaults = $postgresql::params::pg_hba_conf_defaults, + + $user = $postgresql::params::user, + $group = $postgresql::params::group, + + $needs_initdb = $postgresql::params::needs_initdb, + + $encoding = $postgresql::params::encoding, + $locale = $postgresql::params::locale, + + $manage_firewall = $postgresql::params::manage_firewall, + $manage_pg_hba_conf = $postgresql::params::manage_pg_hba_conf, + $firewall_supported = $postgresql::params::firewall_supported +) inherits postgresql::params { + $pg = 'postgresql::server' + + if ($ensure == 'present' or $ensure == true) { + # Reload has its own ordering, specified by other defines + class { "${pg}::reload": require => Class["${pg}::install"] } + + anchor { "${pg}::start": }-> + class { "${pg}::install": }-> + class { "${pg}::initdb": }-> + class { "${pg}::config": }-> + class { "${pg}::service": }-> + class { "${pg}::passwd": }-> + class { "${pg}::firewall": }-> + anchor { "${pg}::end": } + } else { + anchor { "${pg}::start": }-> + class { "${pg}::firewall": }-> + class { "${pg}::passwd": }-> + class { "${pg}::service": }-> + class { "${pg}::install": }-> + class { "${pg}::initdb": }-> + class { "${pg}::config": }-> + anchor { "${pg}::end": } + } +} diff --git a/modules/postgresql/manifests/server/config.pp b/modules/postgresql/manifests/server/config.pp new file mode 100644 index 0000000..a59f179 --- /dev/null +++ b/modules/postgresql/manifests/server/config.pp @@ -0,0 +1,108 @@ +# PRIVATE CLASS: do not call directly +class postgresql::server::config { + $ensure = $postgresql::server::ensure + $ip_mask_deny_postgres_user = $postgresql::server::ip_mask_deny_postgres_user + $ip_mask_allow_all_users = $postgresql::server::ip_mask_allow_all_users + $listen_addresses = $postgresql::server::listen_addresses + $ipv4acls = $postgresql::server::ipv4acls + $ipv6acls = $postgresql::server::ipv6acls + $pg_hba_conf_path = $postgresql::server::pg_hba_conf_path + $postgresql_conf_path = $postgresql::server::postgresql_conf_path + $pg_hba_conf_defaults = $postgresql::server::pg_hba_conf_defaults + $user = $postgresql::server::user + $group = $postgresql::server::group + $version = $postgresql::server::version + $manage_pg_hba_conf = $postgresql::server::manage_pg_hba_conf + + if ($ensure == 'present' or $ensure == true) { + + if ($manage_pg_hba_conf == true) { + # Prepare the main pg_hba file + concat { $pg_hba_conf_path: + owner => 0, + group => $group, + mode => '0640', + warn => true, + notify => Class['postgresql::server::reload'], + } + + if $pg_hba_conf_defaults { + Postgresql::Server::Pg_hba_rule { + database => 'all', + user => 'all', + } + + # Lets setup the base rules + $local_auth_option = $version ? { + '8.1' => 'sameuser', + default => undef, + } + postgresql::server::pg_hba_rule { 'local access as postgres user': + type => 'local', + user => $user, + auth_method => 'ident', + auth_option => $local_auth_option, + order => '001', + } + postgresql::server::pg_hba_rule { 'local access to database with same name': + type => 'local', + auth_method => 'ident', + auth_option => $local_auth_option, + order => '002', + } + postgresql::server::pg_hba_rule { 'allow localhost TCP access to postgresql user': + type => 'host', + user => $user, + address => '127.0.0.1/32', + auth_method => 'md5', + order => '003', + } + postgresql::server::pg_hba_rule { 'deny access to postgresql user': + type => 'host', + user => $user, + address => $ip_mask_deny_postgres_user, + auth_method => 'reject', + order => '004', + } + + # ipv4acls are passed as an array of rule strings, here we transform + # them into a resources hash, and pass the result to create_resources + $ipv4acl_resources = postgresql_acls_to_resources_hash($ipv4acls, + 'ipv4acls', 10) + create_resources('postgresql::server::pg_hba_rule', $ipv4acl_resources) + + postgresql::server::pg_hba_rule { 'allow access to all users': + type => 'host', + address => $ip_mask_allow_all_users, + auth_method => 'md5', + order => '100', + } + postgresql::server::pg_hba_rule { 'allow access to ipv6 localhost': + type => 'host', + address => '::1/128', + auth_method => 'md5', + order => '101', + } + + # ipv6acls are passed as an array of rule strings, here we transform + # them into a resources hash, and pass the result to create_resources + $ipv6acl_resources = postgresql_acls_to_resources_hash($ipv6acls, + 'ipv6acls', 102) + create_resources('postgresql::server::pg_hba_rule', $ipv6acl_resources) + } + } + + # We must set a "listen_addresses" line in the postgresql.conf if we + # want to allow any connections from remote hosts. + postgresql::server::config_entry { 'listen_addresses': + value => $listen_addresses, + } + } else { + file { $pg_hba_conf_path: + ensure => absent, + } + file { $postgresql_conf_path: + ensure => absent, + } + } +} diff --git a/modules/postgresql/manifests/server/config_entry.pp b/modules/postgresql/manifests/server/config_entry.pp new file mode 100644 index 0000000..c6cd1a7 --- /dev/null +++ b/modules/postgresql/manifests/server/config_entry.pp @@ -0,0 +1,43 @@ +# Manage a postgresql.conf entry. See README.md for more details. +define postgresql::server::config_entry ( + $ensure = 'present', + $value = undef, + $path = false +) { + $postgresql_conf_path = $postgresql::server::postgresql_conf_path + + $target = $path ? { + false => $postgresql_conf_path, + default => $path, + } + + case $name { + /data_directory|hba_file|ident_file|include|listen_addresses|port|max_connections|superuser_reserved_connections|unix_socket_directory|unix_socket_group|unix_socket_permissions|bonjour|bonjour_name|ssl|ssl_ciphers|shared_buffers|max_prepared_transactions|max_files_per_process|shared_preload_libraries|wal_level|wal_buffers|archive_mode|max_wal_senders|hot_standby|logging_collector|silent_mode|track_activity_query_size|autovacuum_max_workers|autovacuum_freeze_max_age|max_locks_per_transaction|max_pred_locks_per_transaction|restart_after_crash|lc_messages|lc_monetary|lc_numeric|lc_time/: { + Postgresql_conf { + notify => Class['postgresql::server::service'], + before => Class['postgresql::server::reload'], + } + } + + default: { + Postgresql_conf { + notify => Class['postgresql::server::reload'], + } + } + } + + case $ensure { + /present|absent/: { + postgresql_conf { $name: + ensure => $ensure, + target => $target, + value => $value, + require => Class['postgresql::server::initdb'], + } + } + + default: { + fail("Unknown value for ensure '${ensure}'.") + } + } +} diff --git a/modules/postgresql/manifests/server/contrib.pp b/modules/postgresql/manifests/server/contrib.pp new file mode 100644 index 0000000..fe6309e --- /dev/null +++ b/modules/postgresql/manifests/server/contrib.pp @@ -0,0 +1,27 @@ +# Install the contrib postgresql packaging. See README.md for more details. +class postgresql::server::contrib ( + $package_name = $postgresql::params::contrib_package_name, + $package_ensure = 'present' +) inherits postgresql::params { + validate_string($package_name) + + package { 'postgresql-contrib': + ensure => $package_ensure, + name => $package_name, + tag => 'postgresql', + } + + if($package_ensure == 'present' or $package_ensure == true) { + anchor { 'postgresql::server::contrib::start': }-> + Class['postgresql::server::install']-> + Package['postgresql-contrib']-> + Class['postgresql::server::service']-> + anchor { 'postgresql::server::contrib::end': } + } else { + anchor { 'postgresql::server::contrib::start': }-> + Class['postgresql::server::service']-> + Package['postgresql-contrib']-> + Class['postgresql::server::install']-> + anchor { 'postgresql::server::contrib::end': } + } +} diff --git a/modules/postgresql/manifests/server/database.pp b/modules/postgresql/manifests/server/database.pp new file mode 100644 index 0000000..adeabde --- /dev/null +++ b/modules/postgresql/manifests/server/database.pp @@ -0,0 +1,76 @@ +# Define for creating a database. See README.md for more details. +define postgresql::server::database( + $dbname = $title, + $owner = $postgresql::server::user, + $tablespace = undef, + $template = 'template0', + $encoding = $postgresql::server::encoding, + $locale = $postgresql::server::locale, + $istemplate = false +) { + $createdb_path = $postgresql::server::createdb_path + $user = $postgresql::server::user + $group = $postgresql::server::group + $psql_path = $postgresql::server::psql_path + $version = $postgresql::server::version + + # Set the defaults for the postgresql_psql resource + Postgresql_psql { + psql_user => $user, + psql_group => $group, + psql_path => $psql_path, + } + + # Optionally set the locale switch. Older versions of createdb may not accept + # --locale, so if the parameter is undefined its safer not to pass it. + if ($version != '8.1') { + $locale_option = $locale ? { + undef => '', + default => "--locale=${locale} ", + } + $public_revoke_privilege = 'CONNECT' + } else { + $locale_option = '' + $public_revoke_privilege = 'ALL' + } + + $encoding_option = $encoding ? { + undef => '', + default => "--encoding '${encoding}' ", + } + + $tablespace_option = $tablespace ? { + undef => '', + default => "--tablespace='${tablespace}' ", + } + + $createdb_command = "${createdb_path} --owner='${owner}' --template=${template} ${encoding_option}${locale_option}${tablespace_option} '${dbname}'" + + postgresql_psql { "Check for existence of db '${dbname}'": + command => 'SELECT 1', + unless => "SELECT datname FROM pg_database WHERE datname='${dbname}'", + require => Class['postgresql::server::service'] + }~> + exec { $createdb_command : + refreshonly => true, + user => $user, + logoutput => on_failure, + }~> + + # This will prevent users from connecting to the database unless they've been + # granted privileges. + postgresql_psql {"REVOKE ${public_revoke_privilege} ON DATABASE \"${dbname}\" FROM public": + db => $user, + refreshonly => true, + } + + Exec [ $createdb_command ]-> + postgresql_psql {"UPDATE pg_database SET datistemplate = ${istemplate} WHERE datname = '${dbname}'": + unless => "SELECT datname FROM pg_database WHERE datname = '${dbname}' AND datistemplate = ${istemplate}", + } + + # Build up dependencies on tablespace + if($tablespace != undef and defined(Postgresql::Server::Tablespace[$tablespace])) { + Postgresql::Server::Tablespace[$tablespace]->Exec[$createdb_command] + } +} diff --git a/modules/postgresql/manifests/server/database_grant.pp b/modules/postgresql/manifests/server/database_grant.pp new file mode 100644 index 0000000..5973144 --- /dev/null +++ b/modules/postgresql/manifests/server/database_grant.pp @@ -0,0 +1,18 @@ +# Manage a database grant. See README.md for more details. +define postgresql::server::database_grant( + $privilege, + $db, + $role, + $psql_db = undef, + $psql_user = undef +) { + postgresql::server::grant { "database:${name}": + role => $role, + db => $db, + privilege => $privilege, + object_type => 'DATABASE', + object_name => $db, + psql_db => $psql_db, + psql_user => $psql_user, + } +} diff --git a/modules/postgresql/manifests/server/db.pp b/modules/postgresql/manifests/server/db.pp new file mode 100644 index 0000000..5cc7954 --- /dev/null +++ b/modules/postgresql/manifests/server/db.pp @@ -0,0 +1,38 @@ +# Define for conveniently creating a role, database and assigning the correct +# permissions. See README.md for more details. +define postgresql::server::db ( + $user, + $password, + $encoding = $postgresql::server::encoding, + $locale = $postgresql::server::locale, + $grant = 'ALL', + $tablespace = undef, + $template = 'template0', + $istemplate = false, + $owner = undef +) { + postgresql::server::database { $name: + encoding => $encoding, + tablespace => $tablespace, + template => $template, + locale => $locale, + istemplate => $istemplate, + owner => $owner, + } + + if ! defined(Postgresql::Server::Role[$user]) { + postgresql::server::role { $user: + password_hash => $password, + } + } + + postgresql::server::database_grant { "GRANT ${user} - ${grant} - ${name}": + privilege => $grant, + db => $name, + role => $user, + } + + if($tablespace != undef and defined(Postgresql::Server::Tablespace[$tablespace])) { + Postgresql::Server::Tablespace[$tablespace]->Postgresql::Server::Database[$name] + } +} diff --git a/modules/postgresql/manifests/server/firewall.pp b/modules/postgresql/manifests/server/firewall.pp new file mode 100644 index 0000000..afe3797 --- /dev/null +++ b/modules/postgresql/manifests/server/firewall.pp @@ -0,0 +1,21 @@ +# PRIVATE CLASS: do not use directly +class postgresql::server::firewall { + $ensure = $postgresql::server::ensure + $manage_firewall = $postgresql::server::manage_firewall + $firewall_supported = $postgresql::server::firewall_supported + + if ($manage_firewall and $firewall_supported) { + if ($ensure == 'present' or $ensure == true) { + # TODO: get rid of hard-coded port + firewall { '5432 accept - postgres': + port => '5432', + proto => 'tcp', + action => 'accept', + } + } else { + firewall { '5432 accept - postgres': + ensure => absent, + } + } + } +} diff --git a/modules/postgresql/manifests/server/grant.pp b/modules/postgresql/manifests/server/grant.pp new file mode 100644 index 0000000..d24130c --- /dev/null +++ b/modules/postgresql/manifests/server/grant.pp @@ -0,0 +1,85 @@ +# Define for granting permissions to roles. See README.md for more details. +define postgresql::server::grant ( + $role, + $db, + $privilege = undef, + $object_type = 'database', + $object_name = $db, + $psql_db = $postgresql::server::user, + $psql_user = $postgresql::server::user +) { + $group = $postgresql::server::group + $psql_path = $postgresql::server::psql_path + + ## Munge the input values + $_object_type = upcase($object_type) + $_privilege = upcase($privilege) + + ## Validate that the object type is known + validate_string($_object_type, + #'COLUMN', + 'DATABASE', + #'FOREIGN SERVER', + #'FOREIGN DATA WRAPPER', + #'FUNCTION', + #'PROCEDURAL LANGUAGE', + #'SCHEMA', + #'SEQUENCE', + 'TABLE', + #'TABLESPACE', + #'VIEW', + ) + + ## Validate that the object type's privilege is acceptable + # TODO: this is a terrible hack; if they pass "ALL" as the desired privilege, + # we need a way to test for it--and has_database_privilege does not + # recognize 'ALL' as a valid privilege name. So we probably need to + # hard-code a mapping between 'ALL' and the list of actual privileges that + # it entails, and loop over them to check them. That sort of thing will + # probably need to wait until we port this over to ruby, so, for now, we're + # just going to assume that if they have "CREATE" privileges on a database, + # then they have "ALL". (I told you that it was terrible!) + case $_object_type { + 'DATABASE': { + $unless_privilege = $_privilege ? { + 'ALL' => 'CREATE', + default => $_privilege, + } + validate_string($unless_privilege,'CREATE','CONNECT','TEMPORARY','TEMP', + 'ALL','ALL PRIVILEGES') + $unless_function = 'has_database_privilege' + $on_db = $psql_db + } + 'TABLE': { + $unless_privilege = $_privilege ? { + 'ALL' => 'INSERT', + default => $_privilege, + } + validate_string($unless_privilege,'SELECT','INSERT','UPDATE','DELETE', + 'TRUNCATE','REFERENCES','TRIGGER','ALL','ALL PRIVILEGES') + $unless_function = 'has_table_privilege' + $on_db = $db + } + default: { + fail("Missing privilege validation for object type ${_object_type}") + } + } + + $grant_cmd = "GRANT ${_privilege} ON ${_object_type} \"${object_name}\" TO \"${role}\"" + postgresql_psql { $grant_cmd: + db => $on_db, + psql_user => $psql_user, + psql_group => $group, + psql_path => $psql_path, + unless => "SELECT 1 WHERE ${unless_function}('${role}', '${object_name}', '${unless_privilege}')", + require => Class['postgresql::server'] + } + + if($role != undef and defined(Postgresql::Server::Role[$role])) { + Postgresql::Server::Role[$role]->Postgresql_psql[$grant_cmd] + } + + if($db != undef and defined(Postgresql::Server::Database[$db])) { + Postgresql::Server::Database[$db]->Postgresql_psql[$grant_cmd] + } +} diff --git a/modules/postgresql/manifests/server/initdb.pp b/modules/postgresql/manifests/server/initdb.pp new file mode 100644 index 0000000..a56f19c --- /dev/null +++ b/modules/postgresql/manifests/server/initdb.pp @@ -0,0 +1,76 @@ +# PRIVATE CLASS: do not call directly +class postgresql::server::initdb { + $ensure = $postgresql::server::ensure + $needs_initdb = $postgresql::server::needs_initdb + $initdb_path = $postgresql::server::initdb_path + $datadir = $postgresql::server::datadir + $xlogdir = $postgresql::server::xlogdir + $encoding = $postgresql::server::encoding + $locale = $postgresql::server::locale + $group = $postgresql::server::group + $user = $postgresql::server::user + + if($ensure == 'present' or $ensure == true) { + # Make sure the data directory exists, and has the correct permissions. + file { $datadir: + ensure => directory, + owner => $user, + group => $group, + mode => '0700', + } + + if($xlogdir) { + # Make sure the xlog directory exists, and has the correct permissions. + file { $xlogdir: + ensure => directory, + owner => $user, + group => $group, + mode => '0700', + } + } + + if($needs_initdb) { + # Build up the initdb command. + # + # We optionally add the locale switch if specified. Older versions of the + # initdb command don't accept this switch. So if the user didn't pass the + # parameter, lets not pass the switch at all. + $ic_base = "${initdb_path} --encoding '${encoding}' --pgdata '${datadir}'" + $ic_xlog = $xlogdir ? { + undef => $ic_base, + default => "${ic_base} --xlogdir '${xlogdir}'" + } + $initdb_command = $locale ? { + undef => $ic_xlog, + default => "${ic_xlog} --locale '${locale}'" + } + + # This runs the initdb command, we use the existance of the PG_VERSION + # file to ensure we don't keep running this command. + exec { 'postgresql_initdb': + command => $initdb_command, + creates => "${datadir}/PG_VERSION", + user => $user, + group => $group, + logoutput => on_failure, + require => File[$datadir], + } + } + } else { + # Purge data directory if ensure => absent + file { $datadir: + ensure => absent, + recurse => true, + force => true, + } + + if($xlogdir) { + # Make sure the xlog directory exists, and has the correct permissions. + file { $xlogdir: + ensure => absent, + recurse => true, + force => true, + } + } + } +} diff --git a/modules/postgresql/manifests/server/install.pp b/modules/postgresql/manifests/server/install.pp new file mode 100644 index 0000000..1e912a8 --- /dev/null +++ b/modules/postgresql/manifests/server/install.pp @@ -0,0 +1,49 @@ +# PRIVATE CLASS: do not call directly +class postgresql::server::install { + $package_ensure = $postgresql::server::package_ensure + $package_name = $postgresql::server::package_name + $client_package_name = $postgresql::server::client_package_name + + # This is necessary to ensure that the extra client package that was + # installed automatically by the server package is removed and all + # of its dependencies are removed also. Without this later installation + # of the native Ubuntu packages will fail. + if($::operatingsystem == 'Ubuntu' and $package_ensure == 'absent') { + # This is an exec, because we want to invoke autoremove. + # + # An alternative would be to have a full list of packages, but that seemed + # more problematic to maintain, not to mention the conflict with the + # client class will create duplicate resources. + exec { 'apt-get-autoremove-postgresql-client-XX': + command => "apt-get autoremove --purge --yes ${client_package_name}", + onlyif => "dpkg -l ${client_package_name} | grep -e '^ii'", + logoutput => on_failure, + path => '/usr/bin:/bin:/usr/sbin/:/sbin', + } + + # This will clean up anything we miss + exec { 'apt-get-autoremove-postgresql-client-brute': + command => "dpkg -P postgresql*", + onlyif => "dpkg -l postgresql* | grep -e '^ii'", + logoutput => on_failure, + path => '/usr/bin:/bin:/usr/sbin/:/sbin', + } + } + + $_package_ensure = $package_ensure ? { + true => 'present', + false => 'purged', + 'absent' => 'purged', + default => $package_ensure, + } + + package { 'postgresql-server': + ensure => $_package_ensure, + name => $package_name, + + # This is searched for to create relationships with the package repos, be + # careful about its removal + tag => 'postgresql', + } + +} diff --git a/modules/postgresql/manifests/server/passwd.pp b/modules/postgresql/manifests/server/passwd.pp new file mode 100644 index 0000000..5777b03 --- /dev/null +++ b/modules/postgresql/manifests/server/passwd.pp @@ -0,0 +1,35 @@ +# PRIVATE CLASS: do not call directly +class postgresql::server::passwd { + $ensure = $postgresql::server::ensure + $postgres_password = $postgresql::server::postgres_password + $user = $postgresql::server::user + $group = $postgresql::server::group + $psql_path = $postgresql::server::psql_path + + if($ensure == 'present' or $ensure == true) { + if ($postgres_password != undef) { + # NOTE: this password-setting logic relies on the pg_hba.conf being + # configured to allow the postgres system user to connect via psql + # without specifying a password ('ident' or 'trust' security). This is + # the default for pg_hba.conf. + $escaped = postgresql_escape($postgres_password) + $env = "env PGPASSWORD='${postgres_password}'" + exec { 'set_postgres_postgrespw': + # This command works w/no password because we run it as postgres system + # user + command => "${psql_path} -c 'ALTER ROLE \"${user}\" PASSWORD ${escaped}'", + user => $user, + group => $group, + logoutput => true, + cwd => '/tmp', + # With this command we're passing -h to force TCP authentication, which + # does require a password. We specify the password via the PGPASSWORD + # environment variable. If the password is correct (current), this + # command will exit with an exit code of 0, which will prevent the main + # command from running. + unless => "${env} ${psql_path} -h localhost -c 'select 1' > /dev/null", + path => '/usr/bin:/usr/local/bin:/bin', + } + } + } +} diff --git a/modules/postgresql/manifests/server/pg_hba_rule.pp b/modules/postgresql/manifests/server/pg_hba_rule.pp new file mode 100644 index 0000000..ea300d1 --- /dev/null +++ b/modules/postgresql/manifests/server/pg_hba_rule.pp @@ -0,0 +1,52 @@ +# This resource manages an individual rule that applies to the file defined in +# $target. See README.md for more details. +define postgresql::server::pg_hba_rule( + $type, + $database, + $user, + $auth_method, + $address = undef, + $description = 'none', + $auth_option = undef, + $order = '150', + + # Needed for testing primarily, support for multiple files is not really + # working. + $target = $postgresql::server::pg_hba_conf_path +) { + + if $postgresql::server::manage_pg_hba_conf == false { + fail('postgresql::server::manage_pg_hba_conf has been disabled, so this resource is now unused and redundant, either enable that option or remove this resource from your manifests') + } else { + validate_re($type, '^(local|host|hostssl|hostnossl)$', + "The type you specified [${type}] must be one of: local, host, hostssl, hostnosssl") + + if($type =~ /^host/ and $address == undef) { + fail('You must specify an address property when type is host based') + } + + $allowed_auth_methods = $postgresql::server::version ? { + '9.3' => ['trust', 'reject', 'md5', 'sha1', 'password', 'gss', 'sspi', 'krb5', 'ident', 'peer', 'ldap', 'radius', 'cert', 'pam'], + '9.2' => ['trust', 'reject', 'md5', 'sha1', 'password', 'gss', 'sspi', 'krb5', 'ident', 'peer', 'ldap', 'radius', 'cert', 'pam'], + '9.1' => ['trust', 'reject', 'md5', 'sha1', 'password', 'gss', 'sspi', 'krb5', 'ident', 'peer', 'ldap', 'radius', 'cert', 'pam'], + '9.0' => ['trust', 'reject', 'md5', 'sha1', 'password', 'gss', 'sspi', 'krb5', 'ident', 'ldap', 'radius', 'cert', 'pam'], + '8.4' => ['trust', 'reject', 'md5', 'sha1', 'password', 'gss', 'sspi', 'krb5', 'ident', 'ldap', 'cert', 'pam'], + '8.3' => ['trust', 'reject', 'md5', 'sha1', 'crypt', 'password', 'gss', 'sspi', 'krb5', 'ident', 'ldap', 'pam'], + '8.2' => ['trust', 'reject', 'md5', 'crypt', 'password', 'krb5', 'ident', 'ldap', 'pam'], + '8.1' => ['trust', 'reject', 'md5', 'crypt', 'password', 'krb5', 'ident', 'pam'], + default => ['trust', 'reject', 'md5', 'password', 'gss', 'sspi', 'krb5', 'ident', 'peer', 'ldap', 'radius', 'cert', 'pam', 'crypt'] + } + + $auth_method_regex = join(['^(', join($allowed_auth_methods, '|'), ')$'],'') + validate_re($auth_method, $auth_method_regex, + join(["The auth_method you specified [${auth_method}] must be one of: ", join($allowed_auth_methods, ', ')],'')) + + # Create a rule fragment + $fragname = "pg_hba_rule_${name}" + concat::fragment { $fragname: + target => $target, + content => template('postgresql/pg_hba_rule.conf'), + order => $order, + } + } +} diff --git a/modules/postgresql/manifests/server/plperl.pp b/modules/postgresql/manifests/server/plperl.pp new file mode 100644 index 0000000..c338f16 --- /dev/null +++ b/modules/postgresql/manifests/server/plperl.pp @@ -0,0 +1,27 @@ +# This class installs the PL/Perl procedural language for postgresql. See +# README.md for more details. +class postgresql::server::plperl( + $package_ensure = 'present', + $package_name = $postgresql::server::plperl_package_name +) { + package { 'postgresql-plperl': + ensure => $package_ensure, + name => $package_name, + tag => 'postgresql', + } + + if($package_ensure == 'present' or $package_ensure == true) { + anchor { 'postgresql::server::plperl::start': }-> + Class['postgresql::server::install']-> + Package['postgresql-plperl']-> + Class['postgresql::server::service']-> + anchor { 'postgresql::server::plperl::end': } + } else { + anchor { 'postgresql::server::plperl::start': }-> + Class['postgresql::server::service']-> + Package['postgresql-plperl']-> + Class['postgresql::server::install']-> + anchor { 'postgresql::server::plperl::end': } + } + +} diff --git a/modules/postgresql/manifests/server/reload.pp b/modules/postgresql/manifests/server/reload.pp new file mode 100644 index 0000000..6b11ebf --- /dev/null +++ b/modules/postgresql/manifests/server/reload.pp @@ -0,0 +1,15 @@ +# PRIVATE CLASS: do not use directly +class postgresql::server::reload { + $ensure = $postgresql::server::ensure + $service_name = $postgresql::server::service_name + $service_status = $postgresql::server::service_status + + if($ensure == 'present' or $ensure == true) { + exec { 'postgresql_reload': + path => '/usr/bin:/usr/sbin:/bin:/sbin', + command => "service ${service_name} reload", + onlyif => $service_status, + refreshonly => true, + } + } +} diff --git a/modules/postgresql/manifests/server/role.pp b/modules/postgresql/manifests/server/role.pp new file mode 100644 index 0000000..971191f --- /dev/null +++ b/modules/postgresql/manifests/server/role.pp @@ -0,0 +1,85 @@ +# Define for creating a database role. See README.md for more information +define postgresql::server::role( + $password_hash = false, + $createdb = false, + $createrole = false, + $db = $postgresql::server::user, + $login = true, + $superuser = false, + $replication = false, + $connection_limit = '-1', + $username = $title +) { + $psql_user = $postgresql::server::user + $psql_group = $postgresql::server::group + $psql_path = $postgresql::server::psql_path + $version = $postgresql::server::version + + $login_sql = $login ? { true => 'LOGIN', default => 'NOLOGIN' } + $createrole_sql = $createrole ? { true => 'CREATEROLE', default => 'NOCREATEROLE' } + $createdb_sql = $createdb ? { true => 'CREATEDB', default => 'NOCREATEDB' } + $superuser_sql = $superuser ? { true => 'SUPERUSER', default => 'NOSUPERUSER' } + $replication_sql = $replication ? { true => 'REPLICATION', default => '' } + if ($password_hash != false) { + $password_sql = "ENCRYPTED PASSWORD '${password_hash}'" + } else { + $password_sql = '' + } + + Postgresql_psql { + db => $db, + psql_user => $psql_user, + psql_group => $psql_group, + psql_path => $psql_path, + require => [ Postgresql_psql["CREATE ROLE \"${username}\" ${password_sql} ${login_sql} ${createrole_sql} ${createdb_sql} ${superuser_sql} ${replication_sql} CONNECTION LIMIT ${connection_limit}"], Class['postgresql::server'] ], + } + + postgresql_psql {"CREATE ROLE \"${username}\" ${password_sql} ${login_sql} ${createrole_sql} ${createdb_sql} ${superuser_sql} ${replication_sql} CONNECTION LIMIT ${connection_limit}": + unless => "SELECT rolname FROM pg_roles WHERE rolname='${username}'", + require => Class['Postgresql::Server'], + } + + postgresql_psql {"ALTER ROLE \"${username}\" ${superuser_sql}": + unless => "SELECT rolname FROM pg_roles WHERE rolname='${username}' and rolsuper=${superuser}", + } + + postgresql_psql {"ALTER ROLE \"${username}\" ${createdb_sql}": + unless => "SELECT rolname FROM pg_roles WHERE rolname='${username}' and rolcreatedb=${createdb}", + } + + postgresql_psql {"ALTER ROLE \"${username}\" ${createrole_sql}": + unless => "SELECT rolname FROM pg_roles WHERE rolname='${username}' and rolcreaterole=${createrole}", + } + + postgresql_psql {"ALTER ROLE \"${username}\" ${login_sql}": + unless => "SELECT rolname FROM pg_roles WHERE rolname='${username}' and rolcanlogin=${login}", + } + + if(versioncmp($version, '9.1') >= 0) { + if $replication_sql == '' { + postgresql_psql {"ALTER ROLE \"${username}\" NOREPLICATION": + unless => "SELECT rolname FROM pg_roles WHERE rolname='${username}' and rolreplication=${replication}", + } + } else { + postgresql_psql {"ALTER ROLE \"${username}\" ${replication_sql}": + unless => "SELECT rolname FROM pg_roles WHERE rolname='${username}' and rolreplication=${replication}", + } + } + } + + postgresql_psql {"ALTER ROLE \"${username}\" CONNECTION LIMIT ${connection_limit}": + unless => "SELECT rolname FROM pg_roles WHERE rolname='${username}' and rolconnlimit=${connection_limit}", + } + + if $password_hash { + if($password_hash =~ /^md5.+/) { + $pwd_hash_sql = $password_hash + } else { + $pwd_md5 = md5("${password_hash}${username}") + $pwd_hash_sql = "md5${pwd_md5}" + } + postgresql_psql {"ALTER ROLE \"${username}\" ${password_sql}": + unless => "SELECT usename FROM pg_shadow WHERE usename='${username}' and passwd='${pwd_hash_sql}'", + } + } +} diff --git a/modules/postgresql/manifests/server/service.pp b/modules/postgresql/manifests/server/service.pp new file mode 100644 index 0000000..598acd8 --- /dev/null +++ b/modules/postgresql/manifests/server/service.pp @@ -0,0 +1,45 @@ +# PRIVATE CLASS: do not call directly +class postgresql::server::service { + $ensure = $postgresql::server::ensure + $service_name = $postgresql::server::service_name + $service_provider = $postgresql::server::service_provider + $service_status = $postgresql::server::service_status + $user = $postgresql::server::user + $default_database = $postgresql::server::default_database + + $service_ensure = $ensure ? { + present => true, + absent => false, + default => $ensure + } + + anchor { 'postgresql::server::service::begin': } + + service { 'postgresqld': + ensure => $service_ensure, + name => $service_name, + enable => $service_ensure, + provider => $service_provider, + hasstatus => true, + status => $service_status, + } + + if($service_ensure) { + # This blocks the class before continuing if chained correctly, making + # sure the service really is 'up' before continuing. + # + # Without it, we may continue doing more work before the database is + # prepared leading to a nasty race condition. + postgresql::validate_db_connection { 'validate_service_is_running': + run_as => $user, + database_name => $default_database, + sleep => 1, + tries => 60, + create_db_first => false, + require => Service['postgresqld'], + before => Anchor['postgresql::server::service::end'] + } + } + + anchor { 'postgresql::server::service::end': } +} diff --git a/modules/postgresql/manifests/server/table_grant.pp b/modules/postgresql/manifests/server/table_grant.pp new file mode 100644 index 0000000..643416e --- /dev/null +++ b/modules/postgresql/manifests/server/table_grant.pp @@ -0,0 +1,20 @@ +# This resource wraps the grant resource to manage table grants specifically. +# See README.md for more details. +define postgresql::server::table_grant( + $privilege, + $table, + $db, + $role, + $psql_db = undef, + $psql_user = undef +) { + postgresql::server::grant { "table:${name}": + role => $role, + db => $db, + privilege => $privilege, + object_type => 'TABLE', + object_name => $table, + psql_db => $psql_db, + psql_user => $psql_user, + } +} diff --git a/modules/postgresql/manifests/server/tablespace.pp b/modules/postgresql/manifests/server/tablespace.pp new file mode 100644 index 0000000..2252377 --- /dev/null +++ b/modules/postgresql/manifests/server/tablespace.pp @@ -0,0 +1,42 @@ +# This module creates tablespace. See README.md for more details. +define postgresql::server::tablespace( + $location, + $owner = undef, + $spcname = $title +) { + $user = $postgresql::server::user + $group = $postgresql::server::group + $psql_path = $postgresql::server::psql_path + + Postgresql_psql { + psql_user => $user, + psql_group => $group, + psql_path => $psql_path, + } + + if ($owner == undef) { + $owner_section = '' + } else { + $owner_section = "OWNER \"${owner}\"" + } + + $create_tablespace_command = "CREATE TABLESPACE \"${spcname}\" ${owner_section} LOCATION '${location}'" + + file { $location: + ensure => directory, + owner => $user, + group => $group, + mode => '0700', + } + + $create_ts = "Create tablespace '${spcname}'" + postgresql_psql { "Create tablespace '${spcname}'": + command => $create_tablespace_command, + unless => "SELECT spcname FROM pg_tablespace WHERE spcname='${spcname}'", + require => [Class['postgresql::server'], File[$location]], + } + + if($owner != undef and defined(Postgresql::Server::Role[$owner])) { + Postgresql::Server::Role[$owner]->Postgresql_psql[$create_ts] + } +} diff --git a/modules/postgresql/manifests/validate_db_connection.pp b/modules/postgresql/manifests/validate_db_connection.pp new file mode 100644 index 0000000..f70af1e --- /dev/null +++ b/modules/postgresql/manifests/validate_db_connection.pp @@ -0,0 +1,75 @@ +# This type validates that a successful postgres connection can be established +# between the node on which this resource is run and a specified postgres +# instance (host/port/user/password/database name). +# +# See README.md for more details. +define postgresql::validate_db_connection( + $database_host = undef, + $database_name = undef, + $database_password = undef, + $database_username = undef, + $database_port = undef, + $run_as = undef, + $sleep = 2, + $tries = 10, + $create_db_first = true +) { + require postgresql::client + include postgresql::params + + $psql_path = $postgresql::params::psql_path + + $cmd_init = "${psql_path} --tuples-only --quiet " + $cmd_host = $database_host ? { + default => "-h ${database_host} ", + undef => "", + } + $cmd_user = $database_username ? { + default => "-U ${database_username} ", + undef => "", + } + $cmd_port = $database_port ? { + default => "-p ${database_port} ", + undef => "", + } + $cmd_dbname = $database_name ? { + default => "--dbname ${database_name} ", + undef => "--dbname ${postgresql::params::default_database} ", + } + $env = $database_password ? { + default => "PGPASSWORD=${database_password}", + undef => undef, + } + $cmd = join([$cmd_init, $cmd_host, $cmd_user, $cmd_port, $cmd_dbname]) + $validate_cmd = "/usr/local/bin/validate_postgresql_connection.sh ${sleep} ${tries} '${cmd}'" + + # This is more of a safety valve, we add a little extra to compensate for the + # time it takes to run each psql command. + $timeout = (($sleep + 2) * $tries) + + $exec_name = "validate postgres connection for ${database_host}/${database_name}" + exec { $exec_name: + command => "echo 'Unable to connect to defined database using: ${cmd}' && false", + unless => $validate_cmd, + cwd => '/tmp', + environment => $env, + logoutput => 'on_failure', + user => $run_as, + path => '/bin', + timeout => $timeout, + require => Package['postgresql-client'], + } + + # This is a little bit of puppet magic. What we want to do here is make + # sure that if the validation and the database instance creation are being + # applied on the same machine, then the database resource is applied *before* + # the validation resource. Otherwise, the validation is guaranteed to fail + # on the first run. + # + # We accomplish this by using Puppet's resource collection syntax to search + # for the Database resource in our current catalog; if it exists, the + # appropriate relationship is created here. + if($create_db_first) { + Postgresql::Server::Database<|title == $database_name|> -> Exec[$exec_name] + } +} diff --git a/modules/postgresql/metadata.json b/modules/postgresql/metadata.json new file mode 100644 index 0000000..acea407 --- /dev/null +++ b/modules/postgresql/metadata.json @@ -0,0 +1,276 @@ +{ + "operatingsystem_support": [ + { + "operatingsystem": "RedHat", + "operatingsystemrelease": [ + "5", + "6" + ] + }, + { + "operatingsystem": "CentOS", + "operatingsystemrelease": [ + "5", + "6" + ] + }, + { + "operatingsystem": "OracleLinux", + "operatingsystemrelease": [ + "5", + "6" + ] + }, + { + "operatingsystem": "Scientific", + "operatingsystemrelease": [ + "5", + "6" + ] + }, + { + "operatingsystem": "Debian", + "operatingsystemrelease": [ + "6", + "7" + ] + }, + { + "operatingsystem": "Ubuntu", + "operatingsystemrelease": [ + "10.04", + "12.04" + ] + } + ], + "requirements": [ + { + "name": "pe", + "version_requirement": "3.2.x" + }, + { + "name": "puppet", + "version_requirement": "3.x" + } + ], + "name": "puppetlabs-postgresql", + "version": "3.3.3", + "source": "git://github.com/puppetlabs/puppet-postgresql.git", + "author": "Inkling/Puppet Labs", + "license": "ASL 2.0", + "summary": "PostgreSQL defined resource types", + "description": "PostgreSQL defined resource types", + "project_page": "https://github.com/puppetlabs/puppet-postgresql", + "dependencies": [ + { + "name": "puppetlabs/stdlib", + "version_requirement": ">=3.2.0 <5.0.0" + }, + { + "name": "puppetlabs/firewall", + "version_requirement": ">= 0.0.4" + }, + { + "name": "puppetlabs/apt", + "version_requirement": ">=1.1.0 <2.0.0" + }, + { + "name": "puppetlabs/concat", + "version_requirement": ">= 1.0.0 <2.0.0" + } + ], + "types": [ + { + "name": "postgresql_conf", + "doc": "This type allows puppet to manage postgresql.conf parameters.", + "properties": [ + { + "name": "ensure", + "doc": "The basic property that the resource should be in.\n\nValid values are `present`, `absent`. " + }, + { + "name": "value", + "doc": "The value to set for this parameter.\n\n" + }, + { + "name": "target", + "doc": "The path to postgresql.conf\n\n" + } + ], + "parameters": [ + { + "name": "name", + "doc": "The postgresql parameter name to manage.\n\nValues can match `/^[\\w\\.]+$/`." + } + ], + "providers": [ + { + "name": "parsed", + "doc": "Set key/values in postgresql.conf." + } + ] + }, + { + "name": "postgresql_psql", + "doc": "", + "properties": [ + { + "name": "command", + "doc": "The SQL command to execute via psql.\n\n" + } + ], + "parameters": [ + { + "name": "name", + "doc": "An arbitrary tag for your own reference; the name of the message.\n\n" + }, + { + "name": "unless", + "doc": "An optional SQL command to execute prior to the main :command; this is generally intended to be used for idempotency, to check for the existence of an object in the database to determine whether or not the main SQL command needs to be executed at all.\n\n" + }, + { + "name": "db", + "doc": "The name of the database to execute the SQL command against.\n\n" + }, + { + "name": "search_path", + "doc": "The schema search path to use when executing the SQL command\n\n" + }, + { + "name": "psql_path", + "doc": "The path to psql executable.\n\n" + }, + { + "name": "psql_user", + "doc": "The system user account under which the psql command should be executed.\n\n" + }, + { + "name": "psql_group", + "doc": "The system user group account under which the psql command should be executed.\n\n" + }, + { + "name": "cwd", + "doc": "The working directory under which the psql command should be executed.\n\n" + }, + { + "name": "refreshonly", + "doc": "If 'true', then the SQL will only be executed via a notify/subscribe event.\n\nValid values are `true`, `false`. " + } + ], + "providers": [ + { + "name": "ruby", + "doc": "" + } + ] + } + ], + "checksums": { + "CHANGELOG.md": "a6b64297ce9a85952614f7bdb57578fd", + "Gemfile": "1ef583c607af3c85f8a230989b1c41d9", + "Gemfile.lock": "cb6ae23a3082f56401a05db733102ef6", + "LICENSE": "746fe83ebbf8970af0a9ea13962293e9", + "Modulefile": "886e51cf26f9cd2e252b60772effff81", + "NOTICE": "d8ffc52f00e00877b45d2b77e709f69e", + "README.md": "1d43f087642b1b5252602fe73e10dc66", + "Rakefile": "c4f5c8ac6adc0eb4530c4b3d10cb7da0", + "files/RPM-GPG-KEY-PGDG": "78b5db170d33f80ad5a47863a7476b22", + "files/validate_postgresql_connection.sh": "20301932819f035492a30880f5bf335a", + "lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb": "d518a7959b950874820a3b0a7a324488", + "lib/puppet/parser/functions/postgresql_escape.rb": "2e136fcd653ab38d831c5b40806d47d1", + "lib/puppet/parser/functions/postgresql_password.rb": "820da02a888ab42357fe9bc2352b1c37", + "lib/puppet/provider/postgresql_conf/parsed.rb": "9c198422c0558faab1bedc00b68cfe45", + "lib/puppet/provider/postgresql_psql/ruby.rb": "8b651764452d8f410f72bd4bbc37d27d", + "lib/puppet/type/postgresql_conf.rb": "4f333138a3689f9768e7fe4bc3cde9fd", + "lib/puppet/type/postgresql_psql.rb": "2c1270cfed4ffb2971059846a57cf983", + "manifests/client.pp": "f9bc3a578017fe8eb881de2255bdc023", + "manifests/globals.pp": "f6840d296342f17b9e4717a8391d79f6", + "manifests/lib/devel.pp": "94ae7eac3acf1dd3072d481eca4d2d7f", + "manifests/lib/java.pp": "6e4a2187c2b4caecad8098b46e99c8e0", + "manifests/lib/python.pp": "90736f86301c4c6401ec1180c176b616", + "manifests/params.pp": "8a34fe2ef5cca6d0684bb304fa52776b", + "manifests/repo/apt_postgresql_org.pp": "ef7012ea3c5429bea11b1114183d32c3", + "manifests/repo/yum_postgresql_org.pp": "e0c445f877cdb39774b735417c967d1d", + "manifests/repo.pp": "a18a5cb760dbb1e10bdd83730300c1fe", + "manifests/server/config.pp": "ad4e6a3b034bf2975e47ac8df156eab4", + "manifests/server/config_entry.pp": "81ddbb8fe161d94394c7277a92cc6c1c", + "manifests/server/contrib.pp": "3112bd1edbed51b68e1402027f9d53b1", + "manifests/server/database.pp": "a6eacc4bf05c8ac12047dbf8aace7bc4", + "manifests/server/database_grant.pp": "66e5470bb932b087b540c444ee49941b", + "manifests/server/db.pp": "368ce3c55cb1685a7e9598a4760f0d1f", + "manifests/server/firewall.pp": "98632b073511a00926908c6951851052", + "manifests/server/grant.pp": "7f7fdf96611bfdd599dc382755c61c00", + "manifests/server/initdb.pp": "215f84f3d9931372190d9928832e315a", + "manifests/server/install.pp": "8520e3a86c74e0587a46c4548097bab3", + "manifests/server/passwd.pp": "197af62ecfcbd0982aa6563f2579d8bc", + "manifests/server/pg_hba_rule.pp": "f8e203ac4ea5a18ba065a47c8410f165", + "manifests/server/plperl.pp": "d6a2e2f0c93c7b543e9db64202c2e48d", + "manifests/server/reload.pp": "d62c048c8f25c167d266e99e36c0f227", + "manifests/server/role.pp": "a99508ee4e84034064c2cb1a121bdc62", + "manifests/server/service.pp": "8db858d1ea5b778cfef00e6ade81abb8", + "manifests/server/table_grant.pp": "bbc864f0ad8545837cf7782d1f7a1755", + "manifests/server/tablespace.pp": "beda12859757f7f677a711304dfd5185", + "manifests/server.pp": "aef6102d75512fab876195b4601e6fb3", + "manifests/validate_db_connection.pp": "be61434836f7d25cc184126a91b2e3e6", + "spec/acceptance/client_spec.rb": "5fc4174c010624f52d57ee9cefb44da7", + "spec/acceptance/common_patterns_spec.rb": "994e6117a54cbe96402a4c98686c3929", + "spec/acceptance/contrib_spec.rb": "efeaff22f5119067e0d0150edd9630e8", + "spec/acceptance/lib/devel_spec.rb": "8ff9ed46602e54b173dcd144394dddd4", + "spec/acceptance/lib/java_spec.rb": "46cec8b3fbc4a14172a4445ba351f0f8", + "spec/acceptance/lib/python_spec.rb": "2b311428d59918c8a0bd11b0188e6af5", + "spec/acceptance/nodesets/centos-510-x64.yml": "5698f7e61292730c603e03f64fe19359", + "spec/acceptance/nodesets/centos-59-x64.yml": "57eb3e471b9042a8ea40978c467f8151", + "spec/acceptance/nodesets/centos-64-x64-pe.yml": "ec075d95760df3d4702abea1ce0a829b", + "spec/acceptance/nodesets/centos-64-x64.yml": "9cde7b5d2ab6a42366d2344c264d6bdc", + "spec/acceptance/nodesets/debian-607-x64.yml": "d566bf76f534e2af7c9a4605316d232c", + "spec/acceptance/nodesets/debian-73-x64.yml": "ba5a75e27644c48ad8f3564fb6d372a7", + "spec/acceptance/nodesets/default.yml": "9cde7b5d2ab6a42366d2344c264d6bdc", + "spec/acceptance/nodesets/ubuntu-server-10044-x64.yml": "dc0da2d2449f66c8fdae16593811504f", + "spec/acceptance/nodesets/ubuntu-server-12042-x64.yml": "78a3ee42652e26119d90aa62586565b2", + "spec/acceptance/postgresql_psql_spec.rb": "2726a4198506325845281f9540a45711", + "spec/acceptance/server/config_entry_spec.rb": "acde0cb5edfb56b276273fd7b8c9e54c", + "spec/acceptance/server/database_grant_spec.rb": "57fa17960e79b2d6641e148b0ad416de", + "spec/acceptance/server/database_spec.rb": "d52e1743f93933e2b3ccb0536fa06ae3", + "spec/acceptance/server/db_spec.rb": "9389f1688296d38b2be1b3f82f3c47ef", + "spec/acceptance/server/grant_spec.rb": "e920c215c4936f2a70ee6bcb6fed5220", + "spec/acceptance/server/pg_hba_rule_spec.rb": "12809f3d42e6c86e2de9583fab908ede", + "spec/acceptance/server/plperl_spec.rb": "c8d175b8235d0c61377866746d2d0186", + "spec/acceptance/server/role_spec.rb": "a24f1c009013b55a1994eb713526f845", + "spec/acceptance/server/table_grant_spec.rb": "c7f824d83745f2bcc865e69726f1db92", + "spec/acceptance/server/tablespace_spec.rb": "b367d810e2fbc219adb8bdc46dd8b99b", + "spec/acceptance/server_spec.rb": "b49f58a9bce516f93479b5cd59fdf755", + "spec/acceptance/unsupported_spec.rb": "dc8c697053f34c0d1f33e31fb66adf5d", + "spec/acceptance/validate_db_connection_spec.rb": "19e271901a3d782e851805cee03b2b15", + "spec/spec_helper.rb": "d4e4a9a154ada34e7f13b0d8ece0f5db", + "spec/spec_helper_acceptance.rb": "a913cd3be2a7616f42b10eb403aee79b", + "spec/unit/classes/client_spec.rb": "b26438da8906e68d17e568252c1e43b5", + "spec/unit/classes/globals_spec.rb": "ca7fab47214c69fcf4fdbb1320cc4abf", + "spec/unit/classes/lib/devel_spec.rb": "11a2a75953d63a34b3e9ab7b6be2cc69", + "spec/unit/classes/lib/java_spec.rb": "bdb60c3b379a3788b3bf1f6c29b31c0a", + "spec/unit/classes/lib/python_spec.rb": "677c763c1a43a0e33ef7e6e819ec9f0a", + "spec/unit/classes/params_spec.rb": "2db946aa96446a1e38991c843b765323", + "spec/unit/classes/repo_spec.rb": "437ec024ca8d8cbd344671ccbb879a98", + "spec/unit/classes/server/contrib_spec.rb": "16528171ee3e058c06c5fea454dc9dbc", + "spec/unit/classes/server/initdb_spec.rb": "ece63fe900c3bcdb746e03a234b550c2", + "spec/unit/classes/server/plperl_spec.rb": "d00b94c70241848babaeee45143870ae", + "spec/unit/classes/server_spec.rb": "babaac49a4e5ae918f17328d86b72249", + "spec/unit/defines/server/config_entry_spec.rb": "cc2d9d0e4508d745f85c3446ccf76eb4", + "spec/unit/defines/server/database_grant_spec.rb": "e09254037c042efa5a29ba8d777c882f", + "spec/unit/defines/server/database_spec.rb": "090e9cf334843a4dc8b3f4eadce0109b", + "spec/unit/defines/server/db_spec.rb": "9f2181b0df771f4c6adf089b788adf42", + "spec/unit/defines/server/grant_spec.rb": "b8d8f46c7c4539747ee0b797a3a1834f", + "spec/unit/defines/server/pg_hba_rule_spec.rb": "3ed69d689bf28b56a030c543e7ce6775", + "spec/unit/defines/server/role_spec.rb": "fdb53fa637ccd79f8231e15383099137", + "spec/unit/defines/server/table_grant_spec.rb": "bb794a0b15dc74e8c8fa5d4878fd3c79", + "spec/unit/defines/server/tablespace_spec.rb": "68e7b9a193475491c58485debf1be220", + "spec/unit/defines/validate_db_connection_spec.rb": "88e57a8f780d381d75fe062f1178e1ce", + "spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb": "e7740c3cd2110e2fcebab8356012267c", + "spec/unit/functions/postgresql_escape_spec.rb": "6e52e4f3ca56491f8ba2d1490a5fd1ad", + "spec/unit/functions/postgresql_password_spec.rb": "76034569a5ff627073c5e6ff69176ac3", + "spec/unit/provider/postgresql_conf/parsed_spec.rb": "7295501a413d8cf99df6f40ea50a36fc", + "spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb": "c0ef725e4e7a5def13c29fad0c42478c", + "spec/unit/puppet/type/postgresql_psql_spec.rb": "2af5b74f7f4b89ff246818cd79488b3e", + "spec/unit/type/postgresql_conf_spec.rb": "76f460e0dfc90a1f38c407e5a0d4f463", + "templates/pg_hba_rule.conf": "13b46eecdfd359eddff71fa485ef2f54" + } +} \ No newline at end of file diff --git a/modules/postgresql/spec/acceptance/client_spec.rb b/modules/postgresql/spec/acceptance/client_spec.rb new file mode 100644 index 0000000..eaff526 --- /dev/null +++ b/modules/postgresql/spec/acceptance/client_spec.rb @@ -0,0 +1,18 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::client:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::client': package_ensure => purged }", + :catch_failures => true) + end + + it 'test loading class with no parameters' do + pp = <<-EOS.unindent + class { 'postgresql::client': } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end +end diff --git a/modules/postgresql/spec/acceptance/common_patterns_spec.rb b/modules/postgresql/spec/acceptance/common_patterns_spec.rb new file mode 100644 index 0000000..441da70 --- /dev/null +++ b/modules/postgresql/spec/acceptance/common_patterns_spec.rb @@ -0,0 +1,47 @@ +require 'spec_helper_acceptance' + +describe 'common patterns:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + describe 'postgresql.conf include pattern' do + after :all do + pp = <<-EOS.unindent + class { 'postgresql::server': ensure => absent } + + file { '/tmp/include.conf': + ensure => absent + } + EOS + apply_manifest(pp, :catch_failures => true) + end + + it "should support an 'include' directive at the end of postgresql.conf" do + pending('no support for include directive with centos 5/postgresql 8.1', + :if => (fact('osfamily') == 'RedHat' and fact('lsbmajdistrelease') == '5')) + + pp = <<-EOS.unindent + class { 'postgresql::server': } + + $extras = "/etc/postgresql-include.conf" + + file { $extras: + content => 'max_connections = 123', + seltype => 'postgresql_db_t', + seluser => 'system_u', + notify => Class['postgresql::server::service'], + } + + postgresql::server::config_entry { 'include': + value => $extras, + require => File[$extras], + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + psql('--command="show max_connections" -t', 'postgres') do |r| + expect(r.stdout).to match(/123/) + expect(r.stderr).to eq('') + end + end + end +end diff --git a/modules/postgresql/spec/acceptance/contrib_spec.rb b/modules/postgresql/spec/acceptance/contrib_spec.rb new file mode 100644 index 0000000..d6dbb95 --- /dev/null +++ b/modules/postgresql/spec/acceptance/contrib_spec.rb @@ -0,0 +1,28 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::server::contrib:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran, remove both contrib and server as contrib + # pulls in the server based packages. + pp = <<-EOS.unindent + class { 'postgresql::server': + ensure => absent, + } + class { 'postgresql::server::contrib': + package_ensure => purged, + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + it 'test loading class with no parameters' do + pp = <<-EOS.unindent + class { 'postgresql::server': } + class { 'postgresql::server::contrib': } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end +end diff --git a/modules/postgresql/spec/acceptance/lib/devel_spec.rb b/modules/postgresql/spec/acceptance/lib/devel_spec.rb new file mode 100644 index 0000000..51a5ea9 --- /dev/null +++ b/modules/postgresql/spec/acceptance/lib/devel_spec.rb @@ -0,0 +1,17 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::lib::devel:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::lib::devel': package_ensure => purged }", :catch_failures => true) + end + + it 'test loading class with no parameters' do + pp = <<-EOS.unindent + class { 'postgresql::lib::devel': } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end +end diff --git a/modules/postgresql/spec/acceptance/lib/java_spec.rb b/modules/postgresql/spec/acceptance/lib/java_spec.rb new file mode 100644 index 0000000..c943bed --- /dev/null +++ b/modules/postgresql/spec/acceptance/lib/java_spec.rb @@ -0,0 +1,20 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::lib::java:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::lib::java': package_ensure => purged }", :catch_failures => true) + end + + it 'test loading class with no parameters' do + pending('libpostgresql-java-jdbc not available natively for Ubuntu 10.04 and Debian 6', + :if => (fact('osfamily') == 'Debian' and ['6', '10'].include?(fact('lsbmajdistrelease')))) + + pp = <<-EOS.unindent + class { 'postgresql::lib::java': } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end +end diff --git a/modules/postgresql/spec/acceptance/lib/python_spec.rb b/modules/postgresql/spec/acceptance/lib/python_spec.rb new file mode 100644 index 0000000..173204e --- /dev/null +++ b/modules/postgresql/spec/acceptance/lib/python_spec.rb @@ -0,0 +1,19 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::lib::python:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::lib::python': package_ensure => purged }", :catch_failures => true) + end + + it 'test loading class with no parameters' do + pending('psycopg2 not available natively for centos 5', :if => (fact('osfamily') == 'RedHat' and fact('lsbmajdistrelease') == '5')) + + pp = <<-EOS.unindent + class { 'postgresql::lib::python': } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end +end diff --git a/modules/postgresql/spec/acceptance/nodesets/centos-510-x64.yml b/modules/postgresql/spec/acceptance/nodesets/centos-510-x64.yml new file mode 100644 index 0000000..12c9e78 --- /dev/null +++ b/modules/postgresql/spec/acceptance/nodesets/centos-510-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-510-x64: + roles: + - master + platform: el-5-x86_64 + box : centos-510-x64-virtualbox-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-510-x64-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/postgresql/spec/acceptance/nodesets/centos-59-x64.yml b/modules/postgresql/spec/acceptance/nodesets/centos-59-x64.yml new file mode 100644 index 0000000..2ad90b8 --- /dev/null +++ b/modules/postgresql/spec/acceptance/nodesets/centos-59-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-59-x64: + roles: + - master + platform: el-5-x86_64 + box : centos-59-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-59-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/postgresql/spec/acceptance/nodesets/centos-64-x64-pe.yml b/modules/postgresql/spec/acceptance/nodesets/centos-64-x64-pe.yml new file mode 100644 index 0000000..7d9242f --- /dev/null +++ b/modules/postgresql/spec/acceptance/nodesets/centos-64-x64-pe.yml @@ -0,0 +1,12 @@ +HOSTS: + centos-64-x64: + roles: + - master + - database + - dashboard + platform: el-6-x86_64 + box : centos-64-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: pe diff --git a/modules/postgresql/spec/acceptance/nodesets/centos-64-x64.yml b/modules/postgresql/spec/acceptance/nodesets/centos-64-x64.yml new file mode 100644 index 0000000..0639835 --- /dev/null +++ b/modules/postgresql/spec/acceptance/nodesets/centos-64-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-64-x64: + roles: + - master + platform: el-6-x86_64 + box : centos-64-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/postgresql/spec/acceptance/nodesets/debian-607-x64.yml b/modules/postgresql/spec/acceptance/nodesets/debian-607-x64.yml new file mode 100644 index 0000000..4c8be42 --- /dev/null +++ b/modules/postgresql/spec/acceptance/nodesets/debian-607-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + debian-607-x64: + roles: + - master + platform: debian-6-amd64 + box : debian-607-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/debian-607-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/postgresql/spec/acceptance/nodesets/debian-73-x64.yml b/modules/postgresql/spec/acceptance/nodesets/debian-73-x64.yml new file mode 100644 index 0000000..3e31a82 --- /dev/null +++ b/modules/postgresql/spec/acceptance/nodesets/debian-73-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + debian-73-x64: + roles: + - master + platform: debian-7-amd64 + box : debian-73-x64-virtualbox-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/debian-73-x64-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/postgresql/spec/acceptance/nodesets/default.yml b/modules/postgresql/spec/acceptance/nodesets/default.yml new file mode 100644 index 0000000..0639835 --- /dev/null +++ b/modules/postgresql/spec/acceptance/nodesets/default.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-64-x64: + roles: + - master + platform: el-6-x86_64 + box : centos-64-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/postgresql/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml b/modules/postgresql/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml new file mode 100644 index 0000000..5047017 --- /dev/null +++ b/modules/postgresql/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + ubuntu-server-10044-x64: + roles: + - master + platform: ubuntu-10.04-amd64 + box : ubuntu-server-10044-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-10044-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/postgresql/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml b/modules/postgresql/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml new file mode 100644 index 0000000..1c7a34c --- /dev/null +++ b/modules/postgresql/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + ubuntu-server-12042-x64: + roles: + - master + platform: ubuntu-12.04-amd64 + box : ubuntu-server-12042-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-12042-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: git diff --git a/modules/postgresql/spec/acceptance/postgresql_psql_spec.rb b/modules/postgresql/spec/acceptance/postgresql_psql_spec.rb new file mode 100644 index 0000000..5c03a7a --- /dev/null +++ b/modules/postgresql/spec/acceptance/postgresql_psql_spec.rb @@ -0,0 +1,43 @@ +require 'spec_helper_acceptance' + +describe 'postgresql_psql:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'should run some SQL when the unless query returns no rows' do + pp = <<-EOS.unindent + class { 'postgresql::server': } + + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select 1', + unless => 'select 1 where 1=2', + require => Class['postgresql::server'], + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_failures => true) + end + + it 'should not run SQL when the unless query returns rows' do + pp = <<-EOS.unindent + class { 'postgresql::server': } + + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select * from pg_database limit 1', + unless => 'select 1 where 1=1', + require => Class['postgresql::server'], + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end + +end diff --git a/modules/postgresql/spec/acceptance/server/config_entry_spec.rb b/modules/postgresql/spec/acceptance/server/config_entry_spec.rb new file mode 100644 index 0000000..a58903a --- /dev/null +++ b/modules/postgresql/spec/acceptance/server/config_entry_spec.rb @@ -0,0 +1,26 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::server::config_entry:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'should change setting and reflect it in show all' do + pp = <<-EOS.unindent + class { 'postgresql::server': } + + postgresql::server::config_entry { 'check_function_bodies': + value => 'off', + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + psql('--command="show all" postgres') do |r| + expect(r.stdout).to match(/check_function_bodies.+off/) + expect(r.stderr).to eq('') + end + end +end diff --git a/modules/postgresql/spec/acceptance/server/database_grant_spec.rb b/modules/postgresql/spec/acceptance/server/database_grant_spec.rb new file mode 100644 index 0000000..99ce44d --- /dev/null +++ b/modules/postgresql/spec/acceptance/server/database_grant_spec.rb @@ -0,0 +1,48 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::server::database_grant:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'should grant access so a user can create objects in a database' do + begin + pp = <<-EOS.unindent + $db = 'postgres' + $user = 'psql_grant_tester' + $password = 'psql_grant_pw' + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + + postgresql::server::database { $db: } + + postgresql::server::database_grant { 'grant create test': + privilege => 'CREATE', + db => $db, + role => $user, + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + # Check that the user can create a table in the database + psql('--command="create table foo (foo int)" postgres', 'psql_grant_tester') do |r| + expect(r.stdout).to match(/CREATE TABLE/) + expect(r.stderr).to eq('') + end + ensure + psql('--command="drop table foo" postgres', 'psql_grant_tester') + end + end +end diff --git a/modules/postgresql/spec/acceptance/server/database_spec.rb b/modules/postgresql/spec/acceptance/server/database_spec.rb new file mode 100644 index 0000000..7f227d1 --- /dev/null +++ b/modules/postgresql/spec/acceptance/server/database_spec.rb @@ -0,0 +1,29 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::server::database:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'should idempotently create a db that we can connect to' do + begin + pp = <<-EOS.unindent + $db = 'postgresql_test_db' + class { 'postgresql::server': } + + postgresql::server::database { $db: } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + psql('--command="select datname from pg_database" postgresql_test_db') do |r| + expect(r.stdout).to match(/postgresql_test_db/) + expect(r.stderr).to eq('') + end + ensure + psql('--command="drop database postgresql_test_db" postgres') + end + end +end diff --git a/modules/postgresql/spec/acceptance/server/db_spec.rb b/modules/postgresql/spec/acceptance/server/db_spec.rb new file mode 100644 index 0000000..0287976 --- /dev/null +++ b/modules/postgresql/spec/acceptance/server/db_spec.rb @@ -0,0 +1,138 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::server::db', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'should idempotently create a db that we can connect to' do + begin + pp = <<-EOS.unindent + $db = 'postgresql_test_db' + class { 'postgresql::server': } + + postgresql::server::db { $db: + user => $db, + password => postgresql_password($db, $db), + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + psql('--command="select datname from pg_database" postgresql_test_db') do |r| + expect(r.stdout).to match(/postgresql_test_db/) + expect(r.stderr).to eq('') + end + ensure + psql('--command="drop database postgresql_test_db" postgres') + end + end + + it 'should take a locale parameter' do + pending('no support for locale parameter with centos 5', :if => (fact('osfamily') == 'RedHat' and fact('lsbmajdistrelease') == '5')) + begin + pp = <<-EOS.unindent + class { 'postgresql::server': } + postgresql::server::db { 'test1': + user => 'test1', + password => postgresql_password('test1', 'test1'), + encoding => 'UTF8', + locale => 'en_NG.UTF-8', + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + psql('-c "show lc_ctype" test1') do |r| + expect(r.stdout).to match(/en_NG/) + end + + psql('-c "show lc_collate" test1') do |r| + expect(r.stdout).to match(/en_NG/) + end + ensure + psql('--command="drop database test1" postgres') + end + end + + it 'should take an istemplate parameter' do + begin + pp = <<-EOS.unindent + $db = 'template2' + class { 'postgresql::server': } + + postgresql::server::db { $db: + user => $db, + password => postgresql_password($db, $db), + istemplate => true, + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + psql('--command="select datname from pg_database" template2') do |r| + expect(r.stdout).to match(/template2/) + expect(r.stderr).to eq('') + end + ensure + psql('--command="drop database template2" postgres', 'postgres', [1,2]) do |r| + expect(r.stdout).to eq('') + expect(r.stderr).to match(/cannot drop a template database/) + end + end + end + + it 'should update istemplate parameter' do + begin + pp = <<-EOS.unindent + $db = 'template2' + class { 'postgresql::server': } + + postgresql::server::db { $db: + user => $db, + password => postgresql_password($db, $db), + istemplate => false, + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + psql('--command="select datname from pg_database" template2') do |r| + expect(r.stdout).to match(/template2/) + expect(r.stderr).to eq('') + end + ensure + psql('--command="drop database template2" postgres') + end + end + + it 'should take a template parameter' do + begin + pp = <<-EOS.unindent + $db = 'postgresql_test_db' + class { 'postgresql::server': } + + postgresql::server::db { $db: + user => $db, + template => 'template1', + password => postgresql_password($db, $db), + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + psql('--command="select datname from pg_database" postgresql_test_db') do |r| + expect(r.stdout).to match(/postgresql_test_db/) + expect(r.stderr).to eq('') + end + ensure + psql('--command="drop database postgresql_test_db" postgres') + end + end +end diff --git a/modules/postgresql/spec/acceptance/server/grant_spec.rb b/modules/postgresql/spec/acceptance/server/grant_spec.rb new file mode 100644 index 0000000..d34523a --- /dev/null +++ b/modules/postgresql/spec/acceptance/server/grant_spec.rb @@ -0,0 +1,49 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::server::grant:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'should grant access so a user can create in a database' do + begin + pp = <<-EOS.unindent + $db = 'postgres' + $user = 'psql_grant_tester' + $password = 'psql_grant_pw' + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + + postgresql::server::database { $db: } + + postgresql::server::grant { 'grant create test': + object_type => 'database', + privilege => 'CREATE', + db => $db, + role => $user, + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + # Check that the user can create a table in the database + psql('--command="create table foo (foo int)" postgres', 'psql_grant_tester') do |r| + expect(r.stdout).to match(/CREATE TABLE/) + expect(r.stderr).to eq('') + end + ensure + psql('--command="drop table foo" postgres', 'psql_grant_tester') + end + end +end diff --git a/modules/postgresql/spec/acceptance/server/pg_hba_rule_spec.rb b/modules/postgresql/spec/acceptance/server/pg_hba_rule_spec.rb new file mode 100644 index 0000000..bbc8e94 --- /dev/null +++ b/modules/postgresql/spec/acceptance/server/pg_hba_rule_spec.rb @@ -0,0 +1,72 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::server::pg_hba_rule:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'should create a ruleset in pg_hba.conf' do + pp = <<-EOS.unindent + class { 'postgresql::server': } + postgresql::server::pg_hba_rule { "allow application network to access app database": + type => "host", + database => "app", + user => "app", + address => "200.1.2.0/24", + auth_method => md5, + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_failures => true) + + shell("grep '200.1.2.0/24' /etc/postgresql/*/*/pg_hba.conf || grep '200.1.2.0/24' /var/lib/pgsql/data/pg_hba.conf") + end + + it 'should create a ruleset in pg_hba.conf that denies db access to db test1' do + pp = <<-EOS.unindent + class { 'postgresql::server': } + + postgresql::server::db { "test1": + user => "test1", + password => postgresql_password('test1', 'test1'), + grant => "all", + } + + postgresql::server::pg_hba_rule { "allow anyone to have access to db test1": + type => "local", + database => "test1", + user => "test1", + auth_method => reject, + order => '001', + } + + user { "test1": + shell => "/bin/bash", + managehome => true, + } + EOS + + apply_manifest(pp, :catch_failures => true) + + shell('su - test1 -c \'psql -U test1 -c "\q" test1\'', :acceptable_exit_codes => [2]) + end + + it 'should fail catalogue if postgresql::server::manage_pga_conf is disabled' do + pp = <<-EOS.unindent + class { 'postgresql::server': + manage_pg_hba_conf => false, + } + postgresql::server::pg_hba_rule { 'foo': + type => "local", + database => "test1", + user => "test1", + auth_method => reject, + order => '001', + } + EOS + + apply_manifest(pp, :expect_failures => true) + end +end diff --git a/modules/postgresql/spec/acceptance/server/plperl_spec.rb b/modules/postgresql/spec/acceptance/server/plperl_spec.rb new file mode 100644 index 0000000..7331284 --- /dev/null +++ b/modules/postgresql/spec/acceptance/server/plperl_spec.rb @@ -0,0 +1,25 @@ +require 'spec_helper_acceptance' + +describe 'server plperl:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + pp = <<-EOS.unindent + class { 'postgresql::server': ensure => absent } + class { 'postgresql::server::plperl': package_ensure => purged } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + it 'test loading class with no parameters' do + pending('no support for plperl with default version on centos 5', + :if => (fact('osfamily') == 'RedHat' and fact('lsbmajdistrelease') == '5')) + pp = <<-EOS.unindent + class { 'postgresql::server': } + class { 'postgresql::server::plperl': } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end +end diff --git a/modules/postgresql/spec/acceptance/server/role_spec.rb b/modules/postgresql/spec/acceptance/server/role_spec.rb new file mode 100644 index 0000000..2bd2b70 --- /dev/null +++ b/modules/postgresql/spec/acceptance/server/role_spec.rb @@ -0,0 +1,88 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::server::role:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'should idempotently create a user who can log in' do + pp = <<-EOS.unindent + $user = "postgresql_test_user" + $password = "postgresql_test_password" + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + EOS + + apply_manifest(pp, :catch_failures => true) + + # Check that the user can log in + psql('--command="select datname from pg_database" postgres', 'postgresql_test_user') do |r| + expect(r.stdout).to match(/template1/) + expect(r.stderr).to eq('') + end + end + + it 'should idempotently alter a user who can log in' do + pp = <<-EOS.unindent + $user = "postgresql_test_user" + $password = "postgresql_test_password2" + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + # Check that the user can log in + psql('--command="select datname from pg_database" postgres', 'postgresql_test_user') do |r| + expect(r.stdout).to match(/template1/) + expect(r.stderr).to eq('') + end + end + + it 'should idempotently create a user with a cleartext password' do + pp = <<-EOS.unindent + $user = "postgresql_test_user2" + $password = "postgresql_test_password2" + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => $password, + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + # Check that the user can log in + psql('--command="select datname from pg_database" postgres', 'postgresql_test_user2') do |r| + expect(r.stdout).to match(/template1/) + expect(r.stderr).to eq('') + end + end +end diff --git a/modules/postgresql/spec/acceptance/server/table_grant_spec.rb b/modules/postgresql/spec/acceptance/server/table_grant_spec.rb new file mode 100644 index 0000000..6a779d9 --- /dev/null +++ b/modules/postgresql/spec/acceptance/server/table_grant_spec.rb @@ -0,0 +1,124 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::server::table_grant:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'should grant all accesses to a user' do + begin + pp = <<-EOS.unindent + $db = 'table_grant' + $user = 'psql_grant_tester' + $password = 'psql_table_pw' + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + + postgresql::server::database { $db: } + + # Create a rule for the user + postgresql::server::pg_hba_rule { "allow ${user}": + type => 'local', + database => $db, + user => $user, + auth_method => 'ident', + order => 1, + } + + postgresql_psql { 'Create testing table': + command => 'CREATE TABLE "test_table" (field integer NOT NULL)', + db => $db, + unless => "SELECT * FROM pg_tables WHERE tablename = 'test_table'", + require => Postgresql::Server::Database[$db], + } + + postgresql::server::table_grant { 'grant insert test': + privilege => 'ALL', + table => 'test_table', + db => $db, + role => $user, + require => Postgresql_psql['Create testing table'], + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + ## Check that the user can create a table in the database + psql('--command="create table foo (foo int)" postgres', 'psql_grant_tester') do |r| + expect(r.stdout).to match(/CREATE TABLE/) + expect(r.stderr).to eq('') + end + ensure + psql('--command="drop table foo" postgres', 'psql_grant_tester') + end + end + + it 'should grant access so a user can insert in a table' do + begin + pp = <<-EOS.unindent + $db = 'table_grant' + $user = 'psql_grant_tester' + $password = 'psql_table_pw' + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + + postgresql::server::database { $db: } + + # Create a rule for the user + postgresql::server::pg_hba_rule { "allow ${user}": + type => 'local', + database => $db, + user => $user, + auth_method => 'ident', + order => 1, + } + + postgresql_psql { 'Create testing table': + command => 'CREATE TABLE "test_table" (field integer NOT NULL)', + db => $db, + unless => "SELECT * FROM pg_tables WHERE tablename = 'test_table'", + require => Postgresql::Server::Database[$db], + } + + postgresql::server::table_grant { 'grant insert test': + privilege => 'INSERT', + table => 'test_table', + db => $db, + role => $user, + require => Postgresql_psql['Create testing table'], + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + ## Check that the user can create a table in the database + psql('--command="create table foo (foo int)" postgres', 'psql_grant_tester') do |r| + expect(r.stdout).to match(/CREATE TABLE/) + expect(r.stderr).to eq('') + end + ensure + psql('--command="drop table foo" postgres', 'psql_grant_tester') + end + end +end diff --git a/modules/postgresql/spec/acceptance/server/tablespace_spec.rb b/modules/postgresql/spec/acceptance/server/tablespace_spec.rb new file mode 100644 index 0000000..c633d6d --- /dev/null +++ b/modules/postgresql/spec/acceptance/server/tablespace_spec.rb @@ -0,0 +1,67 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::server::tablespace:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'should idempotently create tablespaces and databases that are using them' do + pp = <<-EOS.unindent + class { 'postgresql::server': } + + file { '/tmp/postgres/pg_tablespaces': + ensure => 'directory', + owner => 'postgres', + group => 'postgres', + mode => '0700', + } + + postgresql::server::tablespace { 'tablespace1': + location => '/tmp/postgres/pg_tablespaces/space1', + } + postgresql::server::database { 'tablespacedb1': + encoding => 'utf8', + tablespace => 'tablespace1', + } + postgresql::server::db { 'tablespacedb2': + user => 'dbuser2', + password => postgresql_password('dbuser2', 'dbuser2'), + tablespace => 'tablespace1', + } + + postgresql::server::role { 'spcuser': + password_hash => postgresql_password('spcuser', 'spcuser'), + } + postgresql::server::tablespace { 'tablespace2': + location => '/tmp/postgres/pg_tablespaces/space2', + owner => 'spcuser', + } + postgresql::server::database { 'tablespacedb3': + encoding => 'utf8', + tablespace => 'tablespace2', + } + EOS + + shell('mkdir -p /tmp/postgres') + # Apply appropriate selinux labels + if fact('osfamily') == 'RedHat' + if shell('getenforce').stdout =~ /Enforcing/ + shell('chcon -Rv --type=postgresql_db_t /tmp/postgres') + end + end + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + # Check that databases use correct tablespaces + psql('--command="select ts.spcname from pg_database db, pg_tablespace ts where db.dattablespace = ts.oid and db.datname = \'"\'tablespacedb1\'"\'"') do |r| + expect(r.stdout).to match(/tablespace1/) + expect(r.stderr).to eq('') + end + + psql('--command="select ts.spcname from pg_database db, pg_tablespace ts where db.dattablespace = ts.oid and db.datname = \'"\'tablespacedb3\'"\'"') do |r| + expect(r.stdout).to match(/tablespace2/) + expect(r.stderr).to eq('') + end + end +end diff --git a/modules/postgresql/spec/acceptance/server_spec.rb b/modules/postgresql/spec/acceptance/server_spec.rb new file mode 100644 index 0000000..b8456ee --- /dev/null +++ b/modules/postgresql/spec/acceptance/server_spec.rb @@ -0,0 +1,188 @@ +require 'spec_helper_acceptance' + +describe 'server:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + # Cleanup after tests have ran + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'test loading class with no parameters' do + pp = <<-EOS.unindent + class { 'postgresql::server': } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end + + describe port(5432) do + it { should be_listening } + end + + describe 'setting postgres password' do + it 'should install and successfully adjust the password' do + pp = <<-EOS.unindent + class { 'postgresql::server': + postgres_password => 'foobarbaz', + ip_mask_deny_postgres_user => '0.0.0.0/32', + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/\[set_postgres_postgrespw\]\/returns: executed successfully/) + end + apply_manifest(pp, :catch_changes => true) + + pp = <<-EOS.unindent + class { 'postgresql::server': + postgres_password => 'TPSR$$eports!', + ip_mask_deny_postgres_user => '0.0.0.0/32', + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/\[set_postgres_postgrespw\]\/returns: executed successfully/) + end + apply_manifest(pp, :catch_changes => true) + + end + end +end + +describe 'server without defaults:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + context 'test installing non-default version of postgresql' do + after :all do + psql('--command="drop database postgresql_test_db" postgres', 'postgres') + pp = <<-EOS.unindent + if $::osfamily == 'Debian' { + class { 'apt': } + # XXX Need to purge postgresql-common after uninstalling 9.3 because + # it leaves the init script behind. Poor packaging. + package { 'postgresql-common': + ensure => purged, + require => Class['postgresql::server'], + } + } + class { 'postgresql::globals': + ensure => absent, + manage_package_repo => true, + version => '9.3', + } + class { 'postgresql::server': + ensure => absent, + } + EOS + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq('') + end + + it 'perform installation and create a db' do + pp = <<-EOS.unindent + if $::osfamily == 'Debian' { + class { 'apt': } + } + class { "postgresql::globals": + version => "9.3", + manage_package_repo => true, + encoding => 'UTF8', + locale => 'en_US.UTF-8', + xlogdir => '/tmp/pg_xlogs', + } + class { "postgresql::server": } + postgresql::server::db { "postgresql_test_db": + user => "foo1", + password => postgresql_password('foo1', 'foo1'), + } + postgresql::server::config_entry { 'port': + value => '5432', + } + EOS + + expect(apply_manifest(pp, :catch_failures => true).stderr).to eq('') + apply_manifest(pp, :catch_changes => true) + + shell('test -d /tmp/pg_xlogs') do |r| + expect(r.stdout).to eq('') + expect(r.stderr).to eq('') + end + + psql('postgresql_test_db --command="select datname from pg_database limit 1"') + end + + describe port(5432) do + it { should be_listening } + end + end + + unless ((fact('osfamily') == 'RedHat' and fact('lsbmajdistrelease') == '5') || + fact('osfamily') == 'Debian') + + context 'override locale and encoding' do + after :each do + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'perform installation with different locale and encoding' do + pp = <<-EOS.unindent + class { 'postgresql::server': + locale => 'en_NG', + encoding => 'UTF8', + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + + # Remove db first, if it exists for some reason + shell('su postgres -c "dropdb test1"', :acceptable_exit_codes => [0,1,2]) + shell('su postgres -c "createdb test1"') + shell('su postgres -c \'psql -c "show lc_ctype" test1\'') do |r| + expect(r.stdout).to match(/en_NG/) + end + + shell('su postgres -c \'psql -c "show lc_collate" test1\'') do |r| + expect(r.stdout).to match(/en_NG/) + end + end + end + end +end + +describe 'server with firewall:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + context 'test installing postgresql with firewall management on' do + it 'perform installation and make sure it is idempotent' do + pending('no support for firewall with fedora', :if => (fact('operatingsystem') == 'Fedora')) + pp = <<-EOS.unindent + class { 'firewall': } + class { "postgresql::server": + manage_firewall => true, + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end + end +end + +describe 'server without pg_hba.conf:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + after :all do + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + context 'test installing postgresql without pg_hba.conf management on' do + it 'perform installation and make sure it is idempotent' do + pp = <<-EOS.unindent + class { "postgresql::server": + manage_pg_hba_conf => false, + } + EOS + + apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, :catch_changes => true) + end + end +end diff --git a/modules/postgresql/spec/acceptance/unsupported_spec.rb b/modules/postgresql/spec/acceptance/unsupported_spec.rb new file mode 100644 index 0000000..1f64a1f --- /dev/null +++ b/modules/postgresql/spec/acceptance/unsupported_spec.rb @@ -0,0 +1,16 @@ +require 'spec_helper_acceptance' + +describe 'unsupported distributions and OSes', :if => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + it 'should fail for client' do + pp = <<-EOS + class { 'postgresql::client': } + EOS + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/does not provide defaults for osfamily/i) + end + it 'should fail for server' do + pp = <<-EOS + class { 'postgresql::server': } + EOS + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/does not provide defaults for osfamily/i) + end +end diff --git a/modules/postgresql/spec/acceptance/validate_db_connection_spec.rb b/modules/postgresql/spec/acceptance/validate_db_connection_spec.rb new file mode 100644 index 0000000..0bfe509 --- /dev/null +++ b/modules/postgresql/spec/acceptance/validate_db_connection_spec.rb @@ -0,0 +1,79 @@ +require 'spec_helper_acceptance' + +describe 'postgresql::validate_db_connection:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + before :all do + # Setup postgresql server and a sample database for tests to use. + pp = <<-EOS.unindent + $db = 'foo' + class { 'postgresql::server': } + + postgresql::server::db { $db: + user => $db, + password => postgresql_password($db, $db), + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + after :all do + # Remove postgresql server after all tests have ran. + apply_manifest("class { 'postgresql::server': ensure => absent }", :catch_failures => true) + end + + it 'should run puppet with no changes declared if socket connectivity works' do + pp = <<-EOS.unindent + postgresql::validate_db_connection { 'foo': + database_name => 'foo', + run_as => 'postgres', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + it 'should keep retrying if database is down' do + # So first we shut the db down, then background a startup routine with a + # sleep 10 in front of it. That way the tests should continue while + # the pause and db startup happens in the background. + shell("/etc/init.d/postgresql* stop") + shell('nohup bash -c "sleep 10; /etc/init.d/postgresql* start" > /dev/null 2>&1 &') + + pp = <<-EOS.unindent + postgresql::validate_db_connection { 'foo': + database_name => 'foo', + tries => 30, + sleep => 1, + run_as => 'postgres', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + it 'should run puppet with no changes declared if db ip connectivity works' do + pp = <<-EOS.unindent + postgresql::validate_db_connection { 'foo': + database_host => 'localhost', + database_name => 'foo', + database_username => 'foo', + database_password => 'foo', + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + it 'should fail catalogue if database connectivity fails' do + pp = <<-EOS.unindent + postgresql::validate_db_connection { 'foobarbaz': + database_host => 'localhost', + database_name => 'foobarbaz', + database_username => 'foobarbaz', + database_password => 'foobarbaz', + } + EOS + + apply_manifest(pp, :expect_failures => true) + end +end diff --git a/modules/postgresql/spec/spec_helper.rb b/modules/postgresql/spec/spec_helper.rb new file mode 100644 index 0000000..b4c44aa --- /dev/null +++ b/modules/postgresql/spec/spec_helper.rb @@ -0,0 +1,30 @@ +require 'puppetlabs_spec_helper/module_spec_helper' + +RSpec.configure do |c| + c.mock_with :rspec do |mock| + mock.syntax = [:expect, :should] + end + c.include PuppetlabsSpec::Files + + c.before :each do + # Ensure that we don't accidentally cache facts and environment + # between test cases. + Facter::Util::Loader.any_instance.stubs(:load_all) + Facter.clear + Facter.clear_messages + + # Store any environment variables away to be restored later + @old_env = {} + ENV.each_key {|k| @old_env[k] = ENV[k]} + end + + c.after :each do + PuppetlabsSpec::Files.cleanup + end +end + +# Convenience helper for returning parameters for a type from the +# catalogue. +def param(type, title, param) + param_value(catalogue, type, title, param) +end diff --git a/modules/postgresql/spec/spec_helper_acceptance.rb b/modules/postgresql/spec/spec_helper_acceptance.rb new file mode 100644 index 0000000..4984da6 --- /dev/null +++ b/modules/postgresql/spec/spec_helper_acceptance.rb @@ -0,0 +1,75 @@ +require 'beaker-rspec/spec_helper' +require 'beaker-rspec/helpers/serverspec' + +class String + # Provide ability to remove indentation from strings, for the purpose of + # left justifying heredoc blocks. + def unindent + gsub(/^#{scan(/^\s*/).min_by{|l|l.length}}/, "") + end +end + +def shellescape(str) + str = str.to_s + + # An empty argument will be skipped, so return empty quotes. + return "''" if str.empty? + + str = str.dup + + # Treat multibyte characters as is. It is caller's responsibility + # to encode the string in the right encoding for the shell + # environment. + str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/, "\\\\\\1") + + # A LF cannot be escaped with a backslash because a backslash + LF + # combo is regarded as line continuation and simply ignored. + str.gsub!(/\n/, "'\n'") + + return str +end + +def psql(psql_cmd, user = 'postgres', exit_codes = [0], &block) + psql = "psql #{psql_cmd}" + shell("su #{shellescape(user)} -c #{shellescape(psql)}", :acceptable_exit_codes => exit_codes, &block) +end + +unless ENV['RS_PROVISION'] == 'no' + hosts.each do |host| + if host.is_pe? + install_pe + else + install_puppet + on host, "mkdir -p #{host['distmoduledir']}" + end + end +end + +UNSUPPORTED_PLATFORMS = ['AIX','windows','Solaris','Suse'] + +RSpec.configure do |c| + # Project root + proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) + + # Readable test descriptions + c.formatter = :documentation + + # Configure all nodes in nodeset + c.before :suite do + # Install module and dependencies + puppet_module_install(:source => proj_root, :module_name => 'postgresql') + hosts.each do |host| + on host, "/bin/touch #{default['puppetpath']}/hiera.yaml" + on host, 'chmod 755 /root' + if fact('osfamily') == 'Debian' + on host, "echo \"en_US ISO-8859-1\nen_NG.UTF-8 UTF-8\nen_US.UTF-8 UTF-8\n\" > /etc/locale.gen" + on host, '/usr/sbin/locale-gen' + on host, '/usr/sbin/update-locale' + end + on host, puppet('module','install','puppetlabs-stdlib'), { :acceptable_exit_codes => [0,1] } + on host, puppet('module','install','puppetlabs-firewall'), { :acceptable_exit_codes => [0,1] } + on host, puppet('module','install','puppetlabs-apt'), { :acceptable_exit_codes => [0,1] } + on host, puppet('module','install','puppetlabs-concat'), { :acceptable_exit_codes => [0,1] } + end + end +end diff --git a/modules/postgresql/spec/unit/classes/client_spec.rb b/modules/postgresql/spec/unit/classes/client_spec.rb new file mode 100644 index 0000000..dd24dbf --- /dev/null +++ b/modules/postgresql/spec/unit/classes/client_spec.rb @@ -0,0 +1,36 @@ +require 'spec_helper' + +describe 'postgresql::client', :type => :class do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + + describe 'with parameters' do + let :params do + { + :package_ensure => 'absent', + :package_name => 'mypackage', + } + end + + it 'should modify package' do + should contain_package("postgresql-client").with({ + :ensure => 'absent', + :name => 'mypackage', + :tag => 'postgresql', + }) + end + end + + describe 'with no parameters' do + it 'should create package with postgresql tag' do + should contain_package('postgresql-client').with({ + :tag => 'postgresql', + }) + end + end +end diff --git a/modules/postgresql/spec/unit/classes/globals_spec.rb b/modules/postgresql/spec/unit/classes/globals_spec.rb new file mode 100644 index 0000000..f8feb2f --- /dev/null +++ b/modules/postgresql/spec/unit/classes/globals_spec.rb @@ -0,0 +1,29 @@ +require 'spec_helper' + +describe 'postgresql::globals', :type => :class do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + :lsbdistid => 'Debian', + } + end + + describe 'with no parameters' do + it 'should work' do + should contain_class("postgresql::globals") + end + end + + describe 'manage_package_repo => true' do + let(:params) do + { + :manage_package_repo => true, + } + end + it 'should pull in class postgresql::repo' do + should contain_class("postgresql::repo") + end + end +end diff --git a/modules/postgresql/spec/unit/classes/lib/devel_spec.rb b/modules/postgresql/spec/unit/classes/lib/devel_spec.rb new file mode 100644 index 0000000..8c289fc --- /dev/null +++ b/modules/postgresql/spec/unit/classes/lib/devel_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe 'postgresql::lib::devel', :type => :class do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + it { should contain_class("postgresql::lib::devel") } +end diff --git a/modules/postgresql/spec/unit/classes/lib/java_spec.rb b/modules/postgresql/spec/unit/classes/lib/java_spec.rb new file mode 100644 index 0000000..7541bf5 --- /dev/null +++ b/modules/postgresql/spec/unit/classes/lib/java_spec.rb @@ -0,0 +1,40 @@ +require 'spec_helper' + +describe 'postgresql::lib::java', :type => :class do + + describe 'on a debian based os' do + let :facts do { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + it { should contain_package('postgresql-jdbc').with( + :name => 'libpostgresql-jdbc-java', + :ensure => 'present' + )} + end + + describe 'on a redhat based os' do + let :facts do { + :osfamily => 'RedHat', + :operatingsystem => 'RedHat', + :operatingsystemrelease => '6.4', + } + end + it { should contain_package('postgresql-jdbc').with( + :name => 'postgresql-jdbc', + :ensure => 'present' + )} + describe 'when parameters are supplied' do + let :params do + {:package_ensure => 'latest', :package_name => 'somepackage'} + end + it { should contain_package('postgresql-jdbc').with( + :name => 'somepackage', + :ensure => 'latest' + )} + end + end + +end diff --git a/modules/postgresql/spec/unit/classes/lib/python_spec.rb b/modules/postgresql/spec/unit/classes/lib/python_spec.rb new file mode 100644 index 0000000..ab3fd32 --- /dev/null +++ b/modules/postgresql/spec/unit/classes/lib/python_spec.rb @@ -0,0 +1,31 @@ +require 'spec_helper' + +describe 'postgresql::lib::python', :type => :class do + + describe 'on a redhat based os' do + let :facts do { + :osfamily => 'RedHat', + :operatingsystem => 'RedHat', + :operatingsystemrelease => '6.4', + } + end + it { should contain_package('python-psycopg2').with( + :name => 'python-psycopg2', + :ensure => 'present' + )} + end + + describe 'on a debian based os' do + let :facts do { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + it { should contain_package('python-psycopg2').with( + :name => 'python-psycopg2', + :ensure => 'present' + )} + end + +end diff --git a/modules/postgresql/spec/unit/classes/params_spec.rb b/modules/postgresql/spec/unit/classes/params_spec.rb new file mode 100644 index 0000000..730fd10 --- /dev/null +++ b/modules/postgresql/spec/unit/classes/params_spec.rb @@ -0,0 +1,12 @@ +require 'spec_helper' + +describe 'postgresql::params', :type => :class do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + it { should contain_class("postgresql::params") } +end diff --git a/modules/postgresql/spec/unit/classes/repo_spec.rb b/modules/postgresql/spec/unit/classes/repo_spec.rb new file mode 100644 index 0000000..e7e286f --- /dev/null +++ b/modules/postgresql/spec/unit/classes/repo_spec.rb @@ -0,0 +1,18 @@ +require 'spec_helper' + +describe 'postgresql::repo', :type => :class do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + :lsbdistid => 'Debian', + } + end + + describe 'with no parameters' do + it 'should instantiate apt_postgresql_org class' do + should contain_class('postgresql::repo::apt_postgresql_org') + end + end +end diff --git a/modules/postgresql/spec/unit/classes/server/contrib_spec.rb b/modules/postgresql/spec/unit/classes/server/contrib_spec.rb new file mode 100644 index 0000000..9fbab06 --- /dev/null +++ b/modules/postgresql/spec/unit/classes/server/contrib_spec.rb @@ -0,0 +1,42 @@ +require 'spec_helper' + +describe 'postgresql::server::contrib', :type => :class do + let :pre_condition do + "class { 'postgresql::server': }" + end + + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + :kernel => 'Linux', + :concat_basedir => tmpfilename('contrib'), + } + end + + describe 'with parameters' do + let(:params) do + { + :package_name => 'mypackage', + :package_ensure => 'absent', + } + end + + it 'should create package with correct params' do + should contain_package('postgresql-contrib').with({ + :ensure => 'absent', + :name => 'mypackage', + :tag => 'postgresql', + }) + end + end + + describe 'with no parameters' do + it 'should create package with postgresql tag' do + should contain_package('postgresql-contrib').with({ + :tag => 'postgresql', + }) + end + end +end diff --git a/modules/postgresql/spec/unit/classes/server/initdb_spec.rb b/modules/postgresql/spec/unit/classes/server/initdb_spec.rb new file mode 100644 index 0000000..bcf2dbe --- /dev/null +++ b/modules/postgresql/spec/unit/classes/server/initdb_spec.rb @@ -0,0 +1,29 @@ +require 'spec_helper' + +describe 'postgresql::server::initdb', :type => :class do + let (:pre_condition) do + "include postgresql::server" + end + describe 'on RedHat' do + let :facts do + { + :osfamily => 'RedHat', + :operatingsystem => 'CentOS', + :operatingsystemrelease => '6.0', + :concat_basedir => tmpfilename('server'), + } + end + it { should contain_file('/var/lib/pgsql/data').with_ensure('directory') } + end + describe 'on Amazon' do + let :facts do + { + :osfamily => 'RedHat', + :operatingsystem => 'Amazon', + :concat_basedir => tmpfilename('server'), + } + end + it { should contain_file('/var/lib/pgsql9/data').with_ensure('directory') } + end +end + diff --git a/modules/postgresql/spec/unit/classes/server/plperl_spec.rb b/modules/postgresql/spec/unit/classes/server/plperl_spec.rb new file mode 100644 index 0000000..785ed9a --- /dev/null +++ b/modules/postgresql/spec/unit/classes/server/plperl_spec.rb @@ -0,0 +1,45 @@ +require 'spec_helper' + +describe 'postgresql::server::plperl', :type => :class do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + :kernel => 'Linux', + :concat_basedir => tmpfilename('plperl'), + } + end + + let :pre_condition do + "class { 'postgresql::server': }" + end + + describe 'with no parameters' do + it { should contain_class("postgresql::server::plperl") } + it 'should create package' do + should contain_package('postgresql-plperl').with({ + :ensure => 'present', + :tag => 'postgresql', + }) + end + end + + describe 'with parameters' do + let :params do + { + :package_ensure => 'absent', + :package_name => 'mypackage', + } + end + + it { should contain_class("postgresql::server::plperl") } + it 'should create package with correct params' do + should contain_package('postgresql-plperl').with({ + :ensure => 'absent', + :name => 'mypackage', + :tag => 'postgresql', + }) + end + end +end diff --git a/modules/postgresql/spec/unit/classes/server_spec.rb b/modules/postgresql/spec/unit/classes/server_spec.rb new file mode 100644 index 0000000..203eecb --- /dev/null +++ b/modules/postgresql/spec/unit/classes/server_spec.rb @@ -0,0 +1,100 @@ +require 'spec_helper' + +describe 'postgresql::server', :type => :class do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + :concat_basedir => tmpfilename('server'), + :kernel => 'Linux', + } + end + + describe 'with no parameters' do + it { should contain_class("postgresql::params") } + it { should contain_class("postgresql::server") } + it 'should validate connection' do + should contain_postgresql__validate_db_connection('validate_service_is_running') + end + end + + describe 'manage_firewall => true' do + let(:params) do + { + :manage_firewall => true, + :ensure => true, + } + end + + it 'should create firewall rule' do + should contain_firewall("5432 accept - postgres") + end + end + + describe 'ensure => absent' do + let(:params) do + { + :ensure => 'absent', + :datadir => '/my/path', + :xlogdir => '/xlog/path', + } + end + + it 'should make package purged' do + should contain_package('postgresql-server').with({ + :ensure => 'purged', + }) + end + + it 'stop the service' do + should contain_service('postgresqld').with({ + :ensure => false, + }) + end + + it 'should remove datadir' do + should contain_file('/my/path').with({ + :ensure => 'absent', + }) + end + + it 'should remove xlogdir' do + should contain_file('/xlog/path').with({ + :ensure => 'absent', + }) + end + end + + describe 'package_ensure => absent' do + let(:params) do + { + :package_ensure => 'absent', + } + end + + it 'should remove the package' do + should contain_package('postgresql-server').with({ + :ensure => 'purged', + }) + end + + it 'should still enable the service' do + should contain_service('postgresqld').with({ + :ensure => true, + }) + end + end + + describe 'needs_initdb => true' do + let(:params) do + { + :needs_initdb => true, + } + end + + it 'should contain proper initdb exec' do + should contain_exec('postgresql_initdb') + end + end +end diff --git a/modules/postgresql/spec/unit/defines/server/config_entry_spec.rb b/modules/postgresql/spec/unit/defines/server/config_entry_spec.rb new file mode 100644 index 0000000..4c25c67 --- /dev/null +++ b/modules/postgresql/spec/unit/defines/server/config_entry_spec.rb @@ -0,0 +1,23 @@ +require 'spec_helper' + +describe 'postgresql::server::config_entry', :type => :define do + let :facts do + { + :osfamily => 'RedHat', + :operatingsystem => 'RedHat', + :operatingsystemrelease => '6.4', + } + end + + let(:title) { 'config_entry'} + + let :target do + tmpfilename('postgresql_conf') + end + + context "syntax check" do + let(:params) { { :ensure => 'present'} } + it { should contain_postgresql__server__config_entry('config_entry') } + end +end + diff --git a/modules/postgresql/spec/unit/defines/server/database_grant_spec.rb b/modules/postgresql/spec/unit/defines/server/database_grant_spec.rb new file mode 100644 index 0000000..2e481df --- /dev/null +++ b/modules/postgresql/spec/unit/defines/server/database_grant_spec.rb @@ -0,0 +1,26 @@ +require 'spec_helper' + +describe 'postgresql::server::database_grant', :type => :define do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + + let :title do + 'test' + end + + let :params do + { + :privilege => 'ALL', + :db => 'test', + :role => 'test', + } + end + + it { should contain_postgresql__server__database_grant('test') } + it { should contain_postgresql__server__grant('database:test') } +end diff --git a/modules/postgresql/spec/unit/defines/server/database_spec.rb b/modules/postgresql/spec/unit/defines/server/database_spec.rb new file mode 100644 index 0000000..a703827 --- /dev/null +++ b/modules/postgresql/spec/unit/defines/server/database_spec.rb @@ -0,0 +1,16 @@ +require 'spec_helper' + +describe 'postgresql::server::database', :type => :define do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + let :title do + 'test' + end + it { should contain_postgresql__server__database('test') } + it { should contain_postgresql_psql("Check for existence of db 'test'") } +end diff --git a/modules/postgresql/spec/unit/defines/server/db_spec.rb b/modules/postgresql/spec/unit/defines/server/db_spec.rb new file mode 100644 index 0000000..60fa9a9 --- /dev/null +++ b/modules/postgresql/spec/unit/defines/server/db_spec.rb @@ -0,0 +1,28 @@ +require 'spec_helper' + +describe 'postgresql::server::db', :type => :define do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + + let :title do + 'test' + end + + let :params do + { + :user => 'test', + :password => 'test', + :owner => 'tester', + } + end + + it { should contain_postgresql__server__db('test') } + it { should contain_postgresql__server__database('test').with_owner('tester') } + it { should contain_postgresql__server__role('test') } + it { should contain_postgresql__server__database_grant('GRANT test - ALL - test') } +end diff --git a/modules/postgresql/spec/unit/defines/server/grant_spec.rb b/modules/postgresql/spec/unit/defines/server/grant_spec.rb new file mode 100644 index 0000000..43eeb8c --- /dev/null +++ b/modules/postgresql/spec/unit/defines/server/grant_spec.rb @@ -0,0 +1,24 @@ +require 'spec_helper' + +describe 'postgresql::server::grant', :type => :define do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + + let :title do + 'test' + end + + let :params do + { + :db => 'test', + :role => 'test', + } + end + + it { should contain_postgresql__server__grant('test') } +end diff --git a/modules/postgresql/spec/unit/defines/server/pg_hba_rule_spec.rb b/modules/postgresql/spec/unit/defines/server/pg_hba_rule_spec.rb new file mode 100644 index 0000000..b01e338 --- /dev/null +++ b/modules/postgresql/spec/unit/defines/server/pg_hba_rule_spec.rb @@ -0,0 +1,161 @@ +require 'spec_helper' + +describe 'postgresql::server::pg_hba_rule', :type => :define do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + :concat_basedir => tmpfilename('pg_hba'), + } + end + let :title do + 'test' + end + let :target do + tmpfilename('pg_hba_rule') + end + + context 'test template 1' do + let :params do + { + :type => 'host', + :database => 'all', + :user => 'all', + :address => '1.1.1.1/24', + :auth_method => 'md5', + :target => target, + } + end + it do + content = param('concat::fragment', 'pg_hba_rule_test', 'content') + content.should =~ /host\s+all\s+all\s+1\.1\.1\.1\/24\s+md5/ + end + end + + context 'test template 2' do + let :params do + { + :type => 'local', + :database => 'all', + :user => 'all', + :auth_method => 'ident', + :target => target, + } + end + it do + content = param('concat::fragment', 'pg_hba_rule_test', 'content') + content.should =~ /local\s+all\s+all\s+ident/ + end + end + + context 'test template 3' do + let :params do + { + :type => 'host', + :database => 'all', + :user => 'all', + :address => '0.0.0.0/0', + :auth_method => 'ldap', + :auth_option => 'foo=bar', + :target => target, + } + end + it do + content = param('concat::fragment', 'pg_hba_rule_test', 'content') + content.should =~ /host\s+all\s+all\s+0\.0\.0\.0\/0\s+ldap\s+foo=bar/ + end + end + + context 'validation' do + context 'validate type test 1' do + let :params do + { + :type => 'invalid', + :database => 'all', + :user => 'all', + :address => '0.0.0.0/0', + :auth_method => 'ldap', + :target => target, + } + end + it 'should fail parsing when type is not valid' do + expect {subject}.to raise_error(Puppet::Error, + /The type you specified \[invalid\] must be one of/) + end + end + + context 'validate auth_method' do + let :params do + { + :type => 'local', + :database => 'all', + :user => 'all', + :address => '0.0.0.0/0', + :auth_method => 'invalid', + :target => target, + } + end + + it 'should fail parsing when auth_method is not valid' do + expect {subject}.to raise_error(Puppet::Error, + /The auth_method you specified \[invalid\] must be one of/) + end + end + + context 'validate unsupported auth_method' do + let :pre_condition do + <<-EOS + class { 'postgresql::globals': + version => '9.0', + } + class { 'postgresql::server': } + EOS + end + + let :params do + { + :type => 'local', + :database => 'all', + :user => 'all', + :address => '0.0.0.0/0', + :auth_method => 'peer', + :target => target, + } + end + + it 'should fail parsing when auth_method is not valid' do + expect {subject}.to raise_error(Puppet::Error, + /The auth_method you specified \[peer\] must be one of: trust, reject, md5, sha1, password, gss, sspi, krb5, ident, ldap, radius, cert, pam/) + end + end + + context 'validate supported auth_method' do + let :pre_condition do + <<-EOS + class { 'postgresql::globals': + version => '9.2', + } + class { 'postgresql::server': } + EOS + end + + let :params do + { + :type => 'local', + :database => 'all', + :user => 'all', + :address => '0.0.0.0/0', + :auth_method => 'peer', + :target => target, + } + end + + it do + content = param('concat::fragment', 'pg_hba_rule_test', 'content') + content.should =~ /local\s+all\s+all\s+0\.0\.0\.0\/0\s+peer/ + end + end + + end +end diff --git a/modules/postgresql/spec/unit/defines/server/role_spec.rb b/modules/postgresql/spec/unit/defines/server/role_spec.rb new file mode 100644 index 0000000..a50ca14 --- /dev/null +++ b/modules/postgresql/spec/unit/defines/server/role_spec.rb @@ -0,0 +1,23 @@ +require 'spec_helper' + +describe 'postgresql::server::role', :type => :define do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + + let :title do + 'test' + end + + let :params do + { + :password_hash => 'test', + } + end + + it { should contain_postgresql__server__role('test') } +end diff --git a/modules/postgresql/spec/unit/defines/server/table_grant_spec.rb b/modules/postgresql/spec/unit/defines/server/table_grant_spec.rb new file mode 100644 index 0000000..15136a7 --- /dev/null +++ b/modules/postgresql/spec/unit/defines/server/table_grant_spec.rb @@ -0,0 +1,27 @@ +require 'spec_helper' + +describe 'postgresql::server::table_grant', :type => :define do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + + let :title do + 'test' + end + + let :params do + { + :privilege => 'ALL', + :db => 'test', + :role => 'test', + :table => 'foo', + } + end + + it { should contain_postgresql__server__table_grant('test') } + it { should contain_postgresql__server__grant('table:test') } +end diff --git a/modules/postgresql/spec/unit/defines/server/tablespace_spec.rb b/modules/postgresql/spec/unit/defines/server/tablespace_spec.rb new file mode 100644 index 0000000..eb29f1e --- /dev/null +++ b/modules/postgresql/spec/unit/defines/server/tablespace_spec.rb @@ -0,0 +1,23 @@ +require 'spec_helper' + +describe 'postgresql::server::tablespace', :type => :define do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + + let :title do + 'test' + end + + let :params do + { + :location => '/srv/data/foo', + } + end + + it { should contain_postgresql__server__tablespace('test') } +end diff --git a/modules/postgresql/spec/unit/defines/validate_db_connection_spec.rb b/modules/postgresql/spec/unit/defines/validate_db_connection_spec.rb new file mode 100644 index 0000000..7a248f6 --- /dev/null +++ b/modules/postgresql/spec/unit/defines/validate_db_connection_spec.rb @@ -0,0 +1,35 @@ +require 'spec_helper' + +describe 'postgresql::validate_db_connection', :type => :define do + let :facts do + { + :osfamily => 'Debian', + :operatingsystem => 'Debian', + :operatingsystemrelease => '6.0', + } + end + + let :title do + 'test' + end + + describe 'should work with only default parameters' do + it { should contain_postgresql__validate_db_connection('test') } + end + + describe 'should work with all parameters' do + let :params do + { + :database_host => 'test', + :database_name => 'test', + :database_password => 'test', + :database_username => 'test', + :database_port => 5432, + :run_as => 'postgresq', + :sleep => 4, + :tries => 30, + } + end + it { should contain_postgresql__validate_db_connection('test') } + end +end diff --git a/modules/postgresql/spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb b/modules/postgresql/spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb new file mode 100644 index 0000000..0ac1d1b --- /dev/null +++ b/modules/postgresql/spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb @@ -0,0 +1,137 @@ +require 'spec_helper' + +describe 'postgresql_acls_to_resources_hash', :type => :puppet_function do + context 'individual transform tests' do + it do + input = 'local all postgres ident' + result = { + "postgresql class generated rule test 0"=>{ + "type"=>"local", + "database"=>"all", + "user"=>"postgres", + "auth_method"=>"ident", + "order"=>"100", + }, + } + + should run.with_params([input], 'test', 100).and_return(result) + end + + it do + input = 'local all root ident' + result = { + "postgresql class generated rule test 0"=>{ + "type"=>"local", + "database"=>"all", + "user"=>"root", + "auth_method"=>"ident", + "order"=>"100", + }, + } + + should run.with_params([input], 'test', 100).and_return(result) + end + + it do + input_array = [ + 'local all all ident', + ] + result = { + "postgresql class generated rule test 0"=>{ + "type"=>"local", + "database"=>"all", + "user"=>"all", + "auth_method"=>"ident", + "order"=>"100", + }, + } + + should run.with_params(input_array, 'test', 100).and_return(result) + end + + it do + input = 'host all all 127.0.0.1/32 md5' + result = { + "postgresql class generated rule test 0"=>{ + "type"=>"host", + "database"=>"all", + "user"=>"all", + "address"=>"127.0.0.1/32", + "auth_method"=>"md5", + "order"=>"100", + }, + } + + should run.with_params([input], 'test', 100).and_return(result) + end + + it do + input = 'host all all 0.0.0.0/0 md5' + result = { + "postgresql class generated rule test 0"=>{ + "type"=>"host", + "database"=>"all", + "user"=>"all", + "address"=>"0.0.0.0/0", + "auth_method"=>"md5", + "order"=>"100", + }, + } + + should run.with_params([input], 'test', 100).and_return(result) + end + + it do + input = 'host all all ::1/128 md5' + result = { + "postgresql class generated rule test 0"=>{ + "type"=>"host", + "database"=>"all", + "user"=>"all", + "address"=>"::1/128", + "auth_method"=>"md5", + "order"=>"100", + }, + } + + should run.with_params([input], 'test', 100).and_return(result) + end + + it do + input = 'host all all 1.1.1.1 255.255.255.0 md5' + result = { + "postgresql class generated rule test 0"=>{ + "type"=>"host", + "database"=>"all", + "user"=>"all", + "address"=>"1.1.1.1 255.255.255.0", + "auth_method"=>"md5", + "order"=>"100", + }, + } + + should run.with_params([input], 'test', 100).and_return(result) + end + + it do + input = 'host all all 1.1.1.1 255.255.255.0 ldap ldapserver=ldap.example.net ldapprefix="cn=" ldapsuffix=", dc=example, dc=net"' + result = { + "postgresql class generated rule test 0"=>{ + "type"=>"host", + "database"=>"all", + "user"=>"all", + "address"=>"1.1.1.1 255.255.255.0", + "auth_method"=>"ldap", + "auth_option"=>"ldapserver=ldap.example.net ldapprefix=\"cn=\" ldapsuffix=\", dc=example, dc=net\"", + "order"=>"100", + }, + } + + should run.with_params([input], 'test', 100).and_return(result) + end + end + + it 'should return an empty hash when input is empty array' do + should run.with_params([], 'test', 100).and_return({}) + end +end diff --git a/modules/postgresql/spec/unit/functions/postgresql_escape_spec.rb b/modules/postgresql/spec/unit/functions/postgresql_escape_spec.rb new file mode 100644 index 0000000..ee1157d --- /dev/null +++ b/modules/postgresql/spec/unit/functions/postgresql_escape_spec.rb @@ -0,0 +1,10 @@ +require 'spec_helper' + +describe 'postgresql_escape', :type => :puppet_function do + it { should run.with_params('foo'). + and_return('$$foo$$') } +end +describe 'postgresql_escape', :type => :puppet_function do + it { should run.with_params('fo$$o'). + and_return('$ed$fo$$o$ed$') } +end diff --git a/modules/postgresql/spec/unit/functions/postgresql_password_spec.rb b/modules/postgresql/spec/unit/functions/postgresql_password_spec.rb new file mode 100644 index 0000000..0d043f8 --- /dev/null +++ b/modules/postgresql/spec/unit/functions/postgresql_password_spec.rb @@ -0,0 +1,6 @@ +require 'spec_helper' + +describe 'postgresql_password', :type => :puppet_function do + it { should run.with_params('foo', 'bar'). + and_return('md596948aad3fcae80c08a35c9b5958cd89') } +end diff --git a/modules/postgresql/spec/unit/provider/postgresql_conf/parsed_spec.rb b/modules/postgresql/spec/unit/provider/postgresql_conf/parsed_spec.rb new file mode 100644 index 0000000..2e2bfbe --- /dev/null +++ b/modules/postgresql/spec/unit/provider/postgresql_conf/parsed_spec.rb @@ -0,0 +1,112 @@ +require 'spec_helper' +require "tempfile" + +provider_class = Puppet::Type.type(:postgresql_conf).provider(:parsed) + +describe provider_class do + let(:title) { 'postgresql_conf' } + let(:provider) { + conf_class = Puppet::Type.type(:postgresql_conf) + provider = conf_class.provider(:parsed) + conffile = tmpfilename('postgresql.conf') + provider.any_instance.stubs(:target).returns conffile + provider + } + + before do + end + + after :each do + provider.initvars + end + + describe "simple configuration that should be allowed" do + it "should parse a simple ini line" do + provider.parse_line("listen_addreses = '*'").should == + { :name=>"listen_addreses", :value=>"*", :comment=>nil, :record_type=>:parsed } + end + + it "should parse a simple ini line (2)" do + provider.parse_line(" listen_addreses = '*'").should == + { :name=>"listen_addreses", :value=>"*", :comment=>nil, :record_type=>:parsed } + end + + it "should parse a simple ini line (3)" do + provider.parse_line("listen_addreses = '*' # dont mind me").should == + { :name=>"listen_addreses", :value=>"*", :comment=>"dont mind me", :record_type=>:parsed } + end + + it "should parse a comment" do + provider.parse_line("# dont mind me").should == + { :line=>"# dont mind me", :record_type=>:comment } + end + + it "should parse a comment (2)" do + provider.parse_line(" \t# dont mind me").should == + { :line=>" \t# dont mind me", :record_type=>:comment } + end + + it "should allow includes" do + provider.parse_line("include puppetextra").should == + { :name=>"include", :value=>"puppetextra", :comment=>nil, :record_type=>:parsed } + end + + it "should allow numbers thorugh without quotes" do + provider.parse_line("wal_keep_segments = 32").should == + { :name=>"wal_keep_segments", :value=>"32", :comment=>nil, :record_type=>:parsed } + end + + it "should allow blanks thorugh " do + provider.parse_line("").should == + { :line=>"", :record_type=>:blank } + end + + it "should parse keys with dots " do + provider.parse_line("auto_explain.log_min_duration = 1ms").should == + { :name => "auto_explain.log_min_duration", :value => "1ms", :comment => nil, :record_type => :parsed } + end + end + + describe "configuration that should be set" do + it "should set comment lines" do + provider.to_line({ :line=>"# dont mind me", :record_type=>:comment }).should == + '# dont mind me' + end + + it "should set blank lines" do + provider.to_line({ :line=>"", :record_type=>:blank }).should == + '' + end + + it "should set simple configuration" do + provider.to_line({:name=>"listen_addresses", :value=>"*", :comment=>nil, :record_type=>:parsed }).should == + "listen_addresses = '*'" + end + + it "should set simple configuration with period in name" do + provider.to_line({:name => "auto_explain.log_min_duration", :value => '100ms', :comment => nil, :record_type => :parsed }).should == + "auto_explain.log_min_duration = 100ms" + end + + it "should set simple configuration even with comments" do + provider.to_line({:name=>"listen_addresses", :value=>"*", :comment=>'dont mind me', :record_type=>:parsed }).should == + "listen_addresses = '*' # dont mind me" + end + + it 'should quote includes' do + provider.to_line( {:name=>"include", :value=>"puppetextra", :comment=>nil, :record_type=>:parsed }).should == + "include 'puppetextra'" + end + + it 'should quote multiple words' do + provider.to_line( {:name=>"archive_command", :value=>"rsync up", :comment=>nil, :record_type=>:parsed }).should == + "archive_command = 'rsync up'" + end + + it 'shouldn\'t quote numbers' do + provider.to_line( {:name=>"wal_segments", :value=>"32", :comment=>nil, :record_type=>:parsed }).should == + "wal_segments = 32" + end + end +end + diff --git a/modules/postgresql/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb b/modules/postgresql/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb new file mode 100644 index 0000000..325e3db --- /dev/null +++ b/modules/postgresql/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb @@ -0,0 +1,140 @@ +require 'spec_helper' + +describe Puppet::Type.type(:postgresql_psql).provider(:ruby) do + let(:name) { 'rspec psql test' } + let(:resource) do + Puppet::Type.type(:postgresql_psql).new({ :name => name, :provider => :ruby }.merge attributes) + end + + let(:provider) { resource.provider } + + context("#run_sql_command") do + describe "with default attributes" do + let(:attributes) do { :db => 'spec_db' } end + + it "executes with the given psql_path on the given DB" do + expect(provider).to receive(:run_command).with(['psql', '-d', + attributes[:db], '-t', '-c', 'SELECT something'], 'postgres', + 'postgres') + + provider.run_sql_command("SELECT something") + end + end + describe "with psql_path and db" do + let(:attributes) do { + :psql_path => '/opt/postgres/psql', + :psql_user => 'spec_user', + :psql_group => 'spec_group', + :cwd => '/spec', + :db => 'spec_db' + } end + + it "executes with the given psql_path on the given DB" do + expect(Dir).to receive(:chdir).with(attributes[:cwd]).and_yield + expect(provider).to receive(:run_command).with([attributes[:psql_path], + '-d', attributes[:db], '-t', '-c', 'SELECT something'], + attributes[:psql_user], attributes[:psql_group]) + + provider.run_sql_command("SELECT something") + end + end + describe "with search_path string" do + let(:attributes) do { + :search_path => "schema1" + } end + + it "executes with the given search_path" do + expect(provider).to receive(:run_command).with(['psql', '-t', '-c', + 'set search_path to schema1; SELECT something'], + 'postgres', 'postgres') + + provider.run_sql_command("SELECT something") + end + end + describe "with search_path array" do + let(:attributes) do { + :search_path => ['schema1','schema2'], + } end + + it "executes with the given search_path" do + expect(provider).to receive(:run_command).with(['psql', '-t', '-c', + 'set search_path to schema1,schema2; SELECT something'], + 'postgres', + 'postgres' + ) + + provider.run_sql_command("SELECT something") + end + end + + end + + context("#command") do + context "when unless is specified" do + [:true, :false, true, false].each do |refresh| + context "and refreshonly is #{refresh}" do + let(:attributes) { { + :command => 'SELECT something', + :db => 'spec_db', + :unless => 'SELECT something', + :refreshonly => refresh + } } + + it "does not fail when the status is successful" do + expect(provider).to receive(:run_unless_sql_command).and_return ["1 row returned", 0] + provider.command + end + + it "returns the given command when rows are returned" do + expect(provider).to receive(:run_unless_sql_command).and_return ["1 row returned", 0] + expect(provider.command).to eq("SELECT something") + end + + it "does not return the given command when no rows are returned" do + expect(provider).to receive(:run_unless_sql_command).and_return ["0 rows returned", 0] + expect(provider.command).to_not eq("SELECT something") + end + + it "raises an error when the sql command fails" do + allow(provider).to receive(:run_unless_sql_command).and_return ["Something went wrong", 1] + expect { provider.command }.to raise_error(Puppet::Error, /Something went wrong/) + end + end + end + end + + context "when unless is not specified" do + context "and refreshonly is true" do + let(:attributes) do { + :command => 'SELECT something', + :db => 'spec_db', + :refreshonly => :true + } end + it "does not run unless sql command" do + expect(provider).to_not receive(:run_unless_sql_command) + provider.command + end + + it "returns the given command do disable sync" do + expect(provider.command).to eq("SELECT something") + end + end + + context "and refreshonly is false" do + let(:attributes) do { + :command => 'SELECT something', + :db => 'spec_db', + :refreshonly => :false + } end + it "does not run unless sql command" do + expect(provider).to_not receive(:run_unless_sql_command) + provider.command + end + + it "does not return the command so as to enable sync" do + expect(provider.command).to_not eq("SELECT something") + end + end + end + end +end diff --git a/modules/postgresql/spec/unit/puppet/type/postgresql_psql_spec.rb b/modules/postgresql/spec/unit/puppet/type/postgresql_psql_spec.rb new file mode 100644 index 0000000..e89c05f --- /dev/null +++ b/modules/postgresql/spec/unit/puppet/type/postgresql_psql_spec.rb @@ -0,0 +1,92 @@ +require 'spec_helper' + +describe Puppet::Type.type(:postgresql_psql), "when validating attributes" do + [:name, :unless, :db, :psql_path, :psql_user, :psql_group].each do |attr| + it "should have a #{attr} parameter" do + expect(Puppet::Type.type(:postgresql_psql).attrtype(attr)).to eq(:param) + end + end + + [:command].each do |attr| + it "should have a #{attr} property" do + expect(Puppet::Type.type(:postgresql_psql).attrtype(attr)).to eq(:property) + end + end +end + +describe Puppet::Type.type(:postgresql_psql), :unless => Puppet.features.microsoft_windows? do + subject do + Puppet::Type.type(:postgresql_psql).new({:name => 'rspec'}.merge attributes) + end + + describe "available attributes" do + { + :name => "rspec", + :command => "SELECT stuff", + :unless => "SELECT other,stuff", + :db => "postgres", + :psql_path => "/bin/false", + :psql_user => "postgres", + :psql_group => "postgres", + :cwd => "/var/lib", + :refreshonly => :true, + :search_path => [ "schema1", "schema2"] + }.each do |attr, value| + context attr do + let(:attributes) do { attr => value } end + its([attr]) { should == value } + end + end + + context "default values" do + let(:attributes) do {} end + its([:psql_path]) { should eq("psql") } + its([:psql_user]) { should eq("postgres") } + its([:psql_group]) { should eq("postgres") } + its([:cwd]) { should eq("/tmp") } + its(:refreshonly?) { should be_false } + end + end + + describe "#refreshonly" do + [true, :true].each do |refreshonly| + context "=> #{refreshonly.inspect}" do + let(:attributes) do { :refreshonly => refreshonly } end + it "has a value of true" do + expect(subject.refreshonly?).to be_true + end + it "will not enforce command on sync because refresh() will be called" do + expect(subject.provider).to_not receive(:command=) + subject.property(:command).sync + end + end + end + + [false, :false].each do |refreshonly| + context "=> #{refreshonly.inspect}" do + let(:attributes) do { :refreshonly => refreshonly } end + it "has a value of false" do + expect(subject.refreshonly?).to be_false + end + it "will enforce command on sync because refresh() will not be called" do + expect(subject.provider).to receive(:command=) + subject.property(:command).sync + end + end + end + end + + ## If we refresh the resource, the command should always be run regardless of + ## refreshonly + describe "when responding to refresh" do + [true, :true, false, :false].each do |refreshonly| + context "with refreshonly => #{refreshonly.inspect}" do + let(:attributes) do { :refreshonly => refreshonly } end + it "will enforce command on sync" do + expect(subject.provider).to receive(:command=) + subject.refresh + end + end + end + end +end diff --git a/modules/postgresql/spec/unit/type/postgresql_conf_spec.rb b/modules/postgresql/spec/unit/type/postgresql_conf_spec.rb new file mode 100644 index 0000000..4524203 --- /dev/null +++ b/modules/postgresql/spec/unit/type/postgresql_conf_spec.rb @@ -0,0 +1,50 @@ +#! /usr/bin/env ruby +require 'spec_helper' + +describe Puppet::Type.type(:postgresql_conf) do + before do + @provider_class = described_class.provide(:simple) { mk_resource_methods } + @provider_class.stubs(:suitable?).returns true + described_class.stubs(:defaultprovider).returns @provider_class + end + + describe "namevar validation" do + it "should have :name as its namevar" do + described_class.key_attributes.should == [:name] + end + it "should not invalid names" do + expect { described_class.new(:name => 'foo bar') }.to raise_error(Puppet::Error, /Invalid value/) + end + it "should allow dots in names" do + expect { described_class.new(:name => 'foo.bar') }.to_not raise_error + end + end + + describe "when validating attributes" do + [:name, :provider].each do |param| + it "should have a #{param} parameter" do + described_class.attrtype(param).should == :param + end + end + + [:value, :target].each do |property| + it "should have a #{property} property" do + described_class.attrtype(property).should == :property + end + end + end + + describe "when validating values" do + describe "ensure" do + it "should support present as a value for ensure" do + expect { described_class.new(:name => 'foo', :ensure => :present) }.to_not raise_error + end + it "should support absent as a value for ensure" do + expect { described_class.new(:name => 'foo', :ensure => :absent) }.to_not raise_error + end + it "should not support other values" do + expect { described_class.new(:name => 'foo', :ensure => :foo) }.to raise_error(Puppet::Error, /Invalid value/) + end + end + end +end diff --git a/modules/postgresql/templates/pg_hba_rule.conf b/modules/postgresql/templates/pg_hba_rule.conf new file mode 100644 index 0000000..af54db5 --- /dev/null +++ b/modules/postgresql/templates/pg_hba_rule.conf @@ -0,0 +1,5 @@ + +# Rule Name: <%=@name%> +# Description: <%=@description%> +# Order: <%=@order%> +<%=@type%> <%=@database%> <%=@user%> <%=@address%> <%=@auth_method%> <%=@auth_option%> diff --git a/modules/rhizomatica_base_system/.project b/modules/rhizomatica_base_system/.project new file mode 100644 index 0000000..df3089a --- /dev/null +++ b/modules/rhizomatica_base_system/.project @@ -0,0 +1,23 @@ + + + rhizomatica_base_system + + + + + + org.eclipse.xtext.ui.shared.xtextBuilder + + + + + com.puppetlabs.geppetto.pp.dsl.ui.modulefileBuilder + + + + + + com.puppetlabs.geppetto.pp.dsl.ui.puppetNature + org.eclipse.xtext.ui.shared.xtextNature + + diff --git a/modules/rhizomatica_base_system/Modulefile b/modules/rhizomatica_base_system/Modulefile new file mode 100644 index 0000000..3b49bf2 --- /dev/null +++ b/modules/rhizomatica_base_system/Modulefile @@ -0,0 +1,11 @@ +name 'rhizomatica_base_system' +version '0.1.0' +source '' +author '' +license '' +summary '' +description '' +project_page '' + +## Add dependencies, if any: +# dependency 'username/name', '>= 1.2.0' diff --git a/modules/rhizomatica_base_system/README.markdown b/modules/rhizomatica_base_system/README.markdown new file mode 100644 index 0000000..e618b5e --- /dev/null +++ b/modules/rhizomatica_base_system/README.markdown @@ -0,0 +1,3 @@ +# rhizomatica_base_system # + +This is the rhizomatica_base_system module. It provides... diff --git a/modules/rhizomatica_base_system/Rakefile b/modules/rhizomatica_base_system/Rakefile new file mode 100644 index 0000000..14f1c24 --- /dev/null +++ b/modules/rhizomatica_base_system/Rakefile @@ -0,0 +1,2 @@ +require 'rubygems' +require 'puppetlabs_spec_helper/rake_tasks' diff --git a/modules/rhizomatica_base_system/manifests/init.pp b/modules/rhizomatica_base_system/manifests/init.pp new file mode 100644 index 0000000..58e25f2 --- /dev/null +++ b/modules/rhizomatica_base_system/manifests/init.pp @@ -0,0 +1,120 @@ +# Class: rhizomatica_base_system +# +# This module manages rhizomatica_base_system +# +# Parameters: none +# +# Actions: +# +# Requires: see Modulefile +# +# Sample Usage: +# +class rhizomatica_base_system { + + $vpn_address = hiera('rhizo::vpn_address') + $postgresql_password = hiera('rhizo::postgresql_password') + $smsc_password= hiera('rhizo::smsc_password') + $kannel_admin_password = ('rhizo::kannel_admin_password') + $kannel_sendsms_password = hiera('rhizo::kannel_sendsms_password') + + + include 'ntp' + include 'kannel' + + class { 'apt': } + + apt::source { 'rhizomatica': + location => 'http://dev.rhizomatica.org/ubuntu/', + release => 'precise', + repos => 'main', + include_src => false, + require => File['/etc/apt/apt.conf.d/90unsigned'], + } + + apt::source { 'mosh': + location => 'http://ppa.launchpad.net/keithw/mosh/ubuntu', + release => 'precise', + repos => 'main', + key => '7BF6DFCD', + include_src => false, + require => File['/etc/apt/apt.conf.d/90unsigned'], + } + + file { '/etc/apt/apt.conf.d/90unsigned': + ensure => present, + content => 'APT::Get::AllowUnauthenticated "true";', + } + +# file { '/var/rhizomatica': +# ensure => directory, +# } + + file { '/var/www/rmai': + ensure => link, + target => '/var/rhizomatica/rmai', + } + + class { 'postgresql::globals': + manage_package_repo => true, + version => '9.3', + }-> + class { 'postgresql::server': + } + + postgresql::server::db { 'rhizomatica': + user => 'rhizomatica', + password => postgresql_password('rhizomatica', $postgresql_password), + } + + package { 'openvpn': + ensure => installed, + } + + package { 'lm-sensors': + ensure => installed, + } + + class { 'riak': + version => '1.4.7-1', + template => 'rhizomatica_base_system/app.config.erb', + vmargs_template => 'rhizomatica_base_system/vm.args.erb', + } + + class { 'python': + version => 'system', + pip => true, + dev => true, + } + + python::pip { 'riak': + ensure => present, + } + + package { ['apache2','libapache2-mod-php5', 'rrdtool', 'python-twisted-web', 'python-psycopg2', 'python-pysqlite2', + 'php5', 'php5-pgsql', 'php5-curl', 'python-corepost']: + ensure => installed, + } + + package { ['freeswitch', 'freeswitch-lang-en', 'freeswitch-mod-amr', 'freeswitch-mod-amrwb', 'freeswitch-mod-b64', + 'freeswitch-mod-bv', 'freeswitch-mod-cdr-pg-csv', 'freeswitch-mod-cluechoo', 'freeswitch-mod-commands', + 'freeswitch-mod-conference', 'freeswitch-mod-console', 'freeswitch-mod-db', 'freeswitch-mod-dialplan-asterisk', + 'freeswitch-mod-dialplan-xml', 'freeswitch-mod-dptools', 'freeswitch-mod-enum', 'freeswitch-mod-esf', + 'freeswitch-mod-event-socket','freeswitch-mod-expr', 'freeswitch-mod-fifo','freeswitch-mod-fsv', + 'freeswitch-mod-g723-1', 'freeswitch-mod-g729', 'freeswitch-mod-h26x', 'freeswitch-mod-hash', + 'freeswitch-mod-httapi', 'freeswitch-mod-local-stream', 'freeswitch-mod-logfile', 'freeswitch-mod-loopback', + 'freeswitch-mod-lua', 'freeswitch-mod-native-file', 'freeswitch-mod-python', 'freeswitch-mod-say-en', + 'freeswitch-mod-say-es', 'freeswitch-mod-sms', 'freeswitch-mod-sndfile', 'freeswitch-mod-sofia', + 'freeswitch-mod-spandsp', 'freeswitch-mod-speex', 'freeswitch-mod-syslog', 'freeswitch-mod-tone-stream', + 'freeswitch-mod-voicemail', 'freeswitch-mod-voicemail-ivr', 'freeswitch-mod-vp8', 'freeswitch-mod-xml-cdr', + 'freeswitch-sysvinit', 'libfreeswitch1']: + ensure => installed, + require => [ Apt::Source['rhizomatica'], File['/etc/apt/apt.conf.d/90unsigned'] ], + } + + package { ['osmocom-nitb', 'osmocom-nitb-dbg']: + ensure => installed, + require => Apt::Source['rhizomatica'], + } + +} diff --git a/modules/rhizomatica_base_system/metadata.json b/modules/rhizomatica_base_system/metadata.json new file mode 100644 index 0000000..e5711f8 --- /dev/null +++ b/modules/rhizomatica_base_system/metadata.json @@ -0,0 +1,13 @@ +{ + "name": "rhizomatica_base_system", + "version": "0.1.0", + "summary": "", + "author": "", + "description": "", + "dependencies": [], + "types": [], + "checksums": {}, + "source": "", + "project_page": "", + "license": "" +} diff --git a/modules/rhizomatica_base_system/spec/spec.opts b/modules/rhizomatica_base_system/spec/spec.opts new file mode 100644 index 0000000..91cd642 --- /dev/null +++ b/modules/rhizomatica_base_system/spec/spec.opts @@ -0,0 +1,6 @@ +--format +s +--colour +--loadby +mtime +--backtrace diff --git a/modules/rhizomatica_base_system/spec/spec_helper.rb b/modules/rhizomatica_base_system/spec/spec_helper.rb new file mode 100644 index 0000000..dc7e9f4 --- /dev/null +++ b/modules/rhizomatica_base_system/spec/spec_helper.rb @@ -0,0 +1,2 @@ +require 'rubygems' +require 'puppetlabs_spec_helper/module_spec_helper' diff --git a/modules/rhizomatica_base_system/templates/app.config.erb b/modules/rhizomatica_base_system/templates/app.config.erb new file mode 100644 index 0000000..f91295d --- /dev/null +++ b/modules/rhizomatica_base_system/templates/app.config.erb @@ -0,0 +1,85 @@ +[ + {bitcask, [ + {data_root, "/var/lib/riak/bitcask"} + ]}, + {eleveldb, [ + {data_root, "/var/lib/riak/leveldb"} + ]}, + {kernel, [ + {inet_dist_listen_max, 7999}, + {inet_dist_listen_min, 6000} + ]}, + {lager, [ + {crash_log, "/var/log/riak/crash.log"}, + {crash_log_count, 5}, + {crash_log_date, "$D0"}, + {crash_log_msg_side, 65536}, + {crash_log_size, 10485760}, + {error_logger_redirect, true}, + {handlers, [ + {lager_file_backend, [ + {"/var/log/riak/error.log", error, 10485760, "$D0", 5}, + {"/var/log/riak/console.log", info, 10485760, "$D0", 5} + ]} + ]} + ]}, + {merge_index, [ + {buffer_rollover_size, 1048576}, + {data_root, "/var/lib/riak/merge_index"}, + {max_compact_segments, 20} + ]}, + {riak_api, [ + {pb_ip, "127.0.0.1"}, + {pb_port, 8087} + ]}, + {riak_control, [ + {admin, true}, + {auth, "userlist"}, + {enabled, false}, + {userlist, {"user", "pass"}} + ]}, + {riak_core, [ + {dtrace_support, false}, + {handoff_port, 8099}, + {http, [ + {"127.0.0.1", 8098} + ]}, + {platform_bin_dir, "/usr/sbin"}, + {platform_data_dir, "/var/lib/riak"}, + {platform_etc_dir, "/etc/riak"}, + {platform_lib_dir, "/usr/lib/riak"}, + {platform_log_dir, "/var/log/riak"}, + {ring_creation_size, 64}, + {ring_state_dir, "/var/lib/riak/ring"} + ]}, + {riak_kv, [ + {hook_js_vm_count, 2}, + {http_url_encoding, on}, + {js_max_vm_mem, 8}, + {js_thread_stack, 16}, + {legacy_keylisting, false}, + {listkeys_backpressure, true}, + {map_js_vm_count, 8}, + {mapred_2i_pipe, true}, + {mapred_name, "mapred"}, + {mapred_system, "pipe"}, + {reduce_js_vm_count, 6}, + {storage_backend, riak_kv_bitcask_backend}, + {vnode_vclocks, true} + ]}, + {riak_search, [ + {enabled, false} + ]}, + {riak_sysmon, [ + {busy_dist_port, true}, + {busy_port, true}, + {gc_ms_limit, 100}, + {heap_word_limit, 40111000}, + {post_limit, 2}, + {process_limit, 20} + ]}, + {sasl, [ + {sasl_error_logger, false}, + {utc_log, true} + ]} +]. \ No newline at end of file diff --git a/modules/rhizomatica_base_system/templates/vm.args.erb b/modules/rhizomatica_base_system/templates/vm.args.erb new file mode 100644 index 0000000..e04f88d --- /dev/null +++ b/modules/rhizomatica_base_system/templates/vm.args.erb @@ -0,0 +1,8 @@ ++A 64 ++K true +-env ERL_CRASH_DUMP /var/log/riak/erl_crash.dmp +-env ERL_MAX_PORTS 4096 +-ip <%= @vpn_address %> +-name riak@<%= @vpn_address %> +-setcookie riak +-smp enable \ No newline at end of file diff --git a/modules/rhizomatica_base_system/tests/init.pp b/modules/rhizomatica_base_system/tests/init.pp new file mode 100644 index 0000000..a2297ce --- /dev/null +++ b/modules/rhizomatica_base_system/tests/init.pp @@ -0,0 +1 @@ +include rhizomatica_base_system diff --git a/modules/stdlib/CHANGELOG.md b/modules/stdlib/CHANGELOG.md new file mode 100644 index 0000000..97979bf --- /dev/null +++ b/modules/stdlib/CHANGELOG.md @@ -0,0 +1,418 @@ +##2014-06-04 - Release 4.2.2 +### Summary + +This release adds PE3.3 support in the metadata and fixes a few tests. + +## 2014-05-08 - Release - 4.2.1 +### Summary +This release moves a stray symlink that can cause problems. + +## 2014-05-08 - Release - 4.2.0 +### Summary +This release adds many new functions and fixes, and continues to be backwards compatible with stdlib 3.x + +#### Features +- New `base64()` function +- New `deep_merge()` function +- New `delete_undef_values()` function +- New `delete_values()` function +- New `difference()` function +- New `intersection()` function +- New `is_bool()` function +- New `pick_default()` function +- New `union()` function +- New `validate_ipv4_address` function +- New `validate_ipv6_address` function +- Update `ensure_packages()` to take an option hash as a second parameter. +- Update `range()` to take an optional third argument for range step +- Update `validate_slength()` to take an optional third argument for minimum length +- Update `file_line` resource to take `after` and `multiple` attributes + +#### Bugfixes +- Correct `is_string`, `is_domain_name`, `is_array`, `is_float`, and `is_function_available` for parsing odd types such as bools and hashes. +- Allow facts.d facts to contain `=` in the value +- Fix `root_home` fact on darwin systems +- Fix `concat()` to work with a second non-array argument +- Fix `floor()` to work with integer strings +- Fix `is_integer()` to return true if passed integer strings +- Fix `is_numeric()` to return true if passed integer strings +- Fix `merge()` to work with empty strings +- Fix `pick()` to raise the correct error type +- Fix `uriescape()` to use the default URI.escape list +- Add/update unit & acceptance tests. + + +##2014-03-04 - Supported Release - 3.2.1 +###Summary +This is a supported release + +####Bugfixes +- Fixed `is_integer`/`is_float`/`is_numeric` for checking the value of arithmatic expressions. + +####Known bugs +* No known bugs + +--- + +##### 2013-05-06 - Jeff McCune - 4.1.0 + + * (#20582) Restore facter\_dot\_d to stdlib for PE users (3b887c8) + * (maint) Update Gemfile with GEM\_FACTER\_VERSION (f44d535) + +##### 2013-05-06 - Alex Cline - 4.1.0 + + * Terser method of string to array conversion courtesy of ethooz. (d38bce0) + +##### 2013-05-06 - Alex Cline 4.1.0 + + * Refactor ensure\_resource expectations (b33cc24) + +##### 2013-05-06 - Alex Cline 4.1.0 + + * Changed str-to-array conversion and removed abbreviation. (de253db) + +##### 2013-05-03 - Alex Cline 4.1.0 + + * (#20548) Allow an array of resource titles to be passed into the ensure\_resource function (e08734a) + +##### 2013-05-02 - Raphaël Pinson - 4.1.0 + + * Add a dirname function (2ba9e47) + +##### 2013-04-29 - Mark Smith-Guerrero - 4.1.0 + + * (maint) Fix a small typo in hash() description (928036a) + +##### 2013-04-12 - Jeff McCune - 4.0.2 + + * Update user information in gemspec to make the intent of the Gem clear. + +##### 2013-04-11 - Jeff McCune - 4.0.1 + + * Fix README function documentation (ab3e30c) + +##### 2013-04-11 - Jeff McCune - 4.0.0 + + * stdlib 4.0 drops support with Puppet 2.7 + * stdlib 4.0 preserves support with Puppet 3 + +##### 2013-04-11 - Jeff McCune - 4.0.0 + + * Add ability to use puppet from git via bundler (9c5805f) + +##### 2013-04-10 - Jeff McCune - 4.0.0 + + * (maint) Make stdlib usable as a Ruby GEM (e81a45e) + +##### 2013-04-10 - Erik Dalén - 4.0.0 + + * Add a count function (f28550e) + +##### 2013-03-31 - Amos Shapira - 4.0.0 + + * (#19998) Implement any2array (7a2fb80) + +##### 2013-03-29 - Steve Huff - 4.0.0 + + * (19864) num2bool match fix (8d217f0) + +##### 2013-03-20 - Erik Dalén - 4.0.0 + + * Allow comparisons of Numeric and number as String (ff5dd5d) + +##### 2013-03-26 - Richard Soderberg - 4.0.0 + + * add suffix function to accompany the prefix function (88a93ac) + +##### 2013-03-19 - Kristof Willaert - 4.0.0 + + * Add floor function implementation and unit tests (0527341) + +##### 2012-04-03 - Eric Shamow - 4.0.0 + + * (#13610) Add is\_function\_available to stdlib (961dcab) + +##### 2012-12-17 - Justin Lambert - 4.0.0 + + * str2bool should return a boolean if called with a boolean (5d5a4d4) + +##### 2012-10-23 - Uwe Stuehler - 4.0.0 + + * Fix number of arguments check in flatten() (e80207b) + +##### 2013-03-11 - Jeff McCune - 4.0.0 + + * Add contributing document (96e19d0) + +##### 2013-03-04 - Raphaël Pinson - 4.0.0 + + * Add missing documentation for validate\_augeas and validate\_cmd to README.markdown (a1510a1) + +##### 2013-02-14 - Joshua Hoblitt - 4.0.0 + + * (#19272) Add has\_element() function (95cf3fe) + +##### 2013-02-07 - Raphaël Pinson - 4.0.0 + + * validate\_cmd(): Use Puppet::Util::Execution.execute when available (69248df) + +##### 2012-12-06 - Raphaël Pinson - 4.0.0 + + * Add validate\_augeas function (3a97c23) + +##### 2012-12-06 - Raphaël Pinson - 4.0.0 + + * Add validate\_cmd function (6902cc5) + +##### 2013-01-14 - David Schmitt - 4.0.0 + + * Add geppetto project definition (b3fc0a3) + +##### 2013-01-02 - Jaka Hudoklin - 4.0.0 + + * Add getparam function to get defined resource parameters (20e0e07) + +##### 2013-01-05 - Jeff McCune - 4.0.0 + + * (maint) Add Travis CI Support (d082046) + +##### 2012-12-04 - Jeff McCune - 4.0.0 + + * Clarify that stdlib 3 supports Puppet 3 (3a6085f) + +##### 2012-11-30 - Erik Dalén - 4.0.0 + + * maint: style guideline fixes (7742e5f) + +##### 2012-11-09 - James Fryman - 4.0.0 + + * puppet-lint cleanup (88acc52) + +##### 2012-11-06 - Joe Julian - 4.0.0 + + * Add function, uriescape, to URI.escape strings. Redmine #17459 (fd52b8d) + +##### 2012-09-18 - Chad Metcalf - 3.2.0 + + * Add an ensure\_packages function. (8a8c09e) + +##### 2012-11-23 - Erik Dalén - 3.2.0 + + * (#17797) min() and max() functions (9954133) + +##### 2012-05-23 - Peter Meier - 3.2.0 + + * (#14670) autorequire a file\_line resource's path (dfcee63) + +##### 2012-11-19 - Joshua Harlan Lifton - 3.2.0 + + * Add join\_keys\_to\_values function (ee0f2b3) + +##### 2012-11-17 - Joshua Harlan Lifton - 3.2.0 + + * Extend delete function for strings and hashes (7322e4d) + +##### 2012-08-03 - Gary Larizza - 3.2.0 + + * Add the pick() function (ba6dd13) + +##### 2012-03-20 - Wil Cooley - 3.2.0 + + * (#13974) Add predicate functions for interface facts (f819417) + +##### 2012-11-06 - Joe Julian - 3.2.0 + + * Add function, uriescape, to URI.escape strings. Redmine #17459 (70f4a0e) + +##### 2012-10-25 - Jeff McCune - 3.1.1 + + * (maint) Fix spec failures resulting from Facter API changes (97f836f) + +##### 2012-10-23 - Matthaus Owens - 3.1.0 + + * Add PE facts to stdlib (cdf3b05) + +##### 2012-08-16 - Jeff McCune - 3.0.1 + + * Fix accidental removal of facts\_dot\_d.rb in 3.0.0 release + +##### 2012-08-16 - Jeff McCune - 3.0.0 + + * stdlib 3.0 drops support with Puppet 2.6 + * stdlib 3.0 preserves support with Puppet 2.7 + +##### 2012-08-07 - Dan Bode - 3.0.0 + + * Add function ensure\_resource and defined\_with\_params (ba789de) + +##### 2012-07-10 - Hailee Kenney - 3.0.0 + + * (#2157) Remove facter\_dot\_d for compatibility with external facts (f92574f) + +##### 2012-04-10 - Chris Price - 3.0.0 + + * (#13693) moving logic from local spec\_helper to puppetlabs\_spec\_helper (85f96df) + +##### 2012-10-25 - Jeff McCune - 2.5.1 + + * (maint) Fix spec failures resulting from Facter API changes (97f836f) + +##### 2012-10-23 - Matthaus Owens - 2.5.0 + + * Add PE facts to stdlib (cdf3b05) + +##### 2012-08-15 - Dan Bode - 2.5.0 + + * Explicitly load functions used by ensure\_resource (9fc3063) + +##### 2012-08-13 - Dan Bode - 2.5.0 + + * Add better docs about duplicate resource failures (97d327a) + +##### 2012-08-13 - Dan Bode - 2.5.0 + + * Handle undef for parameter argument (4f8b133) + +##### 2012-08-07 - Dan Bode - 2.5.0 + + * Add function ensure\_resource and defined\_with\_params (a0cb8cd) + +##### 2012-08-20 - Jeff McCune - 2.5.0 + + * Disable tests that fail on 2.6.x due to #15912 (c81496e) + +##### 2012-08-20 - Jeff McCune - 2.5.0 + + * (Maint) Fix mis-use of rvalue functions as statements (4492913) + +##### 2012-08-20 - Jeff McCune - 2.5.0 + + * Add .rspec file to repo root (88789e8) + +##### 2012-06-07 - Chris Price - 2.4.0 + + * Add support for a 'match' parameter to file\_line (a06c0d8) + +##### 2012-08-07 - Erik Dalén - 2.4.0 + + * (#15872) Add to\_bytes function (247b69c) + +##### 2012-07-19 - Jeff McCune - 2.4.0 + + * (Maint) use PuppetlabsSpec::PuppetInternals.scope (master) (deafe88) + +##### 2012-07-10 - Hailee Kenney - 2.4.0 + + * (#2157) Make facts\_dot\_d compatible with external facts (5fb0ddc) + +##### 2012-03-16 - Steve Traylen - 2.4.0 + + * (#13205) Rotate array/string randomley based on fqdn, fqdn\_rotate() (fef247b) + +##### 2012-05-22 - Peter Meier - 2.3.3 + + * fix regression in #11017 properly (f0a62c7) + +##### 2012-05-10 - Jeff McCune - 2.3.3 + + * Fix spec tests using the new spec\_helper (7d34333) + +##### 2012-05-10 - Puppet Labs - 2.3.2 + + * Make file\_line default to ensure => present (1373e70) + * Memoize file\_line spec instance variables (20aacc5) + * Fix spec tests using the new spec\_helper (1ebfa5d) + * (#13595) initialize\_everything\_for\_tests couples modules Puppet ver (3222f35) + * (#13439) Fix MRI 1.9 issue with spec\_helper (15c5fd1) + * (#13439) Fix test failures with Puppet 2.6.x (665610b) + * (#13439) refactor spec helper for compatibility with both puppet 2.7 and master (82194ca) + * (#13494) Specify the behavior of zero padded strings (61891bb) + +##### 2012-03-29 Puppet Labs - 2.1.3 + +* (#11607) Add Rakefile to enable spec testing +* (#12377) Avoid infinite loop when retrying require json + +##### 2012-03-13 Puppet Labs - 2.3.1 + +* (#13091) Fix LoadError bug with puppet apply and puppet\_vardir fact + +##### 2012-03-12 Puppet Labs - 2.3.0 + +* Add a large number of new Puppet functions +* Backwards compatibility preserved with 2.2.x + +##### 2011-12-30 Puppet Labs - 2.2.1 + +* Documentation only release for the Forge + +##### 2011-12-30 Puppet Labs - 2.1.2 + +* Documentation only release for PE 2.0.x + +##### 2011-11-08 Puppet Labs - 2.2.0 + +* #10285 - Refactor json to use pson instead. +* Maint - Add watchr autotest script +* Maint - Make rspec tests work with Puppet 2.6.4 +* #9859 - Add root\_home fact and tests + +##### 2011-08-18 Puppet Labs - 2.1.1 + +* Change facts.d paths to match Facter 2.0 paths. +* /etc/facter/facts.d +* /etc/puppetlabs/facter/facts.d + +##### 2011-08-17 Puppet Labs - 2.1.0 + +* Add R.I. Pienaar's facts.d custom facter fact +* facts defined in /etc/facts.d and /etc/puppetlabs/facts.d are + automatically loaded now. + +##### 2011-08-04 Puppet Labs - 2.0.0 + +* Rename whole\_line to file\_line +* This is an API change and as such motivating a 2.0.0 release according to semver.org. + +##### 2011-08-04 Puppet Labs - 1.1.0 + +* Rename append\_line to whole\_line +* This is an API change and as such motivating a 1.1.0 release. + +##### 2011-08-04 Puppet Labs - 1.0.0 + +* Initial stable release +* Add validate\_array and validate\_string functions +* Make merge() function work with Ruby 1.8.5 +* Add hash merging function +* Add has\_key function +* Add loadyaml() function +* Add append\_line native + +##### 2011-06-21 Jeff McCune - 0.1.7 + +* Add validate\_hash() and getvar() functions + +##### 2011-06-15 Jeff McCune - 0.1.6 + +* Add anchor resource type to provide containment for composite classes + +##### 2011-06-03 Jeff McCune - 0.1.5 + +* Add validate\_bool() function to stdlib + +##### 0.1.4 2011-05-26 Jeff McCune + +* Move most stages after main + +##### 0.1.3 2011-05-25 Jeff McCune + +* Add validate\_re() function + +##### 0.1.2 2011-05-24 Jeff McCune + +* Update to add annotated tag + +##### 0.1.1 2011-05-24 Jeff McCune + +* Add stdlib::stages class with a standard set of stages diff --git a/modules/stdlib/CONTRIBUTING.md b/modules/stdlib/CONTRIBUTING.md new file mode 100644 index 0000000..5280da1 --- /dev/null +++ b/modules/stdlib/CONTRIBUTING.md @@ -0,0 +1,65 @@ +# How to contribute + +Third-party patches are essential for keeping stdlib great. We simply can't +access the huge number of platforms and myriad configurations for running +stdlib. We want to keep it as easy as possible to contribute changes that +get things working in your environment. There are a few guidelines that we +need contributors to follow so that we can have a chance of keeping on +top of things. + +## Getting Started + +* Make sure you have a [Jira account](http://tickets.puppetlabs.com) +* Make sure you have a [GitHub account](https://github.com/signup/free) +* Submit a ticket for your issue, assuming one does not already exist. + * Clearly describe the issue including steps to reproduce when it is a bug. + * Make sure you fill in the earliest version that you know has the issue. +* Fork the repository on GitHub + +## Making Changes + +* Create a topic branch from where you want to base your work. + * This is usually the master branch. + * Only target release branches if you are certain your fix must be on that + branch. + * To quickly create a topic branch based on master; `git branch + fix/master/my_contribution master` then checkout the new branch with `git + checkout fix/master/my_contribution`. Please avoid working directly on the + `master` branch. +* Make commits of logical units. +* Check for unnecessary whitespace with `git diff --check` before committing. +* Make sure your commit messages are in the proper format. + +```` + (#99999) Make the example in CONTRIBUTING imperative and concrete + + Without this patch applied the example commit message in the CONTRIBUTING + document is not a concrete example. This is a problem because the + contributor is left to imagine what the commit message should look like + based on a description rather than an example. This patch fixes the + problem by making the example concrete and imperative. + + The first line is a real life imperative statement with a ticket number + from our issue tracker. The body describes the behavior without the patch, + why this is a problem, and how the patch fixes the problem when applied. +```` + +* Make sure you have added the necessary tests for your changes. +* Run _all_ the tests to assure nothing else was accidentally broken. + +## Submitting Changes + +* Sign the [Contributor License Agreement](http://links.puppetlabs.com/cla). +* Push your changes to a topic branch in your fork of the repository. +* Submit a pull request to the repository in the puppetlabs organization. +* Update your ticket to mark that you have submitted code and are ready for it to be reviewed. + * Include a link to the pull request in the ticket + +# Additional Resources + +* [More information on contributing](http://links.puppetlabs.com/contribute-to-puppet) +* [Bug tracker (Jira)](http://tickets.puppetlabs.com) +* [Contributor License Agreement](http://links.puppetlabs.com/cla) +* [General GitHub documentation](http://help.github.com/) +* [GitHub pull request documentation](http://help.github.com/send-pull-requests/) +* #puppet-dev IRC channel on freenode.org diff --git a/modules/stdlib/Gemfile b/modules/stdlib/Gemfile new file mode 100644 index 0000000..bbef720 --- /dev/null +++ b/modules/stdlib/Gemfile @@ -0,0 +1,33 @@ +source ENV['GEM_SOURCE'] || 'https://rubygems.org' + +def location_for(place, fake_version = nil) + if place =~ /^(git[:@][^#]*)#(.*)/ + [fake_version, { :git => $1, :branch => $2, :require => false }].compact + elsif place =~ /^file:\/\/(.*)/ + ['>= 0', { :path => File.expand_path($1), :require => false }] + else + [place, { :require => false }] + end +end + +group :development, :test do + gem 'rake', '~> 10.1.0', :require => false + gem 'rspec-puppet', :require => false + gem 'puppetlabs_spec_helper', :require => false + gem 'serverspec', :require => false + gem 'puppet-lint', :require => false + gem 'pry', :require => false + gem 'simplecov', :require => false + gem 'beaker', :require => false + gem 'beaker-rspec', :require => false +end + +ENV['GEM_PUPPET_VERSION'] ||= ENV['PUPPET_GEM_VERSION'] +puppetversion = ENV['GEM_PUPPET_VERSION'] +if puppetversion + gem 'puppet', *location_for(puppetversion) +else + gem 'puppet', :require => false +end + +# vim:ft=ruby diff --git a/modules/stdlib/Gemfile.lock b/modules/stdlib/Gemfile.lock new file mode 100644 index 0000000..402a3ea --- /dev/null +++ b/modules/stdlib/Gemfile.lock @@ -0,0 +1,166 @@ +GEM + remote: https://rubygems.org/ + specs: + CFPropertyList (2.2.8) + addressable (2.3.6) + archive-tar-minitar (0.5.2) + autoparse (0.3.3) + addressable (>= 2.3.1) + extlib (>= 0.9.15) + multi_json (>= 1.0.0) + aws-sdk (1.42.0) + json (~> 1.4) + nokogiri (>= 1.4.4) + beaker (1.12.1) + aws-sdk (~> 1.38) + blimpy (~> 0.6) + docker-api + fission (~> 0.4) + google-api-client (~> 0.7.1) + inifile (~> 2.0) + json (~> 1.8) + mime-types (~> 1.25) + net-scp (~> 1.1) + net-ssh (~> 2.6) + nokogiri (= 1.5.10) + rbvmomi (= 1.8.1) + unf (~> 0.1) + beaker-rspec (2.2.4) + beaker (~> 1.10) + rspec (~> 2.14) + serverspec (~> 1.0) + specinfra (~> 1.0) + blimpy (0.6.7) + fog + minitar + thor + builder (3.2.2) + coderay (1.1.0) + diff-lcs (1.2.5) + docile (1.1.3) + docker-api (1.11.0) + archive-tar-minitar + excon (>= 0.34.0) + json + excon (0.34.0) + extlib (0.9.16) + facter (2.0.1) + CFPropertyList (~> 2.2.6) + faraday (0.9.0) + multipart-post (>= 1.2, < 3) + fission (0.5.0) + CFPropertyList (~> 2.2) + fog (1.11.1) + builder + excon (~> 0.20) + formatador (~> 0.2.0) + json (~> 1.7) + mime-types + net-scp (~> 1.1) + net-ssh (>= 2.1.3) + nokogiri (~> 1.5.0) + ruby-hmac + formatador (0.2.5) + google-api-client (0.7.1) + addressable (>= 2.3.2) + autoparse (>= 0.3.3) + extlib (>= 0.9.15) + faraday (>= 0.9.0) + jwt (>= 0.1.5) + launchy (>= 2.1.1) + multi_json (>= 1.0.0) + retriable (>= 1.4) + signet (>= 0.5.0) + uuidtools (>= 2.1.0) + hiera (1.3.3) + json_pure + highline (1.6.21) + inifile (2.0.2) + json (1.8.1) + json_pure (1.8.1) + jwt (1.0.0) + launchy (2.4.2) + addressable (~> 2.3) + metaclass (0.0.4) + method_source (0.8.2) + mime-types (1.25.1) + minitar (0.5.4) + mocha (1.1.0) + metaclass (~> 0.0.1) + multi_json (1.10.1) + multipart-post (2.0.0) + net-scp (1.2.1) + net-ssh (>= 2.6.5) + net-ssh (2.9.1) + nokogiri (1.5.10) + pry (0.9.12.6) + coderay (~> 1.0) + method_source (~> 0.8) + slop (~> 3.4) + puppet (3.6.1) + facter (> 1.6, < 3) + hiera (~> 1.0) + json_pure + rgen (~> 0.6.5) + puppet-lint (0.3.2) + puppetlabs_spec_helper (0.4.1) + mocha (>= 0.10.5) + rake + rspec (>= 2.9.0) + rspec-puppet (>= 0.1.1) + rake (10.1.1) + rbvmomi (1.8.1) + builder + nokogiri (>= 1.4.1) + trollop + retriable (1.4.1) + rgen (0.6.6) + rspec (2.99.0) + rspec-core (~> 2.99.0) + rspec-expectations (~> 2.99.0) + rspec-mocks (~> 2.99.0) + rspec-core (2.99.0) + rspec-expectations (2.99.0) + diff-lcs (>= 1.1.3, < 2.0) + rspec-mocks (2.99.0) + rspec-puppet (1.0.1) + rspec + ruby-hmac (0.4.0) + serverspec (1.7.0) + highline + net-ssh + rspec (~> 2.13) + specinfra (~> 1.13) + signet (0.5.0) + addressable (>= 2.2.3) + faraday (>= 0.9.0.rc5) + jwt (>= 0.1.5) + multi_json (>= 1.0.0) + simplecov (0.8.2) + docile (~> 1.1.0) + multi_json + simplecov-html (~> 0.8.0) + simplecov-html (0.8.0) + slop (3.5.0) + specinfra (1.15.0) + thor (0.19.1) + trollop (2.0) + unf (0.1.4) + unf_ext + unf_ext (0.0.6) + uuidtools (2.1.4) + +PLATFORMS + ruby + +DEPENDENCIES + beaker + beaker-rspec (= 2.2.4) + pry + puppet + puppet-lint + puppetlabs_spec_helper + rake (~> 10.1.0) + rspec-puppet + serverspec + simplecov diff --git a/modules/stdlib/LICENSE b/modules/stdlib/LICENSE new file mode 100644 index 0000000..ec0587c --- /dev/null +++ b/modules/stdlib/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011 Puppet Labs Inc + +and some parts: + +Copyright (C) 2011 Krzysztof Wilczynski + +Puppet Labs can be contacted at: info@puppetlabs.com + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/modules/stdlib/Modulefile b/modules/stdlib/Modulefile new file mode 100644 index 0000000..bf80e3b --- /dev/null +++ b/modules/stdlib/Modulefile @@ -0,0 +1,11 @@ +name 'puppetlabs-stdlib' +version '4.2.2' +source 'git://github.com/puppetlabs/puppetlabs-stdlib.git' +author 'puppetlabs' +license 'Apache 2.0' +summary 'Puppet Module Standard Library' +description 'Standard Library for Puppet Modules' +project_page 'https://github.com/puppetlabs/puppetlabs-stdlib' + +## Add dependencies, if any: +# dependency 'username/name', '>= 1.2.0' diff --git a/modules/stdlib/README.markdown b/modules/stdlib/README.markdown new file mode 100644 index 0000000..e9ad53b --- /dev/null +++ b/modules/stdlib/README.markdown @@ -0,0 +1,1304 @@ +# Puppet Labs Standard Library # + +[![Build Status](https://travis-ci.org/puppetlabs/puppetlabs-stdlib.png?branch=master)](https://travis-ci.org/puppetlabs/puppetlabs-stdlib) + +This module provides a "standard library" of resources for developing Puppet +Modules. This modules will include the following additions to Puppet + + * Stages + * Facts + * Functions + * Defined resource types + * Types + * Providers + +This module is officially curated and provided by Puppet Labs. The modules +Puppet Labs writes and distributes will make heavy use of this standard +library. + +To report or research a bug with any part of this module, please go to +[http://tickets.puppetlabs.com/browse/PUP](http://tickets.puppetlabs.com/browse/PUP) + +# Versions # + +This module follows semver.org (v1.0.0) versioning guidelines. The standard +library module is released as part of [Puppet +Enterprise](http://puppetlabs.com/puppet/puppet-enterprise/) and as a result +older versions of Puppet Enterprise that Puppet Labs still supports will have +bugfix maintenance branches periodically "merged up" into master. The current +list of integration branches are: + + * v2.1.x (v2.1.1 released in PE 1) + * v2.2.x (Never released as part of PE, only to the Forge) + * v2.3.x (Released in PE 2) + * v3.0.x (Released in PE 3) + * v4.0.x (Maintains compatibility with v3.x despite the major semantic version bump. Compatible with Puppet 2.7.x) + * v5.x (To be released when stdlib can drop support for Puppet 2.7.x. Please see [this discussion](https://github.com/puppetlabs/puppetlabs-stdlib/pull/176#issuecomment-30251414)) + * master (mainline development branch) + +The first Puppet Enterprise version including the stdlib module is Puppet +Enterprise 1.2. + +# Compatibility # + +Puppet Versions | < 2.6 | 2.6 | 2.7 | 3.x | +:---------------|:-----:|:---:|:---:|:----: +**stdlib 2.x** | no | **yes** | **yes** | no +**stdlib 3.x** | no | no | **yes** | **yes** +**stdlib 4.x** | no | no | **yes** | **yes** + +The stdlib module does not work with Puppet versions released prior to Puppet +2.6.0. + +## stdlib 2.x ## + +All stdlib releases in the 2.0 major version support Puppet 2.6 and Puppet 2.7. + +## stdlib 3.x ## + +The 3.0 major release of stdlib drops support for Puppet 2.6. Stdlib 3.x +supports Puppet 2 and Puppet 3. + +## stdlib 4.x ## + +The 4.0 major release of stdlib was intended to drop support for Puppet 2.7, +but the impact on end users was too high. The decision was made to treat +stdlib 4.x as a continuation of stdlib 3.x support. Stdlib 4.x supports Puppet +2.7 and 3. Notably, ruby 1.8.5 is no longer supported though ruby +1.8.7, 1.9.3, and 2.0.0 are fully supported. + +# Functions # + +abs +--- +Returns the absolute value of a number, for example -34.56 becomes +34.56. Takes a single integer and float value as an argument. + + +- *Type*: rvalue + +any2array +--------- +This converts any object to an array containing that object. Empty argument +lists are converted to an empty array. Arrays are left untouched. Hashes are +converted to arrays of alternating keys and values. + + +- *Type*: rvalue + +base64 +-------- +Converts a string to and from base64 encoding. +Requires an action ['encode','decode'] and either a plain or base64 encoded +string + + +- *Type*: rvalue + +bool2num +-------- +Converts a boolean to a number. Converts the values: +false, f, 0, n, and no to 0 +true, t, 1, y, and yes to 1 + Requires a single boolean or string as an input. + + +- *Type*: rvalue + +capitalize +---------- +Capitalizes the first letter of a string or array of strings. +Requires either a single string or an array as an input. + + +- *Type*: rvalue + +chomp +----- +Removes the record separator from the end of a string or an array of +strings, for example `hello\n` becomes `hello`. +Requires a single string or array as an input. + + +- *Type*: rvalue + +chop +---- +Returns a new string with the last character removed. If the string ends +with `\r\n`, both characters are removed. Applying chop to an empty +string returns an empty string. If you wish to merely remove record +separators then you should use the `chomp` function. +Requires a string or array of strings as input. + + +- *Type*: rvalue + +concat +------ +Appends the contents of array 2 onto array 1. + +*Example:* + + concat(['1','2','3'],['4','5','6']) + +Would result in: + + ['1','2','3','4','5','6'] + + concat(['1','2','3'],'4') + +Would result in: + + ['1','2','3','4'] + +- *Type*: rvalue + +count +----- +Takes an array as first argument and an optional second argument. +Count the number of elements in array that matches second argument. +If called with only an array it counts the number of elements that are not nil/undef. + + +- *Type*: rvalue + +defined_with_params +------------------- +Takes a resource reference and an optional hash of attributes. + +Returns true if a resource with the specified attributes has already been added +to the catalog, and false otherwise. + + user { 'dan': + ensure => present, + } + + if ! defined_with_params(User[dan], {'ensure' => 'present' }) { + user { 'dan': ensure => present, } + } + + +- *Type*: rvalue + +delete +------ +Deletes all instances of a given element from an array, substring from a +string, or key from a hash. + +*Examples:* + + delete(['a','b','c','b'], 'b') + Would return: ['a','c'] + + delete({'a'=>1,'b'=>2,'c'=>3}, 'b') + Would return: {'a'=>1,'c'=>3} + + delete('abracadabra', 'bra') + Would return: 'acada' + + +- *Type*: rvalue + +delete_at +--------- +Deletes a determined indexed value from an array. + +*Examples:* + + delete_at(['a','b','c'], 1) + +Would return: ['a','c'] + + +- *Type*: rvalue + +delete_values +------------- +Deletes all instances of a given value from a hash. + +*Examples:* + + delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B') + +Would return: {'a'=>'A','c'=>'C','B'=>'D'} + + +- *Type*: rvalue + +delete_undef_values +------------------- +Deletes all instances of the undef value from an array or hash. + +*Examples:* + + $hash = delete_undef_values({a=>'A', b=>'', c=>undef, d => false}) + +Would return: {a => 'A', b => '', d => false} + + $array = delete_undef_values(['A','',undef,false]) + +Would return: ['A','',false] + +- *Type*: rvalue + +difference +---------- +This function returns the difference between two arrays. +The returned array is a copy of the original array, removing any items that +also appear in the second array. + +*Examples:* + + difference(["a","b","c"],["b","c","d"]) + +Would return: ["a"] + +dirname +------- +Returns the `dirname` of a path. + +*Examples:* + + dirname('/path/to/a/file.ext') + +Would return: '/path/to/a' + +downcase +-------- +Converts the case of a string or all strings in an array to lower case. + + +- *Type*: rvalue + +empty +----- +Returns true if the variable is empty. + + +- *Type*: rvalue + +ensure_packages +--------------- +Takes a list of packages and only installs them if they don't already exist. +It optionally takes a hash as a second parameter that will be passed as the +third argument to the ensure_resource() function. + + +- *Type*: statement + +ensure_resource +--------------- +Takes a resource type, title, and a list of attributes that describe a +resource. + + user { 'dan': + ensure => present, + } + +This example only creates the resource if it does not already exist: + + ensure_resource('user', 'dan', {'ensure' => 'present' }) + +If the resource already exists but does not match the specified parameters, +this function will attempt to recreate the resource leading to a duplicate +resource definition error. + +An array of resources can also be passed in and each will be created with +the type and parameters specified if it doesn't already exist. + + ensure_resource('user', ['dan','alex'], {'ensure' => 'present'}) + + + +- *Type*: statement + +file_line +--------- +This resource ensures that a given line is contained within a file. You can also use +"match" to replace existing lines. + +*Examples:* + + file_line { 'sudo_rule': + path => '/etc/sudoers', + line => '%sudo ALL=(ALL) ALL', + } + + file_line { 'change_mount': + path => '/etc/fstab', + line => '10.0.0.1:/vol/data /opt/data nfs defaults 0 0', + match => '^172.16.17.2:/vol/old', + } + +- *Type*: resource + +flatten +------- +This function flattens any deeply nested arrays and returns a single flat array +as a result. + +*Examples:* + + flatten(['a', ['b', ['c']]]) + +Would return: ['a','b','c'] + + +- *Type*: rvalue + +floor +----- +Returns the largest integer less or equal to the argument. +Takes a single numeric value as an argument. + + +- *Type*: rvalue + +fqdn_rotate +----------- +Rotates an array a random number of times based on a nodes fqdn. + + +- *Type*: rvalue + +get_module_path +--------------- +Returns the absolute path of the specified module for the current +environment. + +Example: + $module_path = get_module_path('stdlib') + + +- *Type*: rvalue + +getparam +-------- +Takes a resource reference and name of the parameter and +returns value of resource's parameter. + +*Examples:* + + define example_resource($param) { + } + + example_resource { "example_resource_instance": + param => "param_value" + } + + getparam(Example_resource["example_resource_instance"], "param") + +Would return: param_value + + +- *Type*: rvalue + +getvar +------ +Lookup a variable in a remote namespace. + +For example: + + $foo = getvar('site::data::foo') + # Equivalent to $foo = $site::data::foo + +This is useful if the namespace itself is stored in a string: + + $datalocation = 'site::data' + $bar = getvar("${datalocation}::bar") + # Equivalent to $bar = $site::data::bar + + +- *Type*: rvalue + +grep +---- +This function searches through an array and returns any elements that match +the provided regular expression. + +*Examples:* + + grep(['aaa','bbb','ccc','aaaddd'], 'aaa') + +Would return: + + ['aaa','aaaddd'] + + +- *Type*: rvalue + +has_interface_with +------------------ +Returns boolean based on kind and value: +* macaddress +* netmask +* ipaddress +* network + +*Examples:* + + has_interface_with("macaddress", "x:x:x:x:x:x") + has_interface_with("ipaddress", "127.0.0.1") => true + +etc. + +If no "kind" is given, then the presence of the interface is checked: + + has_interface_with("lo") => true + + +- *Type*: rvalue + +has_ip_address +-------------- +Returns true if the client has the requested IP address on some interface. + +This function iterates through the 'interfaces' fact and checks the +'ipaddress_IFACE' facts, performing a simple string comparison. + + +- *Type*: rvalue + +has_ip_network +-------------- +Returns true if the client has an IP address within the requested network. + +This function iterates through the 'interfaces' fact and checks the +'network_IFACE' facts, performing a simple string comparision. + + +- *Type*: rvalue + +has_key +------- +Determine if a hash has a certain key value. + +Example: + + $my_hash = {'key_one' => 'value_one'} + if has_key($my_hash, 'key_two') { + notice('we will not reach here') + } + if has_key($my_hash, 'key_one') { + notice('this will be printed') + } + + + +- *Type*: rvalue + +hash +---- +This function converts an array into a hash. + +*Examples:* + + hash(['a',1,'b',2,'c',3]) + +Would return: {'a'=>1,'b'=>2,'c'=>3} + + +- *Type*: rvalue + +intersection +----------- +This function returns an array an intersection of two. + +*Examples:* + + intersection(["a","b","c"],["b","c","d"]) + +Would return: ["b","c"] + +is_array +-------- +Returns true if the variable passed to this function is an array. + +- *Type*: rvalue + +is_bool +-------- +Returns true if the variable passed to this function is a boolean. + +- *Type*: rvalue + +is_domain_name +-------------- +Returns true if the string passed to this function is a syntactically correct domain name. + +- *Type*: rvalue + +is_float +-------- +Returns true if the variable passed to this function is a float. + +- *Type*: rvalue + +is_function_available +--------------------- +This function accepts a string as an argument, determines whether the +Puppet runtime has access to a function by that name. It returns a +true if the function exists, false if not. + +- *Type*: rvalue + +is_hash +------- +Returns true if the variable passed to this function is a hash. + +- *Type*: rvalue + +is_integer +---------- +Returns true if the variable returned to this string is an integer. + +- *Type*: rvalue + +is_ip_address +------------- +Returns true if the string passed to this function is a valid IP address. + +- *Type*: rvalue + +is_mac_address +-------------- +Returns true if the string passed to this function is a valid mac address. + +- *Type*: rvalue + +is_numeric +---------- +Returns true if the variable passed to this function is a number. + +- *Type*: rvalue + +is_string +--------- +Returns true if the variable passed to this function is a string. + +- *Type*: rvalue + +join +---- +This function joins an array into a string using a separator. + +*Examples:* + + join(['a','b','c'], ",") + +Would result in: "a,b,c" + +- *Type*: rvalue + +join_keys_to_values +------------------- +This function joins each key of a hash to that key's corresponding value with a +separator. Keys and values are cast to strings. The return value is an array in +which each element is one joined key/value pair. + +*Examples:* + + join_keys_to_values({'a'=>1,'b'=>2}, " is ") + +Would result in: ["a is 1","b is 2"] + +- *Type*: rvalue + +keys +---- +Returns the keys of a hash as an array. + +- *Type*: rvalue + +loadyaml +-------- +Load a YAML file containing an array, string, or hash, and return the data +in the corresponding native data type. + +For example: + + $myhash = loadyaml('/etc/puppet/data/myhash.yaml') + + +- *Type*: rvalue + +lstrip +------ +Strips leading spaces to the left of a string. + +- *Type*: rvalue + +max +--- +Returns the highest value of all arguments. +Requires at least one argument. + +- *Type*: rvalue + +member +------ +This function determines if a variable is a member of an array. + +*Examples:* + + member(['a','b'], 'b') + +Would return: true + + member(['a','b'], 'c') + +Would return: false + +- *Type*: rvalue + +merge +----- +Merges two or more hashes together and returns the resulting hash. + +For example: + + $hash1 = {'one' => 1, 'two' => 2} + $hash2 = {'two' => 'dos', 'three' => 'tres'} + $merged_hash = merge($hash1, $hash2) + # The resulting hash is equivalent to: + # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'} + +When there is a duplicate key, the key in the rightmost hash will "win." + +- *Type*: rvalue + +min +--- +Returns the lowest value of all arguments. +Requires at least one argument. + +- *Type*: rvalue + +num2bool +-------- +This function converts a number or a string representation of a number into a +true boolean. Zero or anything non-numeric becomes false. Numbers higher then 0 +become true. + +- *Type*: rvalue + +parsejson +--------- +This function accepts JSON as a string and converts into the correct Puppet +structure. + +- *Type*: rvalue + +parseyaml +--------- +This function accepts YAML as a string and converts it into the correct +Puppet structure. + +- *Type*: rvalue + +pick +---- +This function is similar to a coalesce function in SQL in that it will return +the first value in a list of values that is not undefined or an empty string +(two things in Puppet that will return a boolean false value). Typically, +this function is used to check for a value in the Puppet Dashboard/Enterprise +Console, and failover to a default value like the following: + + $real_jenkins_version = pick($::jenkins_version, '1.449') + +The value of $real_jenkins_version will first look for a top-scope variable +called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ +Enterprise Console are brought into Puppet as top-scope variables), and, +failing that, will use a default value of 1.449. + +- *Type*: rvalue + +prefix +------ +This function applies a prefix to all elements in an array. + +*Examples:* + + prefix(['a','b','c'], 'p') + +Will return: ['pa','pb','pc'] + +- *Type*: rvalue + +range +----- +When given range in the form of (start, stop) it will extrapolate a range as +an array. + +*Examples:* + + range("0", "9") + +Will return: [0,1,2,3,4,5,6,7,8,9] + + range("00", "09") + +Will return: [0,1,2,3,4,5,6,7,8,9] - Zero padded strings are converted to +integers automatically + + range("a", "c") + +Will return: ["a","b","c"] + + range("host01", "host10") + +Will return: ["host01", "host02", ..., "host09", "host10"] + +- *Type*: rvalue + +reject +------ +This function searches through an array and rejects all elements that match +the provided regular expression. + +*Examples:* + + reject(['aaa','bbb','ccc','aaaddd'], 'aaa') + +Would return: + + ['bbb','ccc'] + + +- *Type*: rvalue + +reverse +------- +Reverses the order of a string or array. + +- *Type*: rvalue + +rstrip +------ +Strips leading spaces to the right of the string. + +- *Type*: rvalue + +shuffle +------- +Randomizes the order of a string or array elements. + +- *Type*: rvalue + +size +---- +Returns the number of elements in a string or array. + +- *Type*: rvalue + +sort +---- +Sorts strings and arrays lexically. + +- *Type*: rvalue + +squeeze +------- +Returns a new string where runs of the same character that occur in this set +are replaced by a single character. + +- *Type*: rvalue + +str2bool +-------- +This converts a string to a boolean. This attempts to convert strings that +contain things like: y, 1, t, true to 'true' and strings that contain things +like: 0, f, n, false, no to 'false'. + + +- *Type*: rvalue + +str2saltedsha512 +---------------- +This converts a string to a salted-SHA512 password hash (which is used for +OS X versions >= 10.7). Given any simple string, you will get a hex version +of a salted-SHA512 password hash that can be inserted into your Puppet +manifests as a valid password attribute. + + +- *Type*: rvalue + +strftime +-------- +This function returns formatted time. + +*Examples:* + +To return the time since epoch: + + strftime("%s") + +To return the date: + + strftime("%Y-%m-%d") + +*Format meaning:* + + %a - The abbreviated weekday name (``Sun'') + %A - The full weekday name (``Sunday'') + %b - The abbreviated month name (``Jan'') + %B - The full month name (``January'') + %c - The preferred local date and time representation + %C - Century (20 in 2009) + %d - Day of the month (01..31) + %D - Date (%m/%d/%y) + %e - Day of the month, blank-padded ( 1..31) + %F - Equivalent to %Y-%m-%d (the ISO 8601 date format) + %h - Equivalent to %b + %H - Hour of the day, 24-hour clock (00..23) + %I - Hour of the day, 12-hour clock (01..12) + %j - Day of the year (001..366) + %k - hour, 24-hour clock, blank-padded ( 0..23) + %l - hour, 12-hour clock, blank-padded ( 0..12) + %L - Millisecond of the second (000..999) + %m - Month of the year (01..12) + %M - Minute of the hour (00..59) + %n - Newline (\n) + %N - Fractional seconds digits, default is 9 digits (nanosecond) + %3N millisecond (3 digits) + %6N microsecond (6 digits) + %9N nanosecond (9 digits) + %p - Meridian indicator (``AM'' or ``PM'') + %P - Meridian indicator (``am'' or ``pm'') + %r - time, 12-hour (same as %I:%M:%S %p) + %R - time, 24-hour (%H:%M) + %s - Number of seconds since 1970-01-01 00:00:00 UTC. + %S - Second of the minute (00..60) + %t - Tab character ( ) + %T - time, 24-hour (%H:%M:%S) + %u - Day of the week as a decimal, Monday being 1. (1..7) + %U - Week number of the current year, + starting with the first Sunday as the first + day of the first week (00..53) + %v - VMS date (%e-%b-%Y) + %V - Week number of year according to ISO 8601 (01..53) + %W - Week number of the current year, + starting with the first Monday as the first + day of the first week (00..53) + %w - Day of the week (Sunday is 0, 0..6) + %x - Preferred representation for the date alone, no time + %X - Preferred representation for the time alone, no date + %y - Year without a century (00..99) + %Y - Year with century + %z - Time zone as hour offset from UTC (e.g. +0900) + %Z - Time zone name + %% - Literal ``%'' character + + +- *Type*: rvalue + +strip +----- +This function removes leading and trailing whitespace from a string or from +every string inside an array. + +*Examples:* + + strip(" aaa ") + +Would result in: "aaa" + + +- *Type*: rvalue + +suffix +------ +This function applies a suffix to all elements in an array. + +*Examples:* + + suffix(['a','b','c'], 'p') + +Will return: ['ap','bp','cp'] + + +- *Type*: rvalue + +swapcase +-------- +This function will swap the existing case of a string. + +*Examples:* + + swapcase("aBcD") + +Would result in: "AbCd" + + +- *Type*: rvalue + +time +---- +This function will return the current time since epoch as an integer. + +*Examples:* + + time() + +Will return something like: 1311972653 + + +- *Type*: rvalue + +to_bytes +-------- +Converts the argument into bytes, for example 4 kB becomes 4096. +Takes a single string value as an argument. + + +- *Type*: rvalue + +type +---- +Returns the type when passed a variable. Type can be one of: + +* string +* array +* hash +* float +* integer +* boolean + + +- *Type*: rvalue + +union +----- +This function returns a union of two arrays. + +*Examples:* + + union(["a","b","c"],["b","c","d"]) + +Would return: ["a","b","c","d"] + + +unique +------ +This function will remove duplicates from strings and arrays. + +*Examples:* + + unique("aabbcc") + +Will return: + + abc + +You can also use this with arrays: + + unique(["a","a","b","b","c","c"]) + +This returns: + + ["a","b","c"] + + +- *Type*: rvalue + +upcase +------ +Converts a string or an array of strings to uppercase. + +*Examples:* + + upcase("abcd") + +Will return: + + ABCD + + +- *Type*: rvalue + +uriescape +--------- +Urlencodes a string or array of strings. +Requires either a single string or an array as an input. + + +- *Type*: rvalue + +validate_absolute_path +---------------------- +Validate the string represents an absolute path in the filesystem. This function works +for windows and unix style paths. + +The following values will pass: + + $my_path = "C:/Program Files (x86)/Puppet Labs/Puppet" + validate_absolute_path($my_path) + $my_path2 = "/var/lib/puppet" + validate_absolute_path($my_path2) + + +The following values will fail, causing compilation to abort: + + validate_absolute_path(true) + validate_absolute_path([ 'var/lib/puppet', '/var/foo' ]) + validate_absolute_path([ '/var/lib/puppet', 'var/foo' ]) + $undefined = undef + validate_absolute_path($undefined) + + + +- *Type*: statement + +validate_array +-------------- +Validate that all passed values are array data structures. Abort catalog +compilation if any value fails this check. + +The following values will pass: + + $my_array = [ 'one', 'two' ] + validate_array($my_array) + +The following values will fail, causing compilation to abort: + + validate_array(true) + validate_array('some_string') + $undefined = undef + validate_array($undefined) + + + +- *Type*: statement + +validate_augeas +--------------- +Perform validation of a string using an Augeas lens +The first argument of this function should be a string to +test, and the second argument should be the name of the Augeas lens to use. +If Augeas fails to parse the string with the lens, the compilation will +abort with a parse error. + +A third argument can be specified, listing paths which should +not be found in the file. The `$file` variable points to the location +of the temporary file being tested in the Augeas tree. + +For example, if you want to make sure your passwd content never contains +a user `foo`, you could write: + + validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo']) + +Or if you wanted to ensure that no users used the '/bin/barsh' shell, +you could use: + + validate_augeas($passwdcontent, 'Passwd.lns', ['$file/*[shell="/bin/barsh"]'] + +If a fourth argument is specified, this will be the error message raised and +seen by the user. + +A helpful error message can be returned like this: + + validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas') + + + +- *Type*: statement + +validate_bool +------------- +Validate that all passed values are either true or false. Abort catalog +compilation if any value fails this check. + +The following values will pass: + + $iamtrue = true + validate_bool(true) + validate_bool(true, true, false, $iamtrue) + +The following values will fail, causing compilation to abort: + + $some_array = [ true ] + validate_bool("false") + validate_bool("true") + validate_bool($some_array) + + + +- *Type*: statement + +validate_cmd +------------ +Perform validation of a string with an external command. +The first argument of this function should be a string to +test, and the second argument should be a path to a test command +taking a file as last argument. If the command, launched against +a tempfile containing the passed string, returns a non-null value, +compilation will abort with a parse error. + +If a third argument is specified, this will be the error message raised and +seen by the user. + +A helpful error message can be returned like this: + +Example: + + validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content') + + + +- *Type*: statement + +validate_hash +------------- +Validate that all passed values are hash data structures. Abort catalog +compilation if any value fails this check. + +The following values will pass: + + $my_hash = { 'one' => 'two' } + validate_hash($my_hash) + +The following values will fail, causing compilation to abort: + + validate_hash(true) + validate_hash('some_string') + $undefined = undef + validate_hash($undefined) + + + +- *Type*: statement + +validate_re +----------- +Perform simple validation of a string against one or more regular +expressions. The first argument of this function should be a string to +test, and the second argument should be a stringified regular expression +(without the // delimiters) or an array of regular expressions. If none +of the regular expressions match the string passed in, compilation will +abort with a parse error. + +If a third argument is specified, this will be the error message raised and +seen by the user. + +The following strings will validate against the regular expressions: + + validate_re('one', '^one$') + validate_re('one', [ '^one', '^two' ]) + +The following strings will fail to validate, causing compilation to abort: + + validate_re('one', [ '^two', '^three' ]) + +A helpful error message can be returned like this: + + validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7') + + + +- *Type*: statement + +validate_slength +---------------- +Validate that the first argument is a string (or an array of strings), and +less/equal to than the length of the second argument. It fails if the first +argument is not a string or array of strings, and if arg 2 is not convertable +to a number. + +The following values will pass: + + validate_slength("discombobulate",17) + validate_slength(["discombobulate","moo"],17) + +The following values will not: + + validate_slength("discombobulate",1) + validate_slength(["discombobulate","thermometer"],5) + + + +- *Type*: statement + +validate_string +--------------- +Validate that all passed values are string data structures. Abort catalog +compilation if any value fails this check. + +The following values will pass: + + $my_string = "one two" + validate_string($my_string, 'three') + +The following values will fail, causing compilation to abort: + + validate_string(true) + validate_string([ 'some', 'array' ]) + $undefined = undef + validate_string($undefined) + + +- *Type*: statement + +values +------ +When given a hash this function will return the values of that hash. + +*Examples:* + + $hash = { + 'a' => 1, + 'b' => 2, + 'c' => 3, + } + values($hash) + +This example would return: + + [1,2,3] + + +- *Type*: rvalue + +values_at +--------- +Finds value inside an array based on location. + +The first argument is the array you want to analyze, and the second element can +be a combination of: + +* A single numeric index +* A range in the form of 'start-stop' (eg. 4-9) +* An array combining the above + +*Examples*: + + values_at(['a','b','c'], 2) + +Would return ['c']. + + values_at(['a','b','c'], ["0-1"]) + +Would return ['a','b']. + + values_at(['a','b','c','d','e'], [0, "2-3"]) + +Would return ['a','c','d']. + + +- *Type*: rvalue + +zip +--- +Takes one element from first array and merges corresponding elements from second array. This generates a sequence of n-element arrays, where n is one more than the count of arguments. + +*Example:* + + zip(['1','2','3'],['4','5','6']) + +Would result in: + + ["1", "4"], ["2", "5"], ["3", "6"] + + +- *Type*: rvalue + +*This page autogenerated on 2013-04-11 13:54:25 -0700* diff --git a/modules/stdlib/README_DEVELOPER.markdown b/modules/stdlib/README_DEVELOPER.markdown new file mode 100644 index 0000000..04349ed --- /dev/null +++ b/modules/stdlib/README_DEVELOPER.markdown @@ -0,0 +1,35 @@ +Puppet Specific Facts +===================== + +Facter is meant to stand alone and apart from Puppet. However, Facter often +runs inside Puppet and all custom facts included in the stdlib module will +almost always be evaluated in the context of Puppet and Facter working +together. + +Still, we don't want to write custom facts that blow up in the users face if +Puppet is not loaded in memory. This is often the case if the user runs +`facter` without also supplying the `--puppet` flag. + +Ah! But Jeff, the custom fact won't be in the `$LOAD_PATH` unless the user +supplies `--facter`! You might say... + +Not (always) true I say! If the user happens to have a CWD of +`/stdlib/lib` then the facts will automatically be evaluated and +blow up. + +In any event, it's pretty easy to write a fact that has no value if Puppet is +not loaded. Simply do it like this: + + Facter.add(:node_vardir) do + setcode do + # This will be nil if Puppet is not available. + Facter::Util::PuppetSettings.with_puppet do + Puppet[:vardir] + end + end + end + +The `Facter::Util::PuppetSettings.with_puppet` method accepts a block and +yields to it only if the Puppet library is loaded. If the Puppet library is +not loaded, then the method silently returns `nil` which Facter interprets as +an undefined fact value. The net effect is that the fact won't be set. diff --git a/modules/stdlib/README_SPECS.markdown b/modules/stdlib/README_SPECS.markdown new file mode 100644 index 0000000..917b631 --- /dev/null +++ b/modules/stdlib/README_SPECS.markdown @@ -0,0 +1,7 @@ +NOTE +==== + +This project's specs depend on puppet core, and thus they require the +`puppetlabs_spec_helper` project. For more information please see the README +in that project, which can be found here: [puppetlabs spec +helper](https://github.com/puppetlabs/puppetlabs_spec_helper) diff --git a/modules/stdlib/RELEASE_PROCESS.markdown b/modules/stdlib/RELEASE_PROCESS.markdown new file mode 100644 index 0000000..0f9328e --- /dev/null +++ b/modules/stdlib/RELEASE_PROCESS.markdown @@ -0,0 +1,24 @@ +# Contributing to this module # + + * Work in a topic branch + * Submit a github pull request + * Address any comments / feeback + * Merge into master using --no-ff + +# Releasing this module # + + * This module adheres to http://semver.org/ + * Look for API breaking changes using git diff vX.Y.Z..master + * If no API breaking changes, the minor version may be bumped. + * If there are API breaking changes, the major version must be bumped. + * If there are only small minor changes, the patch version may be bumped. + * Update the CHANGELOG + * Update the Modulefile + * Commit these changes with a message along the lines of "Update CHANGELOG and + Modulefile for release" + * Create an annotated tag with git tag -a vX.Y.Z -m 'version X.Y.Z' (NOTE the + leading v as per semver.org) + * Push the tag with git push origin --tags + * Build a new package with puppet-module or the rake build task if it exists + * Publish the new package to the forge + * Bonus points for an announcement to puppet-users. diff --git a/modules/stdlib/Rakefile b/modules/stdlib/Rakefile new file mode 100644 index 0000000..4ed1327 --- /dev/null +++ b/modules/stdlib/Rakefile @@ -0,0 +1,18 @@ +require 'rubygems' +require 'puppetlabs_spec_helper/rake_tasks' +require 'puppet-lint/tasks/puppet-lint' +PuppetLint.configuration.send('disable_80chars') +PuppetLint.configuration.ignore_paths = ["spec/**/*.pp", "pkg/**/*.pp"] + +desc "Validate manifests, templates, and ruby files in lib." +task :validate do + Dir['manifests/**/*.pp'].each do |manifest| + sh "puppet parser validate --noop #{manifest}" + end + Dir['lib/**/*.rb'].each do |lib_file| + sh "ruby -c #{lib_file}" + end + Dir['templates/**/*.erb'].each do |template| + sh "erb -P -x -T '-' #{template} | ruby -c" + end +end diff --git a/modules/stdlib/checksums.json b/modules/stdlib/checksums.json new file mode 100644 index 0000000..a423e04 --- /dev/null +++ b/modules/stdlib/checksums.json @@ -0,0 +1,349 @@ +{ + "CHANGELOG.md": "a3a77d93597fffb4b829b6b56e5d2f16", + "CONTRIBUTING.md": "7fcaaec4913b3d7c123510329ecc4b2d", + "Gemfile": "38895f95212fe38cf47474a05cff2ad2", + "Gemfile.lock": "381b13f5540032a5b9c731766d25c13a", + "LICENSE": "38a048b9d82e713d4e1b2573e370a756", + "Modulefile": "ee2ec9280b87e32529db8b20cf6b1a19", + "README.markdown": "21410cab41d903b5c39c55739846b6b3", + "README_DEVELOPER.markdown": "220a8b28521b5c5d2ea87c4ddb511165", + "README_SPECS.markdown": "82bb4c6abbb711f40778b162ec0070c1", + "RELEASE_PROCESS.markdown": "94b92bc99ac4106ba1a74d5c04e520f9", + "Rakefile": "dfa334598bfd087adf11533a72d71106", + "lib/facter/facter_dot_d.rb": "1f1fcf1bde3443e42a445d3573602304", + "lib/facter/pe_version.rb": "4a9353952963b011759f3e6652a10da5", + "lib/facter/puppet_vardir.rb": "c7ddc97e8a84ded3dd93baa5b9b3283d", + "lib/facter/root_home.rb": "d9c8276acdceb7340d95f60c36dcdcc5", + "lib/facter/util/puppet_settings.rb": "9f1d2593d0ae56bfca89d4b9266aeee1", + "lib/puppet/parser/functions/abs.rb": "32161bd0435fdfc2aec2fc559d2b454b", + "lib/puppet/parser/functions/any2array.rb": "a81e71d6b67a551d38770ba9a1948a75", + "lib/puppet/parser/functions/base64.rb": "ae25adf92295df67ebd9edfabc9ecdd6", + "lib/puppet/parser/functions/bool2num.rb": "8e627eee990e811e35e7e838c586bd77", + "lib/puppet/parser/functions/capitalize.rb": "14481fc8c7c83fe002066ebcf6722f17", + "lib/puppet/parser/functions/chomp.rb": "719d46923d75251f7b6b68b6e015cccc", + "lib/puppet/parser/functions/chop.rb": "4691a56e6064b792ed4575e4ad3f3d20", + "lib/puppet/parser/functions/concat.rb": "c522e67e558336e1ac26b0a3cfeeed2d", + "lib/puppet/parser/functions/count.rb": "9eb74eccd93e2b3c87fd5ea14e329eba", + "lib/puppet/parser/functions/deep_merge.rb": "d83696855578fb81b64b9e92b9c7cc7c", + "lib/puppet/parser/functions/defined_with_params.rb": "ffab4433d03f32b551f2ea024a2948fc", + "lib/puppet/parser/functions/delete.rb": "96e569dac96b8c9387e9303445d73048", + "lib/puppet/parser/functions/delete_at.rb": "6bc24b79390d463d8be95396c963381a", + "lib/puppet/parser/functions/delete_undef_values.rb": "b32d4a3925753b2eb2c318cbd7f14404", + "lib/puppet/parser/functions/delete_values.rb": "39b147f7d369bb5f809044b6341954a2", + "lib/puppet/parser/functions/difference.rb": "e31b95fbaf974cf853a510177368bfb9", + "lib/puppet/parser/functions/dirname.rb": "bef7214eb89db3eb8f7ee5fc9dca0233", + "lib/puppet/parser/functions/downcase.rb": "9204a04c2a168375a38d502db8811bbe", + "lib/puppet/parser/functions/empty.rb": "ae92905c9d94ddca30bf56b7b1dabedf", + "lib/puppet/parser/functions/ensure_packages.rb": "fbed5c0c9bf82b7746e01f15f89d184f", + "lib/puppet/parser/functions/ensure_resource.rb": "6678127386e77bbc0f09db7b5a32ab6a", + "lib/puppet/parser/functions/flatten.rb": "25777b76f9719162a8bab640e5595b7a", + "lib/puppet/parser/functions/floor.rb": "42cad4c689231a51526c55a6f0985d1f", + "lib/puppet/parser/functions/fqdn_rotate.rb": "20743a138c56fc806a35cb7b60137dbc", + "lib/puppet/parser/functions/get_module_path.rb": "d4bf50da25c0b98d26b75354fa1bcc45", + "lib/puppet/parser/functions/getparam.rb": "4dd7a0e35f4a3780dcfc9b19b4e0006e", + "lib/puppet/parser/functions/getvar.rb": "10bf744212947bc6a7bfd2c9836dbd23", + "lib/puppet/parser/functions/grep.rb": "5682995af458b05f3b53dd794c4bf896", + "lib/puppet/parser/functions/has_interface_with.rb": "8d3ebca805dc6edb88b6b7a13d404787", + "lib/puppet/parser/functions/has_ip_address.rb": "ee207f47906455a5aa49c4fb219dd325", + "lib/puppet/parser/functions/has_ip_network.rb": "b4d726c8b2a0afac81ced8a3a28aa731", + "lib/puppet/parser/functions/has_key.rb": "7cd9728c38f0b0065f832dabd62b0e7e", + "lib/puppet/parser/functions/hash.rb": "9d072527dfc7354b69292e9302906530", + "lib/puppet/parser/functions/intersection.rb": "924ac4aceec7b896952166a7ec08fdb1", + "lib/puppet/parser/functions/is_array.rb": "875ca4356cb0d7a10606fb146b4a3d11", + "lib/puppet/parser/functions/is_bool.rb": "e693b7c4b5366cff1380b6e0c7dd7b11", + "lib/puppet/parser/functions/is_domain_name.rb": "cf72726c0fec831eb703ec9deea739eb", + "lib/puppet/parser/functions/is_float.rb": "10e0d3ecf75fac15e415aee79acf70dc", + "lib/puppet/parser/functions/is_function_available.rb": "628428bbcd9313ce09783d9484330e09", + "lib/puppet/parser/functions/is_hash.rb": "8c7d9a05084dab0389d1b779c8a05b1a", + "lib/puppet/parser/functions/is_integer.rb": "c665be82686aa4729959bb42c66a7510", + "lib/puppet/parser/functions/is_ip_address.rb": "a714a736c1560e8739aaacd9030cca00", + "lib/puppet/parser/functions/is_mac_address.rb": "288bd4b38d4df42a83681f13e7eaaee0", + "lib/puppet/parser/functions/is_numeric.rb": "93ddc9d4c0834a5e5e0562d7b3cdce91", + "lib/puppet/parser/functions/is_string.rb": "2bd9a652bbb2668323eee6c57729ff64", + "lib/puppet/parser/functions/join.rb": "a285a05c015ae278608f6454aef211ea", + "lib/puppet/parser/functions/join_keys_to_values.rb": "f29da49531228f6ca5b3aa0df00a14c2", + "lib/puppet/parser/functions/keys.rb": "eb6ac815ea14fbf423580ed903ef7bad", + "lib/puppet/parser/functions/loadyaml.rb": "2b912f257aa078e376d3b3f6a86c2a00", + "lib/puppet/parser/functions/lstrip.rb": "210b103f78622e099f91cc2956b6f741", + "lib/puppet/parser/functions/max.rb": "f652fd0b46ef7d2fbdb42b141f8fdd1d", + "lib/puppet/parser/functions/member.rb": "541e67d06bc4155e79b00843a125e9bc", + "lib/puppet/parser/functions/merge.rb": "f3dcc5c83440cdda2036cce69b61a14b", + "lib/puppet/parser/functions/min.rb": "0d2a1b7e735ab251c5469e735fa3f4c6", + "lib/puppet/parser/functions/num2bool.rb": "605c12fa518c87ed2c66ae153e0686ce", + "lib/puppet/parser/functions/parsejson.rb": "e7f968c34928107b84cd0860daf50ab1", + "lib/puppet/parser/functions/parseyaml.rb": "00f10ec1e2b050e23d80c256061ebdd7", + "lib/puppet/parser/functions/pick.rb": "bf01f13bbfe2318e7f6a302ac7c4433f", + "lib/puppet/parser/functions/pick_default.rb": "ad3ea60262de408767786d37a54d45dc", + "lib/puppet/parser/functions/prefix.rb": "aebbea0290be82a4ae89ddfffbee1125", + "lib/puppet/parser/functions/range.rb": "17a05dbae8f562f882450f9e648d4e2d", + "lib/puppet/parser/functions/reject.rb": "689f6a7c961a55fe9dcd240921f4c7f9", + "lib/puppet/parser/functions/reverse.rb": "1386371c0f5301055fdf99079e862b3e", + "lib/puppet/parser/functions/rstrip.rb": "8a0d69876bdbc88a2054ba41c9c38961", + "lib/puppet/parser/functions/shuffle.rb": "6445e6b4dc62c37b184a60eeaf34414b", + "lib/puppet/parser/functions/size.rb": "8972d48c0f9e487d659bd7326b40b642", + "lib/puppet/parser/functions/sort.rb": "504b033b438461ca4f9764feeb017833", + "lib/puppet/parser/functions/squeeze.rb": "541f85b4203b55c9931d3d6ecd5c75f8", + "lib/puppet/parser/functions/str2bool.rb": "6320f1a50fd28ec027981cd1fb8ffdd0", + "lib/puppet/parser/functions/str2saltedsha512.rb": "49afad7b386be38ce53deaefef326e85", + "lib/puppet/parser/functions/strftime.rb": "e02e01a598ca5d7d6eee0ba22440304a", + "lib/puppet/parser/functions/strip.rb": "273d547c7b05c0598556464dfd12f5fd", + "lib/puppet/parser/functions/suffix.rb": "109279db4180441e75545dbd5f273298", + "lib/puppet/parser/functions/swapcase.rb": "4902f38f0b9292afec66d40fee4b02ec", + "lib/puppet/parser/functions/time.rb": "08d88d52abd1e230e3a2f82107545d48", + "lib/puppet/parser/functions/to_bytes.rb": "83f23c33adbfa42b2a9d9fc2db3daeb4", + "lib/puppet/parser/functions/type.rb": "62f914d6c90662aaae40c5539701be60", + "lib/puppet/parser/functions/union.rb": "137998fe47decf25aede20f0c0155a4c", + "lib/puppet/parser/functions/unique.rb": "217ccce6d23235af92923f50f8556963", + "lib/puppet/parser/functions/upcase.rb": "a5744a74577cfa136fca2835e75888d3", + "lib/puppet/parser/functions/uriescape.rb": "321b8d2c33a5ea48337e1293774db4e0", + "lib/puppet/parser/functions/validate_absolute_path.rb": "385137ac24a2dec6cecc4e6ea75be442", + "lib/puppet/parser/functions/validate_array.rb": "72b29289b8af1cfc3662ef9be78911b8", + "lib/puppet/parser/functions/validate_augeas.rb": "d4acca7b8a9fdada9ae39e5101902cc1", + "lib/puppet/parser/functions/validate_bool.rb": "a712634a000024398b3c6cd4ecc46463", + "lib/puppet/parser/functions/validate_cmd.rb": "78fd21cb3fc52efc3b53ba2b3301de18", + "lib/puppet/parser/functions/validate_hash.rb": "e9cfaca68751524efe16ecf2f958a9a0", + "lib/puppet/parser/functions/validate_ipv4_address.rb": "a8fb6f0ca36aa460d462c07c2af5d5a2", + "lib/puppet/parser/functions/validate_ipv6_address.rb": "4699238e4cad60e7e1428905523eaeb7", + "lib/puppet/parser/functions/validate_re.rb": "c6664b3943bc820415a43f16372dc2a9", + "lib/puppet/parser/functions/validate_slength.rb": "7e67c213509b9383707819cc612b2a29", + "lib/puppet/parser/functions/validate_string.rb": "6afcbc51f83f0714348b8d61e06ea7eb", + "lib/puppet/parser/functions/values.rb": "066a6e4170e5034edb9a80463dff2bb5", + "lib/puppet/parser/functions/values_at.rb": "094ac110ce9f7a5b16d0c80a0cf2243c", + "lib/puppet/parser/functions/zip.rb": "a80782461ed9465f0cd0c010936f1855", + "lib/puppet/provider/file_line/ruby.rb": "10d65268d2d1e75b5dae014974b79d60", + "lib/puppet/type/anchor.rb": "bbd36bb49c3b554f8602d8d3df366c0c", + "lib/puppet/type/file_line.rb": "a1eceef6bd7cbfe99892cf3ee57ef2b4", + "manifests/init.pp": "f2ba5f36e7227ed87bbb69034fc0de8b", + "manifests/stages.pp": "cc6ed1751d334b0ea278c0335c7f0b5a", + "metadata.json": "42591a032ab4a712a52a294148361090", + "spec/acceptance/abs_spec.rb": "435478ef1ba43a6cca1f7b4db14a4bcc", + "spec/acceptance/any2array_spec.rb": "78187dc3683c8ecd15774d99024de47d", + "spec/acceptance/base64_spec.rb": "1684d5dd176dd5bbd4c3c6b1e64fbcea", + "spec/acceptance/bool2num_spec.rb": "c5e3aadb08a437f181247429f4125bab", + "spec/acceptance/build_csv.rb": "f28ef587de764ade1513091c4906412c", + "spec/acceptance/capitalize_spec.rb": "e77ea2c37144a75a67969c0d0839adfd", + "spec/acceptance/chomp_spec.rb": "fb0862a6b7eeb3c290e280788e705061", + "spec/acceptance/chop_spec.rb": "0bd1065b9c16a54b86adeb4e3be041fb", + "spec/acceptance/concat_spec.rb": "3a0dae19a34bb13d406c8e0ec87d8fe5", + "spec/acceptance/count_spec.rb": "5b35e597ae1051f41431812707d4b502", + "spec/acceptance/deep_merge_spec.rb": "c335a947f1666e185e0210e661f1c78a", + "spec/acceptance/defined_with_params_spec.rb": "f27c54ade9872c63c69316f62b03c119", + "spec/acceptance/delete_at_spec.rb": "9c028b703ee0286565c9877757678f3f", + "spec/acceptance/delete_spec.rb": "31e6dfcb9cc7c16b20d47c00e6a85a1d", + "spec/acceptance/delete_undef_values_spec.rb": "6e6a66aee0c383c843b5f92ef8c8410c", + "spec/acceptance/delete_values_spec.rb": "22c9b4914d4cbc0153aa3862cb4fb50e", + "spec/acceptance/difference_spec.rb": "289f4f1788feaacb304ffd54971c7e7e", + "spec/acceptance/dirname_spec.rb": "84db53878c4400a6c684c924cff05cfc", + "spec/acceptance/downcase_spec.rb": "0f094849b94a94df491ee01186473104", + "spec/acceptance/empty_spec.rb": "35c1f43e8a3e1fe7dd4335ef86e7efcc", + "spec/acceptance/ensure_packages_spec.rb": "d4c02a9313e2b8339d9e4a2f5b200e0e", + "spec/acceptance/ensure_resource_spec.rb": "9e03216abb2431e749be76a4302931df", + "spec/acceptance/flatten_spec.rb": "83fb08cc168a105c1d5d0df66b1d9e84", + "spec/acceptance/floor_spec.rb": "d7267b2914b1da6406224abb7489ca86", + "spec/acceptance/fqdn_rotate_spec.rb": "a1fa84292395adec3c47b21c3dc79ec3", + "spec/acceptance/get_module_path_spec.rb": "6a6552ff8d6d75ce795b0139c68a7993", + "spec/acceptance/getparam_spec.rb": "b62a47524f434b903f9e155ad56959b3", + "spec/acceptance/getvar_spec.rb": "ba2f081a88be97c0e7004a6296294f23", + "spec/acceptance/grep_spec.rb": "98818b8b0557b80d6ff519f70ea7617c", + "spec/acceptance/has_interface_with_spec.rb": "467183aeada0bec74143be6cf0b89a3d", + "spec/acceptance/has_ip_address_spec.rb": "e0369b12725695c528e2d47b8ea2b4d8", + "spec/acceptance/has_ip_network_spec.rb": "ca8dd6faa6df940784a60a49bec1330d", + "spec/acceptance/has_key_spec.rb": "6509a26a0886f7d591eaa926b2f92407", + "spec/acceptance/hash_spec.rb": "1c626457ba056bdd3936e28aa5bf503e", + "spec/acceptance/intersection_spec.rb": "40f586af7f95408a5d4a2882a4aa98f1", + "spec/acceptance/is_array_spec.rb": "c2ff70ce59b90b50a5aed67abaa5399d", + "spec/acceptance/is_bool_spec.rb": "c001fdecff6b0a3c9dc78774987a0b15", + "spec/acceptance/is_domain_name_spec.rb": "63e84285c26d8717fd5d4dda01e3f432", + "spec/acceptance/is_float_spec.rb": "2f0164b4d732166aa46055a2cf7b4ea9", + "spec/acceptance/is_function_available_spec.rb": "7745eba89f8719c9ca7ebf04d5b005f7", + "spec/acceptance/is_hash_spec.rb": "cff723cd8fddac45033af5dc8406d4e4", + "spec/acceptance/is_integer_spec.rb": "c09201d17d3914bba197872897fa3413", + "spec/acceptance/is_ip_address_spec.rb": "aa14cf9abf404c3fe1e761ea957871fe", + "spec/acceptance/is_mac_address_spec.rb": "30ff4c6a63be58daa3568305617ca2a7", + "spec/acceptance/is_numeric_spec.rb": "fb9829c7a1a8d4a58836df6ff4c3386d", + "spec/acceptance/is_string_spec.rb": "df3022de123b72f0022728eb2d8ce857", + "spec/acceptance/join_keys_to_values_spec.rb": "8aa128bbaeea65aab8d92badee3ca2b5", + "spec/acceptance/join_spec.rb": "c6378ed481265152bba9871fc5501ee6", + "spec/acceptance/keys_spec.rb": "20486e3ebee53e50dc9de3b78b9d6ae6", + "spec/acceptance/loadyaml_spec.rb": "5bce9c4b90e73bccdcd4f66fc988676b", + "spec/acceptance/lstrip_spec.rb": "e29ab4039b65660ec2bd76a298adcae0", + "spec/acceptance/max_spec.rb": "209cda4b83d677743afb1a8870330618", + "spec/acceptance/member_spec.rb": "0dac8ec7c7f670fca429fc26cf8ccc14", + "spec/acceptance/merge_spec.rb": "ac61d7627c66565a3a5cbfb2f9db21eb", + "spec/acceptance/min_spec.rb": "152a7db28434a0d0378561d4f64cddcc", + "spec/acceptance/nodesets/centos-6-vcloud.yml": "bdf9ce9d3b0f0b4995666ae9d64d878d", + "spec/acceptance/nodesets/centos-64-x64-pe.yml": "ec075d95760df3d4702abea1ce0a829b", + "spec/acceptance/nodesets/centos-64-x64.yml": "092dd2c588a9f87fa1fb12997c0723ef", + "spec/acceptance/nodesets/default.yml": "3e5c36e6aa5a690229e720f4048bb8af", + "spec/acceptance/nodesets/fedora-18-x64.yml": "80e41b1ee16ea489f53164bfdae58855", + "spec/acceptance/nodesets/sles-11-x64.yml": "44e4c6c15c018333bfa9840a5e702f66", + "spec/acceptance/nodesets/ubuntu-server-10044-x64.yml": "75e86400b7889888dc0781c0ae1a1297", + "spec/acceptance/nodesets/ubuntu-server-12042-x64.yml": "d30d73e34cd50b043c7d14e305955269", + "spec/acceptance/num2bool_spec.rb": "e4a00b913b08c68a689837e9f9336cb2", + "spec/acceptance/parsejson_spec.rb": "ea3973d412ad6f72425fdfac6fbb2bb4", + "spec/acceptance/parseyaml_spec.rb": "7bbfeed73d0626f69daedfc151957967", + "spec/acceptance/pick_default_spec.rb": "1bc2562380ef6f6cded5ec90a03922be", + "spec/acceptance/pick_spec.rb": "272c54c8f9398f499768331bdb4276ee", + "spec/acceptance/prefix_spec.rb": "da620568c6771e7d492ec1ff697c531c", + "spec/acceptance/range_spec.rb": "65e5b98ceca257658604d988fbec7d03", + "spec/acceptance/reject_spec.rb": "b5185f1a6071c9bdc7aca92e6f899c3e", + "spec/acceptance/reverse_spec.rb": "7bdee543e82532e97bbf7a067140031c", + "spec/acceptance/rstrip_spec.rb": "28a64ceb7cb5ae8a93d31f49816190ab", + "spec/acceptance/shuffle_spec.rb": "8a8652e57d56f2b4946cdf4d20052b7a", + "spec/acceptance/size_spec.rb": "ae17d8a55921a0570972200c7c9327e1", + "spec/acceptance/sort_spec.rb": "d44b1b8c090f0f00a2f38515fda431ea", + "spec/acceptance/squeeze_spec.rb": "adcd65fa4e72203b97f1f14c8835c2cd", + "spec/acceptance/str2bool_spec.rb": "55ad165ceef6b9ba32bf20ca3b53b44c", + "spec/acceptance/str2saltedsha512_spec.rb": "b684c4214d06ae3d5bae055262a5ccaa", + "spec/acceptance/strftime_spec.rb": "0f4eadbd74445b35de4a42c9790fbcc1", + "spec/acceptance/strip_spec.rb": "6767da5bc735beb5362aeee6ff692c9e", + "spec/acceptance/suffix_spec.rb": "07dfc7eed48b75fcc1b93d0308243eda", + "spec/acceptance/swapcase_spec.rb": "5c3c1bc19a09fed6e01881f79b0b4ea5", + "spec/acceptance/time_spec.rb": "044b2f634a1fa6ecc735998d68a93b73", + "spec/acceptance/to_bytes_spec.rb": "f9df1f234b9409f5eaf56ef24e651c36", + "spec/acceptance/type_spec.rb": "d103a7e1607ab9cea74cdef25af610b0", + "spec/acceptance/union_spec.rb": "b6092941e0574f3c60910bebf84d2844", + "spec/acceptance/unique_spec.rb": "9b00b21cefde3b5391f50eeb9cd2493b", + "spec/acceptance/unsupported_spec.rb": "09b9265ecb05252cd5e5a18327c7ae97", + "spec/acceptance/upcase_spec.rb": "ffd1d6f9e6ec24131fb78983c53a75f9", + "spec/acceptance/uriescape_spec.rb": "13daa387714cbfc63b587aaa8dbf7fcd", + "spec/acceptance/validate_absolute_path_spec.rb": "8b9ebfae80329231d84fcab606a3eeaf", + "spec/acceptance/validate_array_spec.rb": "382641719e754622ffae562d10e38bf7", + "spec/acceptance/validate_augeas_spec.rb": "ec0a9c030e2c3494889973d74d60b2a4", + "spec/acceptance/validate_bool_spec.rb": "08bc139459204cf0a35098a5bc30ab95", + "spec/acceptance/validate_cmd_spec.rb": "d08eacac4dd5bdb50b5b0f02a6494048", + "spec/acceptance/validate_hash_spec.rb": "70ceacc18a0dee97b26ab2e50f925706", + "spec/acceptance/validate_ipv4_address_spec.rb": "dc901bbd05c3764a93cb49154cea6e4b", + "spec/acceptance/validate_ipv6_address_spec.rb": "c0872c56230ac2800cd5723eaa5bc53a", + "spec/acceptance/validate_re_spec.rb": "b289909078d6ae0d015419f518566698", + "spec/acceptance/validate_slength_spec.rb": "f0a05c1c2b895b096cb7326df4821594", + "spec/acceptance/validate_string_spec.rb": "6c9ced99fb1e263e66e25427d24f8f7b", + "spec/acceptance/values_at_spec.rb": "669b26c4d47742051472003518c3aa61", + "spec/acceptance/values_spec.rb": "714a13735aa0db3ffd3dfc4cd2c2e330", + "spec/acceptance/zip_spec.rb": "0a76aa26bd9552b8dae3294af7d233ab", + "spec/classes/anchor_spec.rb": "40600ba2845f9bd360a9504a347f12ba", + "spec/fixtures/dscacheutil/root": "e1a7622f55f3d1be258c9a5b16b474be", + "spec/fixtures/manifests/site.pp": "d41d8cd98f00b204e9800998ecf8427e", + "spec/functions/abs_spec.rb": "0a5864a29a8e9e99acc483268bd5917c", + "spec/functions/any2array_spec.rb": "167e114cfa222de971bf8be141766b6a", + "spec/functions/base64_spec.rb": "fe16d992be54dbb06d040f1b0e189571", + "spec/functions/bool2num_spec.rb": "67c3055d5d4e4c9fbcaca82038a09081", + "spec/functions/capitalize_spec.rb": "82a4209a033fc88c624f708c12e64e2a", + "spec/functions/chomp_spec.rb": "3cd8e2fe6b12efeffad94cce5b693b7c", + "spec/functions/chop_spec.rb": "4e9534d25b952b261c9f46add677c390", + "spec/functions/concat_spec.rb": "d7657b1af27a96072aae711cee041181", + "spec/functions/count_spec.rb": "db98ef89752a7112425f0aade10108e0", + "spec/functions/deep_merge_spec.rb": "7961a696e1b45167cead127f841f1c99", + "spec/functions/defined_with_params_spec.rb": "3bdfac38e3d6f06140ff2e926f4ebed2", + "spec/functions/delete_at_spec.rb": "7fd4fe7db8d213925fbc80c992673d10", + "spec/functions/delete_spec.rb": "fe66bdf9e61b9c992bc73ee54a37035c", + "spec/functions/delete_undef_values_spec.rb": "83b9c3027463f5c8a90a6d47d219acd5", + "spec/functions/delete_values_spec.rb": "ddcaa269caa95ad926b8a3ef82976da9", + "spec/functions/difference_spec.rb": "e64c1501699fef8eb1037a3ca60a05a6", + "spec/functions/dirname_spec.rb": "1d7cf70468c2cfa6dacfc75935322395", + "spec/functions/downcase_spec.rb": "b0197829512f2e92a2d2b06ce8e2226f", + "spec/functions/empty_spec.rb": "028c30267d648a172d8a81a9262c3abe", + "spec/functions/ensure_packages_spec.rb": "f1b60599078cdcb3cff1368346108264", + "spec/functions/ensure_resource_spec.rb": "7765dde3b9fc54b7dddb6597e0f7b523", + "spec/functions/flatten_spec.rb": "583c9a70f93e492cfb22ffa1811f6aa0", + "spec/functions/floor_spec.rb": "d01ef7dfe0245d7a0a73d7df13cb02e3", + "spec/functions/fqdn_rotate_spec.rb": "c67b71737bee9936f5261d41a37bad46", + "spec/functions/get_module_path_spec.rb": "b7ea196f548b1a9a745ab6671295ab27", + "spec/functions/getparam_spec.rb": "75153d949eb122aa18f0c5e2c8e861e5", + "spec/functions/getvar_spec.rb": "842bf88d47077a9ae64097b6e39c3364", + "spec/functions/grep_spec.rb": "78179537496a7150469e591a95e255d8", + "spec/functions/has_interface_with_spec.rb": "7c16d731c518b434c81b8cb2227cc916", + "spec/functions/has_ip_address_spec.rb": "f53c7baeaf024ff577447f6c28c0f3a7", + "spec/functions/has_ip_network_spec.rb": "885ea8a4c987b735d683b742bf846cb1", + "spec/functions/has_key_spec.rb": "3e4e730d98bbdfb88438b6e08e45868e", + "spec/functions/hash_spec.rb": "826337a92d8f7a189b7ac19615db0ed7", + "spec/functions/intersection_spec.rb": "1b1f1a3900a1f1e165692b056e766fba", + "spec/functions/is_array_spec.rb": "8c020af9c360abdbbf1ba887bb26babe", + "spec/functions/is_bool_spec.rb": "3219ba1500de75161bfb4f292404d1fa", + "spec/functions/is_domain_name_spec.rb": "8eed3a9eb9334bf6a473ad4e2cabc2ec", + "spec/functions/is_float_spec.rb": "171fc0e382d9856c2d8db2b70c9ec9cd", + "spec/functions/is_function_available.rb": "c8858a3c6253713cce0113a98d229b5d", + "spec/functions/is_hash_spec.rb": "408e121a5e30c4c5c4a0a383beb6e209", + "spec/functions/is_integer_spec.rb": "c848f20da5f62ac4bbaf0f6c1485c88f", + "spec/functions/is_ip_address_spec.rb": "6040a9bae4e5c853966148b634501157", + "spec/functions/is_mac_address_spec.rb": "644cd498b426ff2f9ea9cbc5d8e141d7", + "spec/functions/is_numeric_spec.rb": "65f2ad0e70d9b60c601740351eba94fd", + "spec/functions/is_string_spec.rb": "5c015d8267de852da3a12b984e077092", + "spec/functions/join_keys_to_values_spec.rb": "7c7937411b7fe4bb944c0c022d3a96b0", + "spec/functions/join_spec.rb": "c3b50c39390a86b493511be2c6722235", + "spec/functions/keys_spec.rb": "35cc2ed490dc68da6464f245dfebd617", + "spec/functions/loadyaml_spec.rb": "ce86614d8aaceec93653ecf299d3d441", + "spec/functions/lstrip_spec.rb": "1fc2c2d80b5f724a358c3cfeeaae6249", + "spec/functions/max_spec.rb": "5562bccc643443af7e4fa7c9d1e52b8b", + "spec/functions/member_spec.rb": "067c60985efc57022ca1c5508d74d77f", + "spec/functions/merge_spec.rb": "c17a7244453f2da22970acc02a6de110", + "spec/functions/min_spec.rb": "bf80bf58261117bb24392670b624a611", + "spec/functions/num2bool_spec.rb": "8cd5b46b7c8e612dfae3362e3a68a5f9", + "spec/functions/parsejson_spec.rb": "37ab84381e035c31d6a3dd9bf73a3d53", + "spec/functions/parseyaml_spec.rb": "65dfed872930ffe0d21954c15daaf498", + "spec/functions/pick_default_spec.rb": "db0a9d261b7e1b82e2786716dd924e92", + "spec/functions/pick_spec.rb": "34382f7483b6c10d38831de2169777c2", + "spec/functions/prefix_spec.rb": "7245749e27bafe1b36c1c5bae6f705c7", + "spec/functions/range_spec.rb": "c40b3c6d4031fc541c2421ff7b8c41fe", + "spec/functions/reject_spec.rb": "8e16c9f064870e958b6278261e480954", + "spec/functions/reverse_spec.rb": "48169990e59081ccbd112b6703418ce4", + "spec/functions/rstrip_spec.rb": "a408e933753c9c323a05d7079d32cbb3", + "spec/functions/shuffle_spec.rb": "2141a54d2fb3cf725b88184d639677f4", + "spec/functions/size_spec.rb": "d126b696b21a8cd754d58f78ddba6f06", + "spec/functions/sort_spec.rb": "7039cd230a94e95d9d1de2e1094acae2", + "spec/functions/squeeze_spec.rb": "df5b349c208a9a2a4d4b8e6d9324756f", + "spec/functions/str2bool_spec.rb": "e2a8a4d39680f3ed18621e26d67c6024", + "spec/functions/str2saltedsha512_spec.rb": "1de174be8835ba6fef86b590887bb2cc", + "spec/functions/strftime_spec.rb": "bf140883ecf3254277306fa5b25f0344", + "spec/functions/strip_spec.rb": "a01796bebbdabd3fad12b0662ea5966e", + "spec/functions/suffix_spec.rb": "ee875e2d09d7ffc363bf6c34d9ef322f", + "spec/functions/swapcase_spec.rb": "0660ce8807608cc8f98ad1edfa76a402", + "spec/functions/time_spec.rb": "b6d0279062779efe5153fe5cfafc5bbd", + "spec/functions/to_bytes_spec.rb": "80aaf68cf7e938e46b5278c1907af6be", + "spec/functions/type_spec.rb": "422f2c33458fe9b0cc9614d16f7573ba", + "spec/functions/union_spec.rb": "c4f72a55e186813cd3a47a83ba3e9a61", + "spec/functions/unique_spec.rb": "2df8b3b2edb9503943cb4dcb4a371867", + "spec/functions/upcase_spec.rb": "813668919bc62cdd1d349dafc19fbbb3", + "spec/functions/uriescape_spec.rb": "204e9b1566e330a0234761ac8ac7083f", + "spec/functions/validate_absolute_path_spec.rb": "5a0b98675070e511810dab9e60dc43b6", + "spec/functions/validate_array_spec.rb": "bcd231229554785c4270ca92ef99cb60", + "spec/functions/validate_augeas_spec.rb": "eee1a0c3ef3051bda525b1e17d577ab0", + "spec/functions/validate_bool_spec.rb": "7aeb6085fc9601c6bbe6c49e56d209a4", + "spec/functions/validate_cmd_spec.rb": "efc88e8e21481acd36c7f948b1f226ea", + "spec/functions/validate_hash_spec.rb": "8529c74051ceb71e6b1b97c9cecdf625", + "spec/functions/validate_ipv4_address_spec.rb": "19f2f44fbbdf7a2e69aeaa2f0f402695", + "spec/functions/validate_ipv6_address_spec.rb": "2d8617be4405bdbd84d140ba8be6c184", + "spec/functions/validate_re_spec.rb": "d8ab477f9afcb748f144588ebb3a28a3", + "spec/functions/validate_slength_spec.rb": "73273a083a26941b3f7c1e3b2e18b3e2", + "spec/functions/validate_string_spec.rb": "64a4f681084cba55775a070f7fab5e0c", + "spec/functions/values_at_spec.rb": "de45fd8abbc4c037c3c4fac2dcf186f9", + "spec/functions/values_spec.rb": "0ac9e141ed1f612d7cc224f747b2d1d9", + "spec/functions/zip_spec.rb": "06a86e4e70d2aea63812582aae1d26c4", + "spec/lib/puppet_spec/compiler.rb": "3c1f03dd8ac2f6f90d7e8f879a3ce4c0", + "spec/lib/puppet_spec/database.rb": "c74c0cf62980beea88c7749f876ccfa7", + "spec/lib/puppet_spec/files.rb": "906da85e399302cee403e10e357d3f4c", + "spec/lib/puppet_spec/fixtures.rb": "0722c5ccbfcba1fc27da1900e54b4463", + "spec/lib/puppet_spec/matchers.rb": "dd30ba6b936e8c267511d67acb087c35", + "spec/lib/puppet_spec/modules.rb": "445d2739aa8754568a14816280727d70", + "spec/lib/puppet_spec/pops.rb": "adf661defa460b7189e3750535533d34", + "spec/lib/puppet_spec/scope.rb": "01aeb89bdc2d29a2528ced26ec6402ec", + "spec/lib/puppet_spec/settings.rb": "5da4e0dad8bf6b21cc4437c73753a56d", + "spec/lib/puppet_spec/verbose.rb": "71dbccd9a45ed89d12fd1c44456a6820", + "spec/monkey_patches/alias_should_to_must.rb": "b19ee31563afb91a72f9869f9d7362ff", + "spec/monkey_patches/publicize_methods.rb": "c690e444b77c871375d321e413e28ca1", + "spec/spec.opts": "a600ded995d948e393fbe2320ba8e51c", + "spec/spec_helper.rb": "846cc69a2d612d55d130622759aa12e0", + "spec/spec_helper_acceptance.rb": "d82b5682eac4ff46bbe5aa08c29d5e28", + "spec/unit/facter/facter_dot_d_spec.rb": "cce0748b2671b1b104332a7c757e5206", + "spec/unit/facter/pe_version_spec.rb": "ef031cca838f36f99b1dab3259df96a5", + "spec/unit/facter/root_home_spec.rb": "ecd851e2b8a4a8578960cce094cf41ee", + "spec/unit/facter/util/puppet_settings_spec.rb": "8666142d017e5804445f5596f3be76e8", + "spec/unit/puppet/provider/file_line/ruby_spec.rb": "e118a65a3eb0ccd3d1bf99d7bb010669", + "spec/unit/puppet/type/anchor_spec.rb": "3c3251acbc1085b121623f4617107fb9", + "spec/unit/puppet/type/file_line_spec.rb": "72ba1d9ad9de5df592f3ff03551983cb", + "tests/file_line.pp": "67727539aa7b7dd76f06626fe734f7f7", + "tests/has_interface_with.pp": "59c98b4af0d39fc11d1ef4c7a6dc8f7a", + "tests/has_ip_address.pp": "93ce02915f67ddfb43a049b2b84ef391", + "tests/has_ip_network.pp": "abc05686797a776ea8c054657e6f7456", + "tests/init.pp": "1d98070412c76824e66db4b7eb74d433" +} \ No newline at end of file diff --git a/modules/stdlib/lib/facter/facter_dot_d.rb b/modules/stdlib/lib/facter/facter_dot_d.rb new file mode 100644 index 0000000..2c096b0 --- /dev/null +++ b/modules/stdlib/lib/facter/facter_dot_d.rb @@ -0,0 +1,202 @@ +# A Facter plugin that loads facts from /etc/facter/facts.d +# and /etc/puppetlabs/facter/facts.d. +# +# Facts can be in the form of JSON, YAML or Text files +# and any executable that returns key=value pairs. +# +# In the case of scripts you can also create a file that +# contains a cache TTL. For foo.sh store the ttl as just +# a number in foo.sh.ttl +# +# The cache is stored in /tmp/facts_cache.yaml as a mode +# 600 file and will have the end result of not calling your +# fact scripts more often than is needed + +class Facter::Util::DotD + require 'yaml' + + def initialize(dir="/etc/facts.d", cache_file="/tmp/facts_cache.yml") + @dir = dir + @cache_file = cache_file + @cache = nil + @types = {".txt" => :txt, ".json" => :json, ".yaml" => :yaml} + end + + def entries + Dir.entries(@dir).reject{|f| f =~ /^\.|\.ttl$/}.sort.map {|f| File.join(@dir, f) } + rescue + [] + end + + def fact_type(file) + extension = File.extname(file) + + type = @types[extension] || :unknown + + type = :script if type == :unknown && File.executable?(file) + + return type + end + + def txt_parser(file) + File.readlines(file).each do |line| + if line =~ /^([^=]+)=(.+)$/ + var = $1; val = $2 + + Facter.add(var) do + setcode { val } + end + end + end + rescue Exception => e + Facter.warn("Failed to handle #{file} as text facts: #{e.class}: #{e}") + end + + def json_parser(file) + begin + require 'json' + rescue LoadError + retry if require 'rubygems' + raise + end + + JSON.load(File.read(file)).each_pair do |f, v| + Facter.add(f) do + setcode { v } + end + end + rescue Exception => e + Facter.warn("Failed to handle #{file} as json facts: #{e.class}: #{e}") + end + + def yaml_parser(file) + require 'yaml' + + YAML.load_file(file).each_pair do |f, v| + Facter.add(f) do + setcode { v } + end + end + rescue Exception => e + Facter.warn("Failed to handle #{file} as yaml facts: #{e.class}: #{e}") + end + + def script_parser(file) + result = cache_lookup(file) + ttl = cache_time(file) + + unless result + result = Facter::Util::Resolution.exec(file) + + if ttl > 0 + Facter.debug("Updating cache for #{file}") + cache_store(file, result) + cache_save! + end + else + Facter.debug("Using cached data for #{file}") + end + + result.split("\n").each do |line| + if line =~ /^(.+)=(.+)$/ + var = $1; val = $2 + + Facter.add(var) do + setcode { val } + end + end + end + rescue Exception => e + Facter.warn("Failed to handle #{file} as script facts: #{e.class}: #{e}") + Facter.debug(e.backtrace.join("\n\t")) + end + + def cache_save! + cache = load_cache + File.open(@cache_file, "w", 0600) {|f| f.write(YAML.dump(cache)) } + rescue + end + + def cache_store(file, data) + load_cache + + @cache[file] = {:data => data, :stored => Time.now.to_i} + rescue + end + + def cache_lookup(file) + cache = load_cache + + return nil if cache.empty? + + ttl = cache_time(file) + + if cache[file] + now = Time.now.to_i + + return cache[file][:data] if ttl == -1 + return cache[file][:data] if (now - cache[file][:stored]) <= ttl + return nil + else + return nil + end + rescue + return nil + end + + def cache_time(file) + meta = file + ".ttl" + + return File.read(meta).chomp.to_i + rescue + return 0 + end + + def load_cache + unless @cache + if File.exist?(@cache_file) + @cache = YAML.load_file(@cache_file) + else + @cache = {} + end + end + + return @cache + rescue + @cache = {} + return @cache + end + + def create + entries.each do |fact| + type = fact_type(fact) + parser = "#{type}_parser" + + if respond_to?("#{type}_parser") + Facter.debug("Parsing #{fact} using #{parser}") + + send(parser, fact) + end + end + end +end + + +mdata = Facter.version.match(/(\d+)\.(\d+)\.(\d+)/) +if mdata + (major, minor, patch) = mdata.captures.map { |v| v.to_i } + if major < 2 + # Facter 1.7 introduced external facts support directly + unless major == 1 and minor > 6 + Facter::Util::DotD.new("/etc/facter/facts.d").create + Facter::Util::DotD.new("/etc/puppetlabs/facter/facts.d").create + + # Windows has a different configuration directory that defaults to a vendor + # specific sub directory of the %COMMON_APPDATA% directory. + if Dir.const_defined? 'COMMON_APPDATA' then + windows_facts_dot_d = File.join(Dir::COMMON_APPDATA, 'PuppetLabs', 'facter', 'facts.d') + Facter::Util::DotD.new(windows_facts_dot_d).create + end + end + end +end diff --git a/modules/stdlib/lib/facter/pe_version.rb b/modules/stdlib/lib/facter/pe_version.rb new file mode 100644 index 0000000..0cc0f64 --- /dev/null +++ b/modules/stdlib/lib/facter/pe_version.rb @@ -0,0 +1,53 @@ +# Fact: is_pe, pe_version, pe_major_version, pe_minor_version, pe_patch_version +# +# Purpose: Return various facts about the PE state of the system +# +# Resolution: Uses a regex match against puppetversion to determine whether the +# machine has Puppet Enterprise installed, and what version (overall, major, +# minor, patch) is installed. +# +# Caveats: +# +Facter.add("pe_version") do + setcode do + pe_ver = Facter.value("puppetversion").match(/Puppet Enterprise (\d+\.\d+\.\d+)/) + pe_ver[1] if pe_ver + end +end + +Facter.add("is_pe") do + setcode do + if Facter.value(:pe_version).to_s.empty? then + false + else + true + end + end +end + +Facter.add("pe_major_version") do + confine :is_pe => true + setcode do + if pe_version = Facter.value(:pe_version) + pe_version.to_s.split('.')[0] + end + end +end + +Facter.add("pe_minor_version") do + confine :is_pe => true + setcode do + if pe_version = Facter.value(:pe_version) + pe_version.to_s.split('.')[1] + end + end +end + +Facter.add("pe_patch_version") do + confine :is_pe => true + setcode do + if pe_version = Facter.value(:pe_version) + pe_version.to_s.split('.')[2] + end + end +end diff --git a/modules/stdlib/lib/facter/puppet_vardir.rb b/modules/stdlib/lib/facter/puppet_vardir.rb new file mode 100644 index 0000000..0e6af40 --- /dev/null +++ b/modules/stdlib/lib/facter/puppet_vardir.rb @@ -0,0 +1,26 @@ +# This facter fact returns the value of the Puppet vardir setting for the node +# running puppet or puppet agent. The intent is to enable Puppet modules to +# automatically have insight into a place where they can place variable data, +# regardless of the node's platform. +# +# The value should be directly usable in a File resource path attribute. + + +begin + require 'facter/util/puppet_settings' +rescue LoadError => e + # puppet apply does not add module lib directories to the $LOAD_PATH (See + # #4248). It should (in the future) but for the time being we need to be + # defensive which is what this rescue block is doing. + rb_file = File.join(File.dirname(__FILE__), 'util', 'puppet_settings.rb') + load rb_file if File.exists?(rb_file) or raise e +end + +Facter.add(:puppet_vardir) do + setcode do + # This will be nil if Puppet is not available. + Facter::Util::PuppetSettings.with_puppet do + Puppet[:vardir] + end + end +end diff --git a/modules/stdlib/lib/facter/root_home.rb b/modules/stdlib/lib/facter/root_home.rb new file mode 100644 index 0000000..b4f87ff --- /dev/null +++ b/modules/stdlib/lib/facter/root_home.rb @@ -0,0 +1,32 @@ +# A facter fact to determine the root home directory. +# This varies on PE supported platforms and may be +# reconfigured by the end user. + +module Facter::Util::RootHome + class << self + def get_root_home + root_ent = Facter::Util::Resolution.exec("getent passwd root") + # The home directory is the sixth element in the passwd entry + # If the platform doesn't have getent, root_ent will be nil and we should + # return it straight away. + root_ent && root_ent.split(":")[5] + end + end +end + +Facter.add(:root_home) do + setcode { Facter::Util::RootHome.get_root_home } +end + +Facter.add(:root_home) do + confine :kernel => :darwin + setcode do + str = Facter::Util::Resolution.exec("dscacheutil -q user -a name root") + hash = {} + str.split("\n").each do |pair| + key,value = pair.split(/:/) + hash[key] = value + end + hash['dir'].strip + end +end diff --git a/modules/stdlib/lib/facter/util/puppet_settings.rb b/modules/stdlib/lib/facter/util/puppet_settings.rb new file mode 100644 index 0000000..1ad9452 --- /dev/null +++ b/modules/stdlib/lib/facter/util/puppet_settings.rb @@ -0,0 +1,21 @@ +module Facter + module Util + module PuppetSettings + # This method is intended to provide a convenient way to evaluate a + # Facter code block only if Puppet is loaded. This is to account for the + # situation where the fact happens to be in the load path, but Puppet is + # not loaded for whatever reason. Perhaps the user is simply running + # facter without the --puppet flag and they happen to be working in a lib + # directory of a module. + def self.with_puppet + begin + Module.const_get("Puppet") + rescue NameError + nil + else + yield + end + end + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/abs.rb b/modules/stdlib/lib/puppet/parser/functions/abs.rb new file mode 100644 index 0000000..11d2d7f --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/abs.rb @@ -0,0 +1,36 @@ +# +# abs.rb +# + +module Puppet::Parser::Functions + newfunction(:abs, :type => :rvalue, :doc => <<-EOS + Returns the absolute value of a number, for example -34.56 becomes + 34.56. Takes a single integer and float value as an argument. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "abs(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + + # Numbers in Puppet are often string-encoded which is troublesome ... + if value.is_a?(String) + if value.match(/^-?(?:\d+)(?:\.\d+){1}$/) + value = value.to_f + elsif value.match(/^-?\d+$/) + value = value.to_i + else + raise(Puppet::ParseError, 'abs(): Requires float or ' + + 'integer to work with') + end + end + + # We have numeric value to handle ... + result = value.abs + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/any2array.rb b/modules/stdlib/lib/puppet/parser/functions/any2array.rb new file mode 100644 index 0000000..e71407e --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/any2array.rb @@ -0,0 +1,33 @@ +# +# any2array.rb +# + +module Puppet::Parser::Functions + newfunction(:any2array, :type => :rvalue, :doc => <<-EOS +This converts any object to an array containing that object. Empty argument +lists are converted to an empty array. Arrays are left untouched. Hashes are +converted to arrays of alternating keys and values. + EOS + ) do |arguments| + + if arguments.empty? + return [] + end + + if arguments.length == 1 + if arguments[0].kind_of?(Array) + return arguments[0] + elsif arguments[0].kind_of?(Hash) + result = [] + arguments[0].each do |key, value| + result << key << value + end + return result + end + end + + return arguments + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/base64.rb b/modules/stdlib/lib/puppet/parser/functions/base64.rb new file mode 100644 index 0000000..617ba31 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/base64.rb @@ -0,0 +1,37 @@ +module Puppet::Parser::Functions + + newfunction(:base64, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + + Base64 encode or decode a string based on the command and the string submitted + + Usage: + + $encodestring = base64('encode','thestring') + $decodestring = base64('decode','dGhlc3RyaW5n') + + ENDHEREDOC + + require 'base64' + + raise Puppet::ParseError, ("base64(): Wrong number of arguments (#{args.length}; must be = 2)") unless args.length == 2 + + actions = ['encode','decode'] + + unless actions.include?(args[0]) + raise Puppet::ParseError, ("base64(): the first argument must be one of 'encode' or 'decode'") + end + + unless args[1].is_a?(String) + raise Puppet::ParseError, ("base64(): the second argument must be a string to base64") + end + + case args[0] + when 'encode' + result = Base64.encode64(args[1]) + when 'decode' + result = Base64.decode64(args[1]) + end + + return result + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/bool2num.rb b/modules/stdlib/lib/puppet/parser/functions/bool2num.rb new file mode 100644 index 0000000..9a07a8a --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/bool2num.rb @@ -0,0 +1,49 @@ +# +# bool2num.rb +# + +module Puppet::Parser::Functions + newfunction(:bool2num, :type => :rvalue, :doc => <<-EOS + Converts a boolean to a number. Converts the values: + false, f, 0, n, and no to 0 + true, t, 1, y, and yes to 1 + Requires a single boolean or string as an input. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "bool2num(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + # We can have either true or false, or string which resembles boolean ... + unless [FalseClass, TrueClass, String].include?(klass) + raise(Puppet::ParseError, 'bool2num(): Requires either ' + + 'boolean or string to work with') + end + + if value.is_a?(String) + # We consider all the yes, no, y, n and so on too ... + value = case value + # + # This is how undef looks like in Puppet ... + # We yield 0 (or false if you wish) in this case. + # + when /^$/, '' then false # Empty string will be false ... + when /^(1|t|y|true|yes)$/ then true + when /^(0|f|n|false|no)$/ then false + when /^(undef|undefined)$/ then false # This is not likely to happen ... + else + raise(Puppet::ParseError, 'bool2num(): Unknown type of boolean given') + end + end + + # We have real boolean values as well ... + result = value ? 1 : 0 + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/capitalize.rb b/modules/stdlib/lib/puppet/parser/functions/capitalize.rb new file mode 100644 index 0000000..640d00b --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/capitalize.rb @@ -0,0 +1,34 @@ +# +# capitalize.rb +# + +module Puppet::Parser::Functions + newfunction(:capitalize, :type => :rvalue, :doc => <<-EOS + Capitalizes the first letter of a string or array of strings. + Requires either a single string or an array as an input. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "capitalize(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'capitalize(): Requires either ' + + 'array or string to work with') + end + + if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + result = value.collect { |i| i.is_a?(String) ? i.capitalize : i } + else + result = value.capitalize + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/chomp.rb b/modules/stdlib/lib/puppet/parser/functions/chomp.rb new file mode 100644 index 0000000..4564a00 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/chomp.rb @@ -0,0 +1,35 @@ +# +# chomp.rb +# + +module Puppet::Parser::Functions + newfunction(:chomp, :type => :rvalue, :doc => <<-'EOS' + Removes the record separator from the end of a string or an array of + strings, for example `hello\n` becomes `hello`. + Requires a single string or array as an input. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "chomp(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'chomp(): Requires either ' + + 'array or string to work with') + end + + if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + result = value.collect { |i| i.is_a?(String) ? i.chomp : i } + else + result = value.chomp + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/chop.rb b/modules/stdlib/lib/puppet/parser/functions/chop.rb new file mode 100644 index 0000000..f242af3 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/chop.rb @@ -0,0 +1,37 @@ +# +# chop.rb +# + +module Puppet::Parser::Functions + newfunction(:chop, :type => :rvalue, :doc => <<-'EOS' + Returns a new string with the last character removed. If the string ends + with `\r\n`, both characters are removed. Applying chop to an empty + string returns an empty string. If you wish to merely remove record + separators then you should use the `chomp` function. + Requires a string or array of strings as input. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "chop(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'chop(): Requires either an ' + + 'array or string to work with') + end + + if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + result = value.collect { |i| i.is_a?(String) ? i.chop : i } + else + result = value.chop + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/concat.rb b/modules/stdlib/lib/puppet/parser/functions/concat.rb new file mode 100644 index 0000000..6c86382 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/concat.rb @@ -0,0 +1,41 @@ +# +# concat.rb +# + +module Puppet::Parser::Functions + newfunction(:concat, :type => :rvalue, :doc => <<-EOS +Appends the contents of array 2 onto array 1. + +*Example:* + + concat(['1','2','3'],['4','5','6']) + +Would result in: + + ['1','2','3','4','5','6'] + EOS + ) do |arguments| + + # Check that 2 arguments have been given ... + raise(Puppet::ParseError, "concat(): Wrong number of arguments " + + "given (#{arguments.size} for 2)") if arguments.size != 2 + + a = arguments[0] + b = arguments[1] + + # Check that the first parameter is an array + unless a.is_a?(Array) + raise(Puppet::ParseError, 'concat(): Requires array to work with') + end + + if b.is_a?(Array) + result = a.concat(b) + else + result = a << b + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/count.rb b/modules/stdlib/lib/puppet/parser/functions/count.rb new file mode 100644 index 0000000..52de1b8 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/count.rb @@ -0,0 +1,22 @@ +module Puppet::Parser::Functions + newfunction(:count, :type => :rvalue, :arity => -2, :doc => <<-EOS +Takes an array as first argument and an optional second argument. +Count the number of elements in array that matches second argument. +If called with only an array it counts the number of elements that are not nil/undef. + EOS + ) do |args| + + if (args.size > 2) then + raise(ArgumentError, "count(): Wrong number of arguments "+ + "given #{args.size} for 1 or 2.") + end + + collection, item = args + + if item then + collection.count item + else + collection.count { |obj| obj != nil && obj != :undef && obj != '' } + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/deep_merge.rb b/modules/stdlib/lib/puppet/parser/functions/deep_merge.rb new file mode 100644 index 0000000..6df32e9 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/deep_merge.rb @@ -0,0 +1,44 @@ +module Puppet::Parser::Functions + newfunction(:deep_merge, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + Recursively merges two or more hashes together and returns the resulting hash. + + For example: + + $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } + $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } } + $merged_hash = deep_merge($hash1, $hash2) + # The resulting hash is equivalent to: + # $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } } + + When there is a duplicate key that is a hash, they are recursively merged. + When there is a duplicate key that is not a hash, the key in the rightmost hash will "win." + + ENDHEREDOC + + if args.length < 2 + raise Puppet::ParseError, ("deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)") + end + + deep_merge = Proc.new do |hash1,hash2| + hash1.merge(hash2) do |key,old_value,new_value| + if old_value.is_a?(Hash) && new_value.is_a?(Hash) + deep_merge.call(old_value, new_value) + else + new_value + end + end + end + + result = Hash.new + args.each do |arg| + next if arg.is_a? String and arg.empty? # empty string is synonym for puppet's undef + # If the argument was not a hash, skip it. + unless arg.is_a?(Hash) + raise Puppet::ParseError, "deep_merge: unexpected argument type #{arg.class}, only expects hash arguments" + end + + result = deep_merge.call(result, arg) + end + return( result ) + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/defined_with_params.rb b/modules/stdlib/lib/puppet/parser/functions/defined_with_params.rb new file mode 100644 index 0000000..d7df306 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/defined_with_params.rb @@ -0,0 +1,35 @@ +# Test whether a given class or definition is defined +require 'puppet/parser/functions' + +Puppet::Parser::Functions.newfunction(:defined_with_params, + :type => :rvalue, + :doc => <<-'ENDOFDOC' +Takes a resource reference and an optional hash of attributes. + +Returns true if a resource with the specified attributes has already been added +to the catalog, and false otherwise. + + user { 'dan': + ensure => present, + } + + if ! defined_with_params(User[dan], {'ensure' => 'present' }) { + user { 'dan': ensure => present, } + } +ENDOFDOC +) do |vals| + reference, params = vals + raise(ArgumentError, 'Must specify a reference') unless reference + if (! params) || params == '' + params = {} + end + ret = false + if resource = findresource(reference.to_s) + matches = params.collect do |key, value| + resource[key] == value + end + ret = params.empty? || !matches.include?(false) + end + Puppet.debug("Resource #{reference} was not determined to be defined") + ret +end diff --git a/modules/stdlib/lib/puppet/parser/functions/delete.rb b/modules/stdlib/lib/puppet/parser/functions/delete.rb new file mode 100644 index 0000000..d03a293 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/delete.rb @@ -0,0 +1,46 @@ +# +# delete.rb +# + +# TODO(Krzysztof Wilczynski): We need to add support for regular expression ... + +module Puppet::Parser::Functions + newfunction(:delete, :type => :rvalue, :doc => <<-EOS +Deletes all instances of a given element from an array, substring from a +string, or key from a hash. + +*Examples:* + + delete(['a','b','c','b'], 'b') + Would return: ['a','c'] + + delete({'a'=>1,'b'=>2,'c'=>3}, 'b') + Would return: {'a'=>1,'c'=>3} + + delete('abracadabra', 'bra') + Would return: 'acada' + EOS + ) do |arguments| + + if (arguments.size != 2) then + raise(Puppet::ParseError, "delete(): Wrong number of arguments "+ + "given #{arguments.size} for 2.") + end + + collection = arguments[0].dup + item = arguments[1] + + case collection + when Array, Hash + collection.delete item + when String + collection.gsub! item, '' + else + raise(TypeError, "delete(): First argument must be an Array, " + + "String, or Hash. Given an argument of class #{collection.class}.") + end + collection + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/delete_at.rb b/modules/stdlib/lib/puppet/parser/functions/delete_at.rb new file mode 100644 index 0000000..3eb4b53 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/delete_at.rb @@ -0,0 +1,49 @@ +# +# delete_at.rb +# + +module Puppet::Parser::Functions + newfunction(:delete_at, :type => :rvalue, :doc => <<-EOS +Deletes a determined indexed value from an array. + +*Examples:* + + delete_at(['a','b','c'], 1) + +Would return: ['a','c'] + EOS + ) do |arguments| + + raise(Puppet::ParseError, "delete_at(): Wrong number of arguments " + + "given (#{arguments.size} for 2)") if arguments.size < 2 + + array = arguments[0] + + unless array.is_a?(Array) + raise(Puppet::ParseError, 'delete_at(): Requires array to work with') + end + + index = arguments[1] + + if index.is_a?(String) and not index.match(/^\d+$/) + raise(Puppet::ParseError, 'delete_at(): You must provide ' + + 'non-negative numeric index') + end + + result = array.clone + + # Numbers in Puppet are often string-encoded which is troublesome ... + index = index.to_i + + if index > result.size - 1 # First element is at index 0 is it not? + raise(Puppet::ParseError, 'delete_at(): Given index ' + + 'exceeds size of array given') + end + + result.delete_at(index) # We ignore the element that got deleted ... + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/delete_undef_values.rb b/modules/stdlib/lib/puppet/parser/functions/delete_undef_values.rb new file mode 100644 index 0000000..f94d4da --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/delete_undef_values.rb @@ -0,0 +1,34 @@ +module Puppet::Parser::Functions + newfunction(:delete_undef_values, :type => :rvalue, :doc => <<-EOS +Returns a copy of input hash or array with all undefs deleted. + +*Examples:* + + $hash = delete_undef_values({a=>'A', b=>'', c=>undef, d => false}) + +Would return: {a => 'A', b => '', d => false} + + $array = delete_undef_values(['A','',undef,false]) + +Would return: ['A','',false] + + EOS + ) do |args| + + raise(Puppet::ParseError, + "delete_undef_values(): Wrong number of arguments given " + + "(#{args.size})") if args.size < 1 + + unless args[0].is_a? Array or args[0].is_a? Hash + raise(Puppet::ParseError, + "delete_undef_values(): expected an array or hash, got #{args[0]} type #{args[0].class} ") + end + result = args[0].dup + if result.is_a?(Hash) + result.delete_if {|key, val| val.equal? :undef} + elsif result.is_a?(Array) + result.delete :undef + end + result + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/delete_values.rb b/modules/stdlib/lib/puppet/parser/functions/delete_values.rb new file mode 100644 index 0000000..f6c8c0e --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/delete_values.rb @@ -0,0 +1,26 @@ +module Puppet::Parser::Functions + newfunction(:delete_values, :type => :rvalue, :doc => <<-EOS +Deletes all instances of a given value from a hash. + +*Examples:* + + delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B') + +Would return: {'a'=>'A','c'=>'C','B'=>'D'} + + EOS + ) do |arguments| + + raise(Puppet::ParseError, + "delete_values(): Wrong number of arguments given " + + "(#{arguments.size} of 2)") if arguments.size != 2 + + hash, item = arguments + + if not hash.is_a?(Hash) + raise(TypeError, "delete_values(): First argument must be a Hash. " + \ + "Given an argument of class #{hash.class}.") + end + hash.dup.delete_if { |key, val| item == val } + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/difference.rb b/modules/stdlib/lib/puppet/parser/functions/difference.rb new file mode 100644 index 0000000..cd258f7 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/difference.rb @@ -0,0 +1,36 @@ +# +# difference.rb +# + +module Puppet::Parser::Functions + newfunction(:difference, :type => :rvalue, :doc => <<-EOS +This function returns the difference between two arrays. +The returned array is a copy of the original array, removing any items that +also appear in the second array. + +*Examples:* + + difference(["a","b","c"],["b","c","d"]) + +Would return: ["a"] + EOS + ) do |arguments| + + # Two arguments are required + raise(Puppet::ParseError, "difference(): Wrong number of arguments " + + "given (#{arguments.size} for 2)") if arguments.size != 2 + + first = arguments[0] + second = arguments[1] + + unless first.is_a?(Array) && second.is_a?(Array) + raise(Puppet::ParseError, 'difference(): Requires 2 arrays') + end + + result = first - second + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/dirname.rb b/modules/stdlib/lib/puppet/parser/functions/dirname.rb new file mode 100644 index 0000000..ea8cc1e --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/dirname.rb @@ -0,0 +1,15 @@ +module Puppet::Parser::Functions + newfunction(:dirname, :type => :rvalue, :doc => <<-EOS + Returns the dirname of a path. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "dirname(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + path = arguments[0] + return File.dirname(path) + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/downcase.rb b/modules/stdlib/lib/puppet/parser/functions/downcase.rb new file mode 100644 index 0000000..4066d21 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/downcase.rb @@ -0,0 +1,33 @@ +# +# downcase.rb +# + +module Puppet::Parser::Functions + newfunction(:downcase, :type => :rvalue, :doc => <<-EOS +Converts the case of a string or all strings in an array to lower case. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "downcase(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'downcase(): Requires either ' + + 'array or string to work with') + end + + if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + result = value.collect { |i| i.is_a?(String) ? i.downcase : i } + else + result = value.downcase + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/empty.rb b/modules/stdlib/lib/puppet/parser/functions/empty.rb new file mode 100644 index 0000000..80ebb86 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/empty.rb @@ -0,0 +1,28 @@ +# +# empty.rb +# + +module Puppet::Parser::Functions + newfunction(:empty, :type => :rvalue, :doc => <<-EOS +Returns true if the variable is empty. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "empty(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, Hash, String].include?(klass) + raise(Puppet::ParseError, 'empty(): Requires either ' + + 'array, hash or string to work with') + end + + result = value.empty? + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/ensure_packages.rb b/modules/stdlib/lib/puppet/parser/functions/ensure_packages.rb new file mode 100644 index 0000000..f1da4aa --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/ensure_packages.rb @@ -0,0 +1,35 @@ +# +# ensure_packages.rb +# + +module Puppet::Parser::Functions + newfunction(:ensure_packages, :type => :statement, :doc => <<-EOS +Takes a list of packages and only installs them if they don't already exist. +It optionally takes a hash as a second parameter that will be passed as the +third argument to the ensure_resource() function. + EOS + ) do |arguments| + + if arguments.size > 2 or arguments.size == 0 + raise(Puppet::ParseError, "ensure_packages(): Wrong number of arguments " + + "given (#{arguments.size} for 1 or 2)") + elsif arguments.size == 2 and !arguments[1].is_a?(Hash) + raise(Puppet::ParseError, 'ensure_packages(): Requires second argument to be a Hash') + end + + packages = Array(arguments[0]) + + if arguments[1] + defaults = { 'ensure' => 'present' }.merge(arguments[1]) + else + defaults = { 'ensure' => 'present' } + end + + Puppet::Parser::Functions.function(:ensure_resource) + packages.each { |package_name| + function_ensure_resource(['package', package_name, defaults ]) + } + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/ensure_resource.rb b/modules/stdlib/lib/puppet/parser/functions/ensure_resource.rb new file mode 100644 index 0000000..05e5593 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/ensure_resource.rb @@ -0,0 +1,45 @@ +# Test whether a given class or definition is defined +require 'puppet/parser/functions' + +Puppet::Parser::Functions.newfunction(:ensure_resource, + :type => :statement, + :doc => <<-'ENDOFDOC' +Takes a resource type, title, and a list of attributes that describe a +resource. + + user { 'dan': + ensure => present, + } + +This example only creates the resource if it does not already exist: + + ensure_resource('user', 'dan', {'ensure' => 'present' }) + +If the resource already exists but does not match the specified parameters, +this function will attempt to recreate the resource leading to a duplicate +resource definition error. + +An array of resources can also be passed in and each will be created with +the type and parameters specified if it doesn't already exist. + + ensure_resource('user', ['dan','alex'], {'ensure' => 'present'}) + +ENDOFDOC +) do |vals| + type, title, params = vals + raise(ArgumentError, 'Must specify a type') unless type + raise(ArgumentError, 'Must specify a title') unless title + params ||= {} + + items = [title].flatten + + items.each do |item| + Puppet::Parser::Functions.function(:defined_with_params) + if function_defined_with_params(["#{type}[#{item}]", params]) + Puppet.debug("Resource #{type}[#{item}] not created because it already exists") + else + Puppet::Parser::Functions.function(:create_resources) + function_create_resources([type.capitalize, { item => params }]) + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/flatten.rb b/modules/stdlib/lib/puppet/parser/functions/flatten.rb new file mode 100644 index 0000000..a1ed183 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/flatten.rb @@ -0,0 +1,33 @@ +# +# flatten.rb +# + +module Puppet::Parser::Functions + newfunction(:flatten, :type => :rvalue, :doc => <<-EOS +This function flattens any deeply nested arrays and returns a single flat array +as a result. + +*Examples:* + + flatten(['a', ['b', ['c']]]) + +Would return: ['a','b','c'] + EOS + ) do |arguments| + + raise(Puppet::ParseError, "flatten(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size != 1 + + array = arguments[0] + + unless array.is_a?(Array) + raise(Puppet::ParseError, 'flatten(): Requires array to work with') + end + + result = array.flatten + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/floor.rb b/modules/stdlib/lib/puppet/parser/functions/floor.rb new file mode 100644 index 0000000..9a6f014 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/floor.rb @@ -0,0 +1,25 @@ +module Puppet::Parser::Functions + newfunction(:floor, :type => :rvalue, :doc => <<-EOS + Returns the largest integer less or equal to the argument. + Takes a single numeric value as an argument. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "floor(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size != 1 + + begin + arg = Float(arguments[0]) + rescue TypeError, ArgumentError => e + raise(Puppet::ParseError, "floor(): Wrong argument type " + + "given (#{arguments[0]} for Numeric)") + end + + raise(Puppet::ParseError, "floor(): Wrong argument type " + + "given (#{arg.class} for Numeric)") if arg.is_a?(Numeric) == false + + arg.floor + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/fqdn_rotate.rb b/modules/stdlib/lib/puppet/parser/functions/fqdn_rotate.rb new file mode 100644 index 0000000..6558206 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/fqdn_rotate.rb @@ -0,0 +1,46 @@ +# +# fqdn_rotate.rb +# + +module Puppet::Parser::Functions + newfunction(:fqdn_rotate, :type => :rvalue, :doc => <<-EOS +Rotates an array a random number of times based on a nodes fqdn. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "fqdn_rotate(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + require 'digest/md5' + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'fqdn_rotate(): Requires either ' + + 'array or string to work with') + end + + result = value.clone + + string = value.is_a?(String) ? true : false + + # Check whether it makes sense to rotate ... + return result if result.size <= 1 + + # We turn any string value into an array to be able to rotate ... + result = string ? result.split('') : result + + elements = result.size + + srand(Digest::MD5.hexdigest([lookupvar('::fqdn'),arguments].join(':')).hex) + rand(elements).times { + result.push result.shift + } + + result = string ? result.join : result + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/get_module_path.rb b/modules/stdlib/lib/puppet/parser/functions/get_module_path.rb new file mode 100644 index 0000000..1421b91 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/get_module_path.rb @@ -0,0 +1,17 @@ +module Puppet::Parser::Functions + newfunction(:get_module_path, :type =>:rvalue, :doc => <<-EOT + Returns the absolute path of the specified module for the current + environment. + + Example: + $module_path = get_module_path('stdlib') + EOT + ) do |args| + raise(Puppet::ParseError, "get_module_path(): Wrong number of arguments, expects one") unless args.size == 1 + if module_path = Puppet::Module.find(args[0], compiler.environment.to_s) + module_path.path + else + raise(Puppet::ParseError, "Could not find module #{args[0]} in environment #{compiler.environment}") + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/getparam.rb b/modules/stdlib/lib/puppet/parser/functions/getparam.rb new file mode 100644 index 0000000..6d51006 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/getparam.rb @@ -0,0 +1,35 @@ +# Test whether a given class or definition is defined +require 'puppet/parser/functions' + +Puppet::Parser::Functions.newfunction(:getparam, + :type => :rvalue, + :doc => <<-'ENDOFDOC' +Takes a resource reference and name of the parameter and +returns value of resource's parameter. + +*Examples:* + + define example_resource($param) { + } + + example_resource { "example_resource_instance": + param => "param_value" + } + + getparam(Example_resource["example_resource_instance"], "param") + +Would return: param_value +ENDOFDOC +) do |vals| + reference, param = vals + raise(ArgumentError, 'Must specify a reference') unless reference + raise(ArgumentError, 'Must specify name of a parameter') unless param and param.instance_of? String + + return '' if param.empty? + + if resource = findresource(reference.to_s) + return resource[param] if resource[param] + end + + return '' +end diff --git a/modules/stdlib/lib/puppet/parser/functions/getvar.rb b/modules/stdlib/lib/puppet/parser/functions/getvar.rb new file mode 100644 index 0000000..1621149 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/getvar.rb @@ -0,0 +1,26 @@ +module Puppet::Parser::Functions + + newfunction(:getvar, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + Lookup a variable in a remote namespace. + + For example: + + $foo = getvar('site::data::foo') + # Equivalent to $foo = $site::data::foo + + This is useful if the namespace itself is stored in a string: + + $datalocation = 'site::data' + $bar = getvar("${datalocation}::bar") + # Equivalent to $bar = $site::data::bar + ENDHEREDOC + + unless args.length == 1 + raise Puppet::ParseError, ("getvar(): wrong number of arguments (#{args.length}; must be 1)") + end + + self.lookupvar("#{args[0]}") + + end + +end diff --git a/modules/stdlib/lib/puppet/parser/functions/grep.rb b/modules/stdlib/lib/puppet/parser/functions/grep.rb new file mode 100644 index 0000000..ceba9ec --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/grep.rb @@ -0,0 +1,33 @@ +# +# grep.rb +# + +module Puppet::Parser::Functions + newfunction(:grep, :type => :rvalue, :doc => <<-EOS +This function searches through an array and returns any elements that match +the provided regular expression. + +*Examples:* + + grep(['aaa','bbb','ccc','aaaddd'], 'aaa') + +Would return: + + ['aaa','aaaddd'] + EOS + ) do |arguments| + + if (arguments.size != 2) then + raise(Puppet::ParseError, "grep(): Wrong number of arguments "+ + "given #{arguments.size} for 2") + end + + a = arguments[0] + pattern = Regexp.new(arguments[1]) + + a.grep(pattern) + + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/has_interface_with.rb b/modules/stdlib/lib/puppet/parser/functions/has_interface_with.rb new file mode 100644 index 0000000..7f150a7 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/has_interface_with.rb @@ -0,0 +1,52 @@ +# +# has_interface_with +# + +module Puppet::Parser::Functions + newfunction(:has_interface_with, :type => :rvalue, :doc => <<-EOS +Returns boolean based on kind and value: + * macaddress + * netmask + * ipaddress + * network + +has_interface_with("macaddress", "x:x:x:x:x:x") +has_interface_with("ipaddress", "127.0.0.1") => true +etc. + +If no "kind" is given, then the presence of the interface is checked: +has_interface_with("lo") => true + EOS + ) do |args| + + raise(Puppet::ParseError, "has_interface_with(): Wrong number of arguments " + + "given (#{args.size} for 1 or 2)") if args.size < 1 or args.size > 2 + + interfaces = lookupvar('interfaces') + + # If we do not have any interfaces, then there are no requested attributes + return false if (interfaces == :undefined) + + interfaces = interfaces.split(',') + + if args.size == 1 + return interfaces.member?(args[0]) + end + + kind, value = args + + if lookupvar(kind) == value + return true + end + + result = false + interfaces.each do |iface| + if value == lookupvar("#{kind}_#{iface}") + result = true + break + end + end + + result + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/has_ip_address.rb b/modules/stdlib/lib/puppet/parser/functions/has_ip_address.rb new file mode 100644 index 0000000..842c8ec --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/has_ip_address.rb @@ -0,0 +1,25 @@ +# +# has_ip_address +# + +module Puppet::Parser::Functions + newfunction(:has_ip_address, :type => :rvalue, :doc => <<-EOS +Returns true if the client has the requested IP address on some interface. + +This function iterates through the 'interfaces' fact and checks the +'ipaddress_IFACE' facts, performing a simple string comparison. + EOS + ) do |args| + + raise(Puppet::ParseError, "has_ip_address(): Wrong number of arguments " + + "given (#{args.size} for 1)") if args.size != 1 + + Puppet::Parser::Functions.autoloader.load(:has_interface_with) \ + unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) + + function_has_interface_with(['ipaddress', args[0]]) + + end +end + +# vim:sts=2 sw=2 diff --git a/modules/stdlib/lib/puppet/parser/functions/has_ip_network.rb b/modules/stdlib/lib/puppet/parser/functions/has_ip_network.rb new file mode 100644 index 0000000..9ccf902 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/has_ip_network.rb @@ -0,0 +1,25 @@ +# +# has_ip_network +# + +module Puppet::Parser::Functions + newfunction(:has_ip_network, :type => :rvalue, :doc => <<-EOS +Returns true if the client has an IP address within the requested network. + +This function iterates through the 'interfaces' fact and checks the +'network_IFACE' facts, performing a simple string comparision. + EOS + ) do |args| + + raise(Puppet::ParseError, "has_ip_network(): Wrong number of arguments " + + "given (#{args.size} for 1)") if args.size != 1 + + Puppet::Parser::Functions.autoloader.load(:has_interface_with) \ + unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) + + function_has_interface_with(['network', args[0]]) + + end +end + +# vim:sts=2 sw=2 diff --git a/modules/stdlib/lib/puppet/parser/functions/has_key.rb b/modules/stdlib/lib/puppet/parser/functions/has_key.rb new file mode 100644 index 0000000..4657cc2 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/has_key.rb @@ -0,0 +1,28 @@ +module Puppet::Parser::Functions + + newfunction(:has_key, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + Determine if a hash has a certain key value. + + Example: + + $my_hash = {'key_one' => 'value_one'} + if has_key($my_hash, 'key_two') { + notice('we will not reach here') + } + if has_key($my_hash, 'key_one') { + notice('this will be printed') + } + + ENDHEREDOC + + unless args.length == 2 + raise Puppet::ParseError, ("has_key(): wrong number of arguments (#{args.length}; must be 2)") + end + unless args[0].is_a?(Hash) + raise Puppet::ParseError, "has_key(): expects the first argument to be a hash, got #{args[0].inspect} which is of type #{args[0].class}" + end + args[0].has_key?(args[1]) + + end + +end diff --git a/modules/stdlib/lib/puppet/parser/functions/hash.rb b/modules/stdlib/lib/puppet/parser/functions/hash.rb new file mode 100644 index 0000000..8cc4823 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/hash.rb @@ -0,0 +1,41 @@ +# +# hash.rb +# + +module Puppet::Parser::Functions + newfunction(:hash, :type => :rvalue, :doc => <<-EOS +This function converts an array into a hash. + +*Examples:* + + hash(['a',1,'b',2,'c',3]) + +Would return: {'a'=>1,'b'=>2,'c'=>3} + EOS + ) do |arguments| + + raise(Puppet::ParseError, "hash(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + array = arguments[0] + + unless array.is_a?(Array) + raise(Puppet::ParseError, 'hash(): Requires array to work with') + end + + result = {} + + begin + # This is to make it compatible with older version of Ruby ... + array = array.flatten + result = Hash[*array] + rescue Exception + raise(Puppet::ParseError, 'hash(): Unable to compute ' + + 'hash from array given') + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/intersection.rb b/modules/stdlib/lib/puppet/parser/functions/intersection.rb new file mode 100644 index 0000000..48f02e9 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/intersection.rb @@ -0,0 +1,34 @@ +# +# intersection.rb +# + +module Puppet::Parser::Functions + newfunction(:intersection, :type => :rvalue, :doc => <<-EOS +This function returns an array an intersection of two. + +*Examples:* + + intersection(["a","b","c"],["b","c","d"]) + +Would return: ["b","c"] + EOS + ) do |arguments| + + # Two arguments are required + raise(Puppet::ParseError, "intersection(): Wrong number of arguments " + + "given (#{arguments.size} for 2)") if arguments.size != 2 + + first = arguments[0] + second = arguments[1] + + unless first.is_a?(Array) && second.is_a?(Array) + raise(Puppet::ParseError, 'intersection(): Requires 2 arrays') + end + + result = first & second + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/is_array.rb b/modules/stdlib/lib/puppet/parser/functions/is_array.rb new file mode 100644 index 0000000..b39e184 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/is_array.rb @@ -0,0 +1,22 @@ +# +# is_array.rb +# + +module Puppet::Parser::Functions + newfunction(:is_array, :type => :rvalue, :doc => <<-EOS +Returns true if the variable passed to this function is an array. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "is_array(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + type = arguments[0] + + result = type.is_a?(Array) + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/is_bool.rb b/modules/stdlib/lib/puppet/parser/functions/is_bool.rb new file mode 100644 index 0000000..8bbdbc8 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/is_bool.rb @@ -0,0 +1,22 @@ +# +# is_bool.rb +# + +module Puppet::Parser::Functions + newfunction(:is_bool, :type => :rvalue, :doc => <<-EOS +Returns true if the variable passed to this function is a boolean. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "is_bool(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size != 1 + + type = arguments[0] + + result = type.is_a?(TrueClass) || type.is_a?(FalseClass) + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/is_domain_name.rb b/modules/stdlib/lib/puppet/parser/functions/is_domain_name.rb new file mode 100644 index 0000000..b3fee96 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/is_domain_name.rb @@ -0,0 +1,50 @@ +# +# is_domain_name.rb +# + +module Puppet::Parser::Functions + newfunction(:is_domain_name, :type => :rvalue, :doc => <<-EOS +Returns true if the string passed to this function is a syntactically correct domain name. + EOS + ) do |arguments| + + if (arguments.size != 1) then + raise(Puppet::ParseError, "is_domain_name(): Wrong number of arguments "+ + "given #{arguments.size} for 1") + end + + domain = arguments[0] + + # Limits (rfc1035, 3.1) + domain_max_length=255 + label_min_length=1 + label_max_length=63 + + # Only allow string types + return false unless domain.is_a?(String) + + # Allow ".", it is the top level domain + return true if domain == '.' + + # Remove the final dot, if present. + domain.chomp!('.') + + # Check the whole domain + return false if domain.empty? + return false if domain.length > domain_max_length + + # Check each label in the domain + labels = domain.split('.') + vlabels = labels.each do |label| + break if label.length < label_min_length + break if label.length > label_max_length + break if label[-1..-1] == '-' + break if label[0..0] == '-' + break unless /^[a-z\d-]+$/i.match(label) + end + return vlabels == labels + + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/is_float.rb b/modules/stdlib/lib/puppet/parser/functions/is_float.rb new file mode 100644 index 0000000..a2da943 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/is_float.rb @@ -0,0 +1,30 @@ +# +# is_float.rb +# + +module Puppet::Parser::Functions + newfunction(:is_float, :type => :rvalue, :doc => <<-EOS +Returns true if the variable passed to this function is a float. + EOS + ) do |arguments| + + if (arguments.size != 1) then + raise(Puppet::ParseError, "is_float(): Wrong number of arguments "+ + "given #{arguments.size} for 1") + end + + value = arguments[0] + + # Only allow Numeric or String types + return false unless value.is_a?(Numeric) or value.is_a?(String) + + if value != value.to_f.to_s and !value.is_a? Float then + return false + else + return true + end + + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/is_function_available.rb b/modules/stdlib/lib/puppet/parser/functions/is_function_available.rb new file mode 100644 index 0000000..6da82c8 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/is_function_available.rb @@ -0,0 +1,26 @@ +# +# is_function_available.rb +# + +module Puppet::Parser::Functions + newfunction(:is_function_available, :type => :rvalue, :doc => <<-EOS +This function accepts a string as an argument, determines whether the +Puppet runtime has access to a function by that name. It returns a +true if the function exists, false if not. + EOS + ) do |arguments| + + if (arguments.size != 1) then + raise(Puppet::ParseError, "is_function_available?(): Wrong number of arguments "+ + "given #{arguments.size} for 1") + end + + # Only allow String types + return false unless arguments[0].is_a?(String) + + function = Puppet::Parser::Functions.function(arguments[0].to_sym) + function.is_a?(String) and not function.empty? + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/is_hash.rb b/modules/stdlib/lib/puppet/parser/functions/is_hash.rb new file mode 100644 index 0000000..ad907f0 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/is_hash.rb @@ -0,0 +1,22 @@ +# +# is_hash.rb +# + +module Puppet::Parser::Functions + newfunction(:is_hash, :type => :rvalue, :doc => <<-EOS +Returns true if the variable passed to this function is a hash. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "is_hash(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size != 1 + + type = arguments[0] + + result = type.is_a?(Hash) + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/is_integer.rb b/modules/stdlib/lib/puppet/parser/functions/is_integer.rb new file mode 100644 index 0000000..c03d28d --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/is_integer.rb @@ -0,0 +1,45 @@ +# +# is_integer.rb +# + +module Puppet::Parser::Functions + newfunction(:is_integer, :type => :rvalue, :doc => <<-EOS +Returns true if the variable passed to this function is an Integer or +a decimal (base 10) integer in String form. The string may +start with a '-' (minus). A value of '0' is allowed, but a leading '0' digit may not +be followed by other digits as this indicates that the value is octal (base 8). + +If given any other argument `false` is returned. + EOS + ) do |arguments| + + if (arguments.size != 1) then + raise(Puppet::ParseError, "is_integer(): Wrong number of arguments "+ + "given #{arguments.size} for 1") + end + + value = arguments[0] + + # Regex is taken from the lexer of puppet + # puppet/pops/parser/lexer.rb but modified to match also + # negative values and disallow numbers prefixed with multiple + # 0's + # + # TODO these parameter should be a constant but I'm not sure + # if there is no risk to declare it inside of the module + # Puppet::Parser::Functions + + # Integer numbers like + # -1234568981273 + # 47291 + numeric = %r{^-?(?:(?:[1-9]\d*)|0)$} + + if value.is_a? Integer or (value.is_a? String and value.match numeric) + return true + else + return false + end + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/is_ip_address.rb b/modules/stdlib/lib/puppet/parser/functions/is_ip_address.rb new file mode 100644 index 0000000..a90adab --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/is_ip_address.rb @@ -0,0 +1,32 @@ +# +# is_ip_address.rb +# + +module Puppet::Parser::Functions + newfunction(:is_ip_address, :type => :rvalue, :doc => <<-EOS +Returns true if the string passed to this function is a valid IP address. + EOS + ) do |arguments| + + require 'ipaddr' + + if (arguments.size != 1) then + raise(Puppet::ParseError, "is_ip_address(): Wrong number of arguments "+ + "given #{arguments.size} for 1") + end + + begin + ip = IPAddr.new(arguments[0]) + rescue ArgumentError + return false + end + + if ip.ipv4? or ip.ipv6? then + return true + else + return false + end + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/is_mac_address.rb b/modules/stdlib/lib/puppet/parser/functions/is_mac_address.rb new file mode 100644 index 0000000..1b3088a --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/is_mac_address.rb @@ -0,0 +1,27 @@ +# +# is_mac_address.rb +# + +module Puppet::Parser::Functions + newfunction(:is_mac_address, :type => :rvalue, :doc => <<-EOS +Returns true if the string passed to this function is a valid mac address. + EOS + ) do |arguments| + + if (arguments.size != 1) then + raise(Puppet::ParseError, "is_mac_address(): Wrong number of arguments "+ + "given #{arguments.size} for 1") + end + + mac = arguments[0] + + if /^[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}:[a-fA-F0-9]{1,2}$/.match(mac) then + return true + else + return false + end + + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/is_numeric.rb b/modules/stdlib/lib/puppet/parser/functions/is_numeric.rb new file mode 100644 index 0000000..e7e1d2a --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/is_numeric.rb @@ -0,0 +1,75 @@ +# +# is_numeric.rb +# + +module Puppet::Parser::Functions + newfunction(:is_numeric, :type => :rvalue, :doc => <<-EOS +Returns true if the given argument is a Numeric (Integer or Float), +or a String containing either a valid integer in decimal base 10 form, or +a valid floating point string representation. + +The function recognizes only decimal (base 10) integers and float but not +integers in hex (base 16) or octal (base 8) form. + +The string representation may start with a '-' (minus). If a decimal '.' is used, +it must be followed by at least one digit. + +Valid examples: + + 77435 + 10e-12 + -8475 + 0.2343 + -23.561e3 + EOS + ) do |arguments| + + if (arguments.size != 1) then + raise(Puppet::ParseError, "is_numeric(): Wrong number of arguments "+ + "given #{arguments.size} for 1") + end + + value = arguments[0] + + # Regex is taken from the lexer of puppet + # puppet/pops/parser/lexer.rb but modified to match also + # negative values and disallow invalid octal numbers or + # numbers prefixed with multiple 0's (except in hex numbers) + # + # TODO these parameters should be constants but I'm not sure + # if there is no risk to declare them inside of the module + # Puppet::Parser::Functions + + # TODO decide if this should be used + # HEX numbers like + # 0xaa230F + # 0X1234009C + # 0x0012 + # -12FcD + #numeric_hex = %r{^-?0[xX][0-9A-Fa-f]+$} + + # TODO decide if this should be used + # OCTAL numbers like + # 01234567 + # -045372 + #numeric_oct = %r{^-?0[1-7][0-7]*$} + + # Integer/Float numbers like + # -0.1234568981273 + # 47291 + # 42.12345e-12 + numeric = %r{^-?(?:(?:[1-9]\d*)|0)(?:\.\d+)?(?:[eE]-?\d+)?$} + + if value.is_a? Numeric or (value.is_a? String and ( + value.match(numeric) #or + # value.match(numeric_hex) or + # value.match(numeric_oct) + )) + return true + else + return false + end + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/is_string.rb b/modules/stdlib/lib/puppet/parser/functions/is_string.rb new file mode 100644 index 0000000..f5bef04 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/is_string.rb @@ -0,0 +1,26 @@ +# +# is_string.rb +# + +module Puppet::Parser::Functions + newfunction(:is_string, :type => :rvalue, :doc => <<-EOS +Returns true if the variable passed to this function is a string. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "is_string(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + type = arguments[0] + + result = type.is_a?(String) + + if result and (type == type.to_f.to_s or type == type.to_i.to_s) then + return false + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/join.rb b/modules/stdlib/lib/puppet/parser/functions/join.rb new file mode 100644 index 0000000..6c0a6ba --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/join.rb @@ -0,0 +1,41 @@ +# +# join.rb +# + +module Puppet::Parser::Functions + newfunction(:join, :type => :rvalue, :doc => <<-EOS +This function joins an array into a string using a separator. + +*Examples:* + + join(['a','b','c'], ",") + +Would result in: "a,b,c" + EOS + ) do |arguments| + + # Technically we support two arguments but only first is mandatory ... + raise(Puppet::ParseError, "join(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + array = arguments[0] + + unless array.is_a?(Array) + raise(Puppet::ParseError, 'join(): Requires array to work with') + end + + suffix = arguments[1] if arguments[1] + + if suffix + unless suffix.is_a?(String) + raise(Puppet::ParseError, 'join(): Requires string to work with') + end + end + + result = suffix ? array.join(suffix) : array.join + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/join_keys_to_values.rb b/modules/stdlib/lib/puppet/parser/functions/join_keys_to_values.rb new file mode 100644 index 0000000..e9924fe --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/join_keys_to_values.rb @@ -0,0 +1,47 @@ +# +# join.rb +# + +module Puppet::Parser::Functions + newfunction(:join_keys_to_values, :type => :rvalue, :doc => <<-EOS +This function joins each key of a hash to that key's corresponding value with a +separator. Keys and values are cast to strings. The return value is an array in +which each element is one joined key/value pair. + +*Examples:* + + join_keys_to_values({'a'=>1,'b'=>2}, " is ") + +Would result in: ["a is 1","b is 2"] + EOS + ) do |arguments| + + # Validate the number of arguments. + if arguments.size != 2 + raise(Puppet::ParseError, "join_keys_to_values(): Takes exactly two " + + "arguments, but #{arguments.size} given.") + end + + # Validate the first argument. + hash = arguments[0] + if not hash.is_a?(Hash) + raise(TypeError, "join_keys_to_values(): The first argument must be a " + + "hash, but a #{hash.class} was given.") + end + + # Validate the second argument. + separator = arguments[1] + if not separator.is_a?(String) + raise(TypeError, "join_keys_to_values(): The second argument must be a " + + "string, but a #{separator.class} was given.") + end + + # Join the keys to their values. + hash.map do |k,v| + String(k) + separator + String(v) + end + + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/keys.rb b/modules/stdlib/lib/puppet/parser/functions/keys.rb new file mode 100644 index 0000000..f0d13b6 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/keys.rb @@ -0,0 +1,26 @@ +# +# keys.rb +# + +module Puppet::Parser::Functions + newfunction(:keys, :type => :rvalue, :doc => <<-EOS +Returns the keys of a hash as an array. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "keys(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + hash = arguments[0] + + unless hash.is_a?(Hash) + raise(Puppet::ParseError, 'keys(): Requires hash to work with') + end + + result = hash.keys + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/loadyaml.rb b/modules/stdlib/lib/puppet/parser/functions/loadyaml.rb new file mode 100644 index 0000000..10c4005 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/loadyaml.rb @@ -0,0 +1,20 @@ +module Puppet::Parser::Functions + + newfunction(:loadyaml, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + Load a YAML file containing an array, string, or hash, and return the data + in the corresponding native data type. + + For example: + + $myhash = loadyaml('/etc/puppet/data/myhash.yaml') + ENDHEREDOC + + unless args.length == 1 + raise Puppet::ParseError, ("loadyaml(): wrong number of arguments (#{args.length}; must be 1)") + end + + YAML.load_file(args[0]) + + end + +end diff --git a/modules/stdlib/lib/puppet/parser/functions/lstrip.rb b/modules/stdlib/lib/puppet/parser/functions/lstrip.rb new file mode 100644 index 0000000..3a64de3 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/lstrip.rb @@ -0,0 +1,33 @@ +# +# lstrip.rb +# + +module Puppet::Parser::Functions + newfunction(:lstrip, :type => :rvalue, :doc => <<-EOS +Strips leading spaces to the left of a string. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "lstrip(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'lstrip(): Requires either ' + + 'array or string to work with') + end + + if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + result = value.collect { |i| i.is_a?(String) ? i.lstrip : i } + else + result = value.lstrip + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/max.rb b/modules/stdlib/lib/puppet/parser/functions/max.rb new file mode 100644 index 0000000..60fb94a --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/max.rb @@ -0,0 +1,21 @@ +module Puppet::Parser::Functions + newfunction(:max, :type => :rvalue, :doc => <<-EOS + Returns the highest value of all arguments. + Requires at least one argument. + EOS + ) do |args| + + raise(Puppet::ParseError, "max(): Wrong number of arguments " + + "need at least one") if args.size == 0 + + # Sometimes we get numbers as numerics and sometimes as strings. + # We try to compare them as numbers when possible + return args.max do |a,b| + if a.to_s =~ /\A-?\d+(.\d+)?\z/ and b.to_s =~ /\A-?\d+(.\d+)?\z/ then + a.to_f <=> b.to_f + else + a.to_s <=> b.to_s + end + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/member.rb b/modules/stdlib/lib/puppet/parser/functions/member.rb new file mode 100644 index 0000000..43d76af --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/member.rb @@ -0,0 +1,44 @@ +# +# member.rb +# + +# TODO(Krzysztof Wilczynski): We need to add support for regular expression ... +# TODO(Krzysztof Wilczynski): Support for strings and hashes too ... + +module Puppet::Parser::Functions + newfunction(:member, :type => :rvalue, :doc => <<-EOS +This function determines if a variable is a member of an array. + +*Examples:* + + member(['a','b'], 'b') + +Would return: true + + member(['a','b'], 'c') + +Would return: false + EOS + ) do |arguments| + + raise(Puppet::ParseError, "member(): Wrong number of arguments " + + "given (#{arguments.size} for 2)") if arguments.size < 2 + + array = arguments[0] + + unless array.is_a?(Array) + raise(Puppet::ParseError, 'member(): Requires array to work with') + end + + item = arguments[1] + + raise(Puppet::ParseError, 'member(): You must provide item ' + + 'to search for within array given') if item.empty? + + result = array.include?(item) + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/merge.rb b/modules/stdlib/lib/puppet/parser/functions/merge.rb new file mode 100644 index 0000000..1b39f20 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/merge.rb @@ -0,0 +1,34 @@ +module Puppet::Parser::Functions + newfunction(:merge, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + Merges two or more hashes together and returns the resulting hash. + + For example: + + $hash1 = {'one' => 1, 'two', => 2} + $hash2 = {'two' => 'dos', 'three', => 'tres'} + $merged_hash = merge($hash1, $hash2) + # The resulting hash is equivalent to: + # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'} + + When there is a duplicate key, the key in the rightmost hash will "win." + + ENDHEREDOC + + if args.length < 2 + raise Puppet::ParseError, ("merge(): wrong number of arguments (#{args.length}; must be at least 2)") + end + + # The hash we accumulate into + accumulator = Hash.new + # Merge into the accumulator hash + args.each do |arg| + next if arg.is_a? String and arg.empty? # empty string is synonym for puppet's undef + unless arg.is_a?(Hash) + raise Puppet::ParseError, "merge: unexpected argument type #{arg.class}, only expects hash arguments" + end + accumulator.merge!(arg) + end + # Return the fully merged hash + accumulator + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/min.rb b/modules/stdlib/lib/puppet/parser/functions/min.rb new file mode 100644 index 0000000..6bd6ebf --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/min.rb @@ -0,0 +1,21 @@ +module Puppet::Parser::Functions + newfunction(:min, :type => :rvalue, :doc => <<-EOS + Returns the lowest value of all arguments. + Requires at least one argument. + EOS + ) do |args| + + raise(Puppet::ParseError, "min(): Wrong number of arguments " + + "need at least one") if args.size == 0 + + # Sometimes we get numbers as numerics and sometimes as strings. + # We try to compare them as numbers when possible + return args.min do |a,b| + if a.to_s =~ /\A^-?\d+(.\d+)?\z/ and b.to_s =~ /\A-?\d+(.\d+)?\z/ then + a.to_f <=> b.to_f + else + a.to_s <=> b.to_s + end + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/num2bool.rb b/modules/stdlib/lib/puppet/parser/functions/num2bool.rb new file mode 100644 index 0000000..af0e6ed --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/num2bool.rb @@ -0,0 +1,43 @@ +# +# num2bool.rb +# + +module Puppet::Parser::Functions + newfunction(:num2bool, :type => :rvalue, :doc => <<-EOS +This function converts a number or a string representation of a number into a +true boolean. Zero or anything non-numeric becomes false. Numbers higher then 0 +become true. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "num2bool(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size != 1 + + number = arguments[0] + + case number + when Numeric + # Yay, it's a number + when String + begin + number = Float(number) + rescue ArgumentError => ex + raise(Puppet::ParseError, "num2bool(): '#{number}' does not look like a number: #{ex.message}") + end + else + begin + number = number.to_s + rescue NoMethodError => ex + raise(Puppet::ParseError, "num2bool(): Unable to parse argument: #{ex.message}") + end + end + + # Truncate Floats + number = number.to_i + + # Return true for any positive number and false otherwise + return number > 0 + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/parsejson.rb b/modules/stdlib/lib/puppet/parser/functions/parsejson.rb new file mode 100644 index 0000000..a9a16a4 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/parsejson.rb @@ -0,0 +1,24 @@ +# +# parsejson.rb +# + +module Puppet::Parser::Functions + newfunction(:parsejson, :type => :rvalue, :doc => <<-EOS +This function accepts JSON as a string and converts into the correct Puppet +structure. + EOS + ) do |arguments| + + if (arguments.size != 1) then + raise(Puppet::ParseError, "parsejson(): Wrong number of arguments "+ + "given #{arguments.size} for 1") + end + + json = arguments[0] + + # PSON is natively available in puppet + PSON.load(json) + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/parseyaml.rb b/modules/stdlib/lib/puppet/parser/functions/parseyaml.rb new file mode 100644 index 0000000..53d54fa --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/parseyaml.rb @@ -0,0 +1,24 @@ +# +# parseyaml.rb +# + +module Puppet::Parser::Functions + newfunction(:parseyaml, :type => :rvalue, :doc => <<-EOS +This function accepts YAML as a string and converts it into the correct +Puppet structure. + EOS + ) do |arguments| + + if (arguments.size != 1) then + raise(Puppet::ParseError, "parseyaml(): Wrong number of arguments "+ + "given #{arguments.size} for 1") + end + + require 'yaml' + + YAML::load(arguments[0]) + + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/pick.rb b/modules/stdlib/lib/puppet/parser/functions/pick.rb new file mode 100644 index 0000000..fdd0aef --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/pick.rb @@ -0,0 +1,29 @@ +module Puppet::Parser::Functions + newfunction(:pick, :type => :rvalue, :doc => <<-EOS + +This function is similar to a coalesce function in SQL in that it will return +the first value in a list of values that is not undefined or an empty string +(two things in Puppet that will return a boolean false value). Typically, +this function is used to check for a value in the Puppet Dashboard/Enterprise +Console, and failover to a default value like the following: + + $real_jenkins_version = pick($::jenkins_version, '1.449') + +The value of $real_jenkins_version will first look for a top-scope variable +called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ +Enterprise Console are brought into Puppet as top-scope variables), and, +failing that, will use a default value of 1.449. + +EOS +) do |args| + args = args.compact + args.delete(:undef) + args.delete(:undefined) + args.delete("") + if args[0].to_s.empty? then + fail Puppet::ParseError, "pick(): must receive at least one non empty value" + else + return args[0] + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/pick_default.rb b/modules/stdlib/lib/puppet/parser/functions/pick_default.rb new file mode 100644 index 0000000..36e33ab --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/pick_default.rb @@ -0,0 +1,35 @@ +module Puppet::Parser::Functions + newfunction(:pick_default, :type => :rvalue, :doc => <<-EOS + +This function is similar to a coalesce function in SQL in that it will return +the first value in a list of values that is not undefined or an empty string +(two things in Puppet that will return a boolean false value). If no value is +found, it will return the last argument. + +Typically, this function is used to check for a value in the Puppet +Dashboard/Enterprise Console, and failover to a default value like the +following: + + $real_jenkins_version = pick_default($::jenkins_version, '1.449') + +The value of $real_jenkins_version will first look for a top-scope variable +called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ +Enterprise Console are brought into Puppet as top-scope variables), and, +failing that, will use a default value of 1.449. + +Note that, contrary to the pick() function, the pick_default does not fail if +all arguments are empty. This allows pick_default to use an empty value as +default. + +EOS +) do |args| + fail "Must receive at least one argument." if args.empty? + default = args.last + args = args[0..-2].compact + args.delete(:undef) + args.delete(:undefined) + args.delete("") + args << default + return args[0] + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/prefix.rb b/modules/stdlib/lib/puppet/parser/functions/prefix.rb new file mode 100644 index 0000000..d02286a --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/prefix.rb @@ -0,0 +1,45 @@ +# +# prefix.rb +# + +module Puppet::Parser::Functions + newfunction(:prefix, :type => :rvalue, :doc => <<-EOS +This function applies a prefix to all elements in an array. + +*Examples:* + + prefix(['a','b','c'], 'p') + +Will return: ['pa','pb','pc'] + EOS + ) do |arguments| + + # Technically we support two arguments but only first is mandatory ... + raise(Puppet::ParseError, "prefix(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + array = arguments[0] + + unless array.is_a?(Array) + raise Puppet::ParseError, "prefix(): expected first argument to be an Array, got #{array.inspect}" + end + + prefix = arguments[1] if arguments[1] + + if prefix + unless prefix.is_a?(String) + raise Puppet::ParseError, "prefix(): expected second argument to be a String, got #{prefix.inspect}" + end + end + + # Turn everything into string same as join would do ... + result = array.collect do |i| + i = i.to_s + prefix ? prefix + i : i + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/range.rb b/modules/stdlib/lib/puppet/parser/functions/range.rb new file mode 100644 index 0000000..ffbdf84 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/range.rb @@ -0,0 +1,88 @@ +# +# range.rb +# + +# TODO(Krzysztof Wilczynski): We probably need to approach numeric values differently ... + +module Puppet::Parser::Functions + newfunction(:range, :type => :rvalue, :doc => <<-EOS +When given range in the form of (start, stop) it will extrapolate a range as +an array. + +*Examples:* + + range("0", "9") + +Will return: [0,1,2,3,4,5,6,7,8,9] + + range("00", "09") + +Will return: [0,1,2,3,4,5,6,7,8,9] (Zero padded strings are converted to +integers automatically) + + range("a", "c") + +Will return: ["a","b","c"] + + range("host01", "host10") + +Will return: ["host01", "host02", ..., "host09", "host10"] + +Passing a third argument will cause the generated range to step by that +interval, e.g. + + range("0", "9", "2") + +Will return: [0,2,4,6,8] + EOS + ) do |arguments| + + # We support more than one argument but at least one is mandatory ... + raise(Puppet::ParseError, "range(): Wrong number of " + + "arguments given (#{arguments.size} for 1)") if arguments.size < 1 + + if arguments.size > 1 + start = arguments[0] + stop = arguments[1] + step = arguments[2].nil? ? 1 : arguments[2].to_i.abs + + type = '..' # We select simplest type for Range available in Ruby ... + + elsif arguments.size > 0 + value = arguments[0] + + if m = value.match(/^(\w+)(\.\.\.?|\-)(\w+)$/) + start = m[1] + stop = m[3] + + type = m[2] + + elsif value.match(/^.+$/) + raise(Puppet::ParseError, 'range(): Unable to compute range ' + + 'from the value given') + else + raise(Puppet::ParseError, 'range(): Unknown format of range given') + end + end + + # Check whether we have integer value if so then make it so ... + if start.match(/^\d+$/) + start = start.to_i + stop = stop.to_i + else + start = start.to_s + stop = stop.to_s + end + + range = case type + when /^(\.\.|\-)$/ then (start .. stop) + when /^(\.\.\.)$/ then (start ... stop) # Exclusive of last element ... + end + + result = range.step(step).collect { |i| i } # Get them all ... Pokemon ... + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/reject.rb b/modules/stdlib/lib/puppet/parser/functions/reject.rb new file mode 100644 index 0000000..1953ffc --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/reject.rb @@ -0,0 +1,31 @@ +# +# reject.rb +# + +module Puppet::Parser::Functions + newfunction(:reject, :type => :rvalue, :doc => <<-EOS) do |args| +This function searches through an array and rejects all elements that match +the provided regular expression. + +*Examples:* + + reject(['aaa','bbb','ccc','aaaddd'], 'aaa') + +Would return: + + ['bbb','ccc'] +EOS + + if (args.size != 2) + raise Puppet::ParseError, + "reject(): Wrong number of arguments given #{args.size} for 2" + end + + ary = args[0] + pattern = Regexp.new(args[1]) + + ary.reject { |e| e =~ pattern } + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/reverse.rb b/modules/stdlib/lib/puppet/parser/functions/reverse.rb new file mode 100644 index 0000000..fe04869 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/reverse.rb @@ -0,0 +1,28 @@ +# +# reverse.rb +# + +module Puppet::Parser::Functions + newfunction(:reverse, :type => :rvalue, :doc => <<-EOS +Reverses the order of a string or array. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "reverse(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'reverse(): Requires either ' + + 'array or string to work with') + end + + result = value.reverse + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/rstrip.rb b/modules/stdlib/lib/puppet/parser/functions/rstrip.rb new file mode 100644 index 0000000..29b0998 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/rstrip.rb @@ -0,0 +1,32 @@ +# +# rstrip.rb +# + +module Puppet::Parser::Functions + newfunction(:rstrip, :type => :rvalue, :doc => <<-EOS +Strips leading spaces to the right of the string. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "rstrip(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'rstrip(): Requires either ' + + 'array or string to work with') + end + + if value.is_a?(Array) + result = value.collect { |i| i.is_a?(String) ? i.rstrip : i } + else + result = value.rstrip + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/shuffle.rb b/modules/stdlib/lib/puppet/parser/functions/shuffle.rb new file mode 100644 index 0000000..18134ab --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/shuffle.rb @@ -0,0 +1,46 @@ +# +# shuffle.rb +# + +module Puppet::Parser::Functions + newfunction(:shuffle, :type => :rvalue, :doc => <<-EOS +Randomizes the order of a string or array elements. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "shuffle(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'shuffle(): Requires either ' + + 'array or string to work with') + end + + result = value.clone + + string = value.is_a?(String) ? true : false + + # Check whether it makes sense to shuffle ... + return result if result.size <= 1 + + # We turn any string value into an array to be able to shuffle ... + result = string ? result.split('') : result + + elements = result.size + + # Simple implementation of Fisher–Yates in-place shuffle ... + elements.times do |i| + j = rand(elements - i) + i + result[j], result[i] = result[i], result[j] + end + + result = string ? result.join : result + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/size.rb b/modules/stdlib/lib/puppet/parser/functions/size.rb new file mode 100644 index 0000000..cc207e3 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/size.rb @@ -0,0 +1,48 @@ +# +# size.rb +# + +# TODO(Krzysztof Wilczynski): Support for hashes would be nice too ... + +module Puppet::Parser::Functions + newfunction(:size, :type => :rvalue, :doc => <<-EOS +Returns the number of elements in a string or array. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "size(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + item = arguments[0] + + if item.is_a?(String) + + begin + # + # Check whether your item is a numeric value or not ... + # This will take care about positive and/or negative numbers + # for both integer and floating-point values ... + # + # Please note that Puppet has no notion of hexadecimal + # nor octal numbers for its DSL at this point in time ... + # + Float(item) + + raise(Puppet::ParseError, 'size(): Requires either ' + + 'string or array to work with') + + rescue ArgumentError + result = item.size + end + + elsif item.is_a?(Array) + result = item.size + else + raise(Puppet::ParseError, 'size(): Unknown type given') + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/sort.rb b/modules/stdlib/lib/puppet/parser/functions/sort.rb new file mode 100644 index 0000000..cefbe54 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/sort.rb @@ -0,0 +1,27 @@ +# +# sort.rb +# + +module Puppet::Parser::Functions + newfunction(:sort, :type => :rvalue, :doc => <<-EOS +Sorts strings and arrays lexically. + EOS + ) do |arguments| + + if (arguments.size != 1) then + raise(Puppet::ParseError, "sort(): Wrong number of arguments "+ + "given #{arguments.size} for 1") + end + + value = arguments[0] + + if value.is_a?(Array) then + value.sort + elsif value.is_a?(String) then + value.split("").sort.join("") + end + + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/squeeze.rb b/modules/stdlib/lib/puppet/parser/functions/squeeze.rb new file mode 100644 index 0000000..81fadfd --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/squeeze.rb @@ -0,0 +1,36 @@ +# +# squeeze.rb +# + +module Puppet::Parser::Functions + newfunction(:squeeze, :type => :rvalue, :doc => <<-EOS +Returns a new string where runs of the same character that occur in this set are replaced by a single character. + EOS + ) do |arguments| + + if ((arguments.size != 2) and (arguments.size != 1)) then + raise(Puppet::ParseError, "squeeze(): Wrong number of arguments "+ + "given #{arguments.size} for 2 or 1") + end + + item = arguments[0] + squeezeval = arguments[1] + + if item.is_a?(Array) then + if squeezeval then + item.collect { |i| i.squeeze(squeezeval) } + else + item.collect { |i| i.squeeze } + end + else + if squeezeval then + item.squeeze(squeezeval) + else + item.squeeze + end + end + + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/str2bool.rb b/modules/stdlib/lib/puppet/parser/functions/str2bool.rb new file mode 100644 index 0000000..446732e --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/str2bool.rb @@ -0,0 +1,46 @@ +# +# str2bool.rb +# + +module Puppet::Parser::Functions + newfunction(:str2bool, :type => :rvalue, :doc => <<-EOS +This converts a string to a boolean. This attempt to convert strings that +contain things like: y, 1, t, true to 'true' and strings that contain things +like: 0, f, n, false, no to 'false'. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "str2bool(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + string = arguments[0] + + # If string is already Boolean, return it + if !!string == string + return string + end + + unless string.is_a?(String) + raise(Puppet::ParseError, 'str2bool(): Requires either ' + + 'string to work with') + end + + # We consider all the yes, no, y, n and so on too ... + result = case string + # + # This is how undef looks like in Puppet ... + # We yield false in this case. + # + when /^$/, '' then false # Empty string will be false ... + when /^(1|t|y|true|yes)$/ then true + when /^(0|f|n|false|no)$/ then false + when /^(undef|undefined)$/ then false # This is not likely to happen ... + else + raise(Puppet::ParseError, 'str2bool(): Unknown type of boolean given') + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/str2saltedsha512.rb b/modules/stdlib/lib/puppet/parser/functions/str2saltedsha512.rb new file mode 100644 index 0000000..7fe7b01 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/str2saltedsha512.rb @@ -0,0 +1,32 @@ +# +# str2saltedsha512.rb +# + +module Puppet::Parser::Functions + newfunction(:str2saltedsha512, :type => :rvalue, :doc => <<-EOS +This converts a string to a salted-SHA512 password hash (which is used for +OS X versions >= 10.7). Given any simple string, you will get a hex version +of a salted-SHA512 password hash that can be inserted into your Puppet +manifests as a valid password attribute. + EOS + ) do |arguments| + require 'digest/sha2' + + raise(Puppet::ParseError, "str2saltedsha512(): Wrong number of arguments " + + "passed (#{arguments.size} but we require 1)") if arguments.size != 1 + + password = arguments[0] + + unless password.is_a?(String) + raise(Puppet::ParseError, 'str2saltedsha512(): Requires a ' + + "String argument, you passed: #{password.class}") + end + + seedint = rand(2**31 - 1) + seedstring = Array(seedint).pack("L") + saltedpass = Digest::SHA512.digest(seedstring + password) + (seedstring + saltedpass).unpack('H*')[0] + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/strftime.rb b/modules/stdlib/lib/puppet/parser/functions/strftime.rb new file mode 100644 index 0000000..0b52ade --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/strftime.rb @@ -0,0 +1,107 @@ +# +# strftime.rb +# + +module Puppet::Parser::Functions + newfunction(:strftime, :type => :rvalue, :doc => <<-EOS +This function returns formatted time. + +*Examples:* + +To return the time since epoch: + + strftime("%s") + +To return the date: + + strftime("%Y-%m-%d") + +*Format meaning:* + + %a - The abbreviated weekday name (``Sun'') + %A - The full weekday name (``Sunday'') + %b - The abbreviated month name (``Jan'') + %B - The full month name (``January'') + %c - The preferred local date and time representation + %C - Century (20 in 2009) + %d - Day of the month (01..31) + %D - Date (%m/%d/%y) + %e - Day of the month, blank-padded ( 1..31) + %F - Equivalent to %Y-%m-%d (the ISO 8601 date format) + %h - Equivalent to %b + %H - Hour of the day, 24-hour clock (00..23) + %I - Hour of the day, 12-hour clock (01..12) + %j - Day of the year (001..366) + %k - hour, 24-hour clock, blank-padded ( 0..23) + %l - hour, 12-hour clock, blank-padded ( 0..12) + %L - Millisecond of the second (000..999) + %m - Month of the year (01..12) + %M - Minute of the hour (00..59) + %n - Newline (\n) + %N - Fractional seconds digits, default is 9 digits (nanosecond) + %3N millisecond (3 digits) + %6N microsecond (6 digits) + %9N nanosecond (9 digits) + %p - Meridian indicator (``AM'' or ``PM'') + %P - Meridian indicator (``am'' or ``pm'') + %r - time, 12-hour (same as %I:%M:%S %p) + %R - time, 24-hour (%H:%M) + %s - Number of seconds since 1970-01-01 00:00:00 UTC. + %S - Second of the minute (00..60) + %t - Tab character (\t) + %T - time, 24-hour (%H:%M:%S) + %u - Day of the week as a decimal, Monday being 1. (1..7) + %U - Week number of the current year, + starting with the first Sunday as the first + day of the first week (00..53) + %v - VMS date (%e-%b-%Y) + %V - Week number of year according to ISO 8601 (01..53) + %W - Week number of the current year, + starting with the first Monday as the first + day of the first week (00..53) + %w - Day of the week (Sunday is 0, 0..6) + %x - Preferred representation for the date alone, no time + %X - Preferred representation for the time alone, no date + %y - Year without a century (00..99) + %Y - Year with century + %z - Time zone as hour offset from UTC (e.g. +0900) + %Z - Time zone name + %% - Literal ``%'' character + EOS + ) do |arguments| + + # Technically we support two arguments but only first is mandatory ... + raise(Puppet::ParseError, "strftime(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + format = arguments[0] + + raise(Puppet::ParseError, 'strftime(): You must provide ' + + 'format for evaluation') if format.empty? + + # The Time Zone argument is optional ... + time_zone = arguments[1] if arguments[1] + + time = Time.new + + # There is probably a better way to handle Time Zone ... + if time_zone and not time_zone.empty? + original_zone = ENV['TZ'] + + local_time = time.clone + local_time = local_time.utc + + ENV['TZ'] = time_zone + + time = local_time.localtime + + ENV['TZ'] = original_zone + end + + result = time.strftime(format) + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/strip.rb b/modules/stdlib/lib/puppet/parser/functions/strip.rb new file mode 100644 index 0000000..5f4630d --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/strip.rb @@ -0,0 +1,39 @@ +# +# strip.rb +# + +module Puppet::Parser::Functions + newfunction(:strip, :type => :rvalue, :doc => <<-EOS +This function removes leading and trailing whitespace from a string or from +every string inside an array. + +*Examples:* + + strip(" aaa ") + +Would result in: "aaa" + EOS + ) do |arguments| + + raise(Puppet::ParseError, "strip(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'strip(): Requires either ' + + 'array or string to work with') + end + + if value.is_a?(Array) + result = value.collect { |i| i.is_a?(String) ? i.strip : i } + else + result = value.strip + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/suffix.rb b/modules/stdlib/lib/puppet/parser/functions/suffix.rb new file mode 100644 index 0000000..f7792d6 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/suffix.rb @@ -0,0 +1,45 @@ +# +# suffix.rb +# + +module Puppet::Parser::Functions + newfunction(:suffix, :type => :rvalue, :doc => <<-EOS +This function applies a suffix to all elements in an array. + +*Examples:* + + suffix(['a','b','c'], 'p') + +Will return: ['ap','bp','cp'] + EOS + ) do |arguments| + + # Technically we support two arguments but only first is mandatory ... + raise(Puppet::ParseError, "suffix(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + array = arguments[0] + + unless array.is_a?(Array) + raise Puppet::ParseError, "suffix(): expected first argument to be an Array, got #{array.inspect}" + end + + suffix = arguments[1] if arguments[1] + + if suffix + unless suffix.is_a? String + raise Puppet::ParseError, "suffix(): expected second argument to be a String, got #{suffix.inspect}" + end + end + + # Turn everything into string same as join would do ... + result = array.collect do |i| + i = i.to_s + suffix ? i + suffix : i + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/swapcase.rb b/modules/stdlib/lib/puppet/parser/functions/swapcase.rb new file mode 100644 index 0000000..b9e6632 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/swapcase.rb @@ -0,0 +1,39 @@ +# +# swapcase.rb +# + +module Puppet::Parser::Functions + newfunction(:swapcase, :type => :rvalue, :doc => <<-EOS +This function will swap the existing case of a string. + +*Examples:* + + swapcase("aBcD") + +Would result in: "AbCd" + EOS + ) do |arguments| + + raise(Puppet::ParseError, "swapcase(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'swapcase(): Requires either ' + + 'array or string to work with') + end + + if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + result = value.collect { |i| i.is_a?(String) ? i.swapcase : i } + else + result = value.swapcase + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/time.rb b/modules/stdlib/lib/puppet/parser/functions/time.rb new file mode 100644 index 0000000..0cddaf8 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/time.rb @@ -0,0 +1,49 @@ +# +# time.rb +# + +module Puppet::Parser::Functions + newfunction(:time, :type => :rvalue, :doc => <<-EOS +This function will return the current time since epoch as an integer. + +*Examples:* + + time() + +Will return something like: 1311972653 + EOS + ) do |arguments| + + # The Time Zone argument is optional ... + time_zone = arguments[0] if arguments[0] + + if (arguments.size != 0) and (arguments.size != 1) then + raise(Puppet::ParseError, "time(): Wrong number of arguments "+ + "given #{arguments.size} for 0 or 1") + end + + time = Time.new + + # There is probably a better way to handle Time Zone ... + if time_zone and not time_zone.empty? + original_zone = ENV['TZ'] + + local_time = time.clone + local_time = local_time.utc + + ENV['TZ'] = time_zone + + time = local_time.localtime + + ENV['TZ'] = original_zone + end + + # Calling Time#to_i on a receiver changes it. Trust me I am the Doctor. + result = time.strftime('%s') + result = result.to_i + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/to_bytes.rb b/modules/stdlib/lib/puppet/parser/functions/to_bytes.rb new file mode 100644 index 0000000..8ff73d1 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/to_bytes.rb @@ -0,0 +1,28 @@ +module Puppet::Parser::Functions + newfunction(:to_bytes, :type => :rvalue, :doc => <<-EOS + Converts the argument into bytes, for example 4 kB becomes 4096. + Takes a single string value as an argument. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "to_bytes(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size != 1 + + arg = arguments[0] + + return arg if arg.is_a? Numeric + + value,prefix = */([0-9.e+-]*)\s*([^bB]?)/.match(arg)[1,2] + + value = value.to_f + case prefix + when '' then return value.to_i + when 'k' then return (value*(1<<10)).to_i + when 'M' then return (value*(1<<20)).to_i + when 'G' then return (value*(1<<30)).to_i + when 'T' then return (value*(1<<40)).to_i + when 'E' then return (value*(1<<50)).to_i + else raise Puppet::ParseError, "to_bytes(): Unknown prefix #{prefix}" + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/type.rb b/modules/stdlib/lib/puppet/parser/functions/type.rb new file mode 100644 index 0000000..8d85f11 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/type.rb @@ -0,0 +1,50 @@ +# +# type.rb +# + +module Puppet::Parser::Functions + newfunction(:type, :type => :rvalue, :doc => <<-EOS +Returns the type when passed a variable. Type can be one of: + +* string +* array +* hash +* float +* integer +* boolean + EOS + ) do |arguments| + + raise(Puppet::ParseError, "type(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + + klass = value.class + + if not [TrueClass, FalseClass, Array, Bignum, Fixnum, Float, Hash, String].include?(klass) + raise(Puppet::ParseError, 'type(): Unknown type') + end + + klass = klass.to_s # Ugly ... + + # We note that Integer is the parent to Bignum and Fixnum ... + result = case klass + when /^(?:Big|Fix)num$/ then 'integer' + when /^(?:True|False)Class$/ then 'boolean' + else klass + end + + if result == "String" then + if value == value.to_i.to_s then + result = "Integer" + elsif value == value.to_f.to_s then + result = "Float" + end + end + + return result.downcase + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/union.rb b/modules/stdlib/lib/puppet/parser/functions/union.rb new file mode 100644 index 0000000..c91bb80 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/union.rb @@ -0,0 +1,34 @@ +# +# union.rb +# + +module Puppet::Parser::Functions + newfunction(:union, :type => :rvalue, :doc => <<-EOS +This function returns a union of two arrays. + +*Examples:* + + union(["a","b","c"],["b","c","d"]) + +Would return: ["a","b","c","d"] + EOS + ) do |arguments| + + # Two arguments are required + raise(Puppet::ParseError, "union(): Wrong number of arguments " + + "given (#{arguments.size} for 2)") if arguments.size != 2 + + first = arguments[0] + second = arguments[1] + + unless first.is_a?(Array) && second.is_a?(Array) + raise(Puppet::ParseError, 'union(): Requires 2 arrays') + end + + result = first | second + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/unique.rb b/modules/stdlib/lib/puppet/parser/functions/unique.rb new file mode 100644 index 0000000..8844a74 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/unique.rb @@ -0,0 +1,51 @@ +# +# unique.rb +# + +module Puppet::Parser::Functions + newfunction(:unique, :type => :rvalue, :doc => <<-EOS +This function will remove duplicates from strings and arrays. + +*Examples:* + + unique("aabbcc") + +Will return: + + abc + +You can also use this with arrays: + + unique(["a","a","b","b","c","c"]) + +This returns: + + ["a","b","c"] + EOS + ) do |arguments| + + raise(Puppet::ParseError, "unique(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'unique(): Requires either ' + + 'array or string to work with') + end + + result = value.clone + + string = value.is_a?(String) ? true : false + + # We turn any string value into an array to be able to shuffle ... + result = string ? result.split('') : result + result = result.uniq # Remove duplicates ... + result = string ? result.join : result + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/upcase.rb b/modules/stdlib/lib/puppet/parser/functions/upcase.rb new file mode 100644 index 0000000..fe6cadc --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/upcase.rb @@ -0,0 +1,41 @@ +# +# upcase.rb +# + +module Puppet::Parser::Functions + newfunction(:upcase, :type => :rvalue, :doc => <<-EOS +Converts a string or an array of strings to uppercase. + +*Examples:* + + upcase("abcd") + +Will return: + + ASDF + EOS + ) do |arguments| + + raise(Puppet::ParseError, "upcase(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'upcase(): Requires either ' + + 'array or string to work with') + end + + if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + result = value.collect { |i| i.is_a?(String) ? i.upcase : i } + else + result = value.upcase + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/uriescape.rb b/modules/stdlib/lib/puppet/parser/functions/uriescape.rb new file mode 100644 index 0000000..0d81de5 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/uriescape.rb @@ -0,0 +1,35 @@ +# +# uriescape.rb +# +require 'uri' + +module Puppet::Parser::Functions + newfunction(:uriescape, :type => :rvalue, :doc => <<-EOS + Urlencodes a string or array of strings. + Requires either a single string or an array as an input. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "uriescape(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + value = arguments[0] + klass = value.class + + unless [Array, String].include?(klass) + raise(Puppet::ParseError, 'uriescape(): Requires either ' + + 'array or string to work with') + end + + if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + result = value.collect { |i| i.is_a?(String) ? URI.escape(i,unsafe) : i } + else + result = URI.escape(value) + end + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/validate_absolute_path.rb b/modules/stdlib/lib/puppet/parser/functions/validate_absolute_path.rb new file mode 100644 index 0000000..fe27974 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/validate_absolute_path.rb @@ -0,0 +1,56 @@ +module Puppet::Parser::Functions + newfunction(:validate_absolute_path, :doc => <<-'ENDHEREDOC') do |args| + Validate the string represents an absolute path in the filesystem. This function works + for windows and unix style paths. + + The following values will pass: + + $my_path = "C:/Program Files (x86)/Puppet Labs/Puppet" + validate_absolute_path($my_path) + $my_path2 = "/var/lib/puppet" + validate_absolute_path($my_path2) + + + The following values will fail, causing compilation to abort: + + validate_absolute_path(true) + validate_absolute_path([ 'var/lib/puppet', '/var/foo' ]) + validate_absolute_path([ '/var/lib/puppet', 'var/foo' ]) + $undefined = undef + validate_absolute_path($undefined) + + ENDHEREDOC + + require 'puppet/util' + + unless args.length > 0 then + raise Puppet::ParseError, ("validate_absolute_path(): wrong number of arguments (#{args.length}; must be > 0)") + end + + args.each do |arg| + # This logic was borrowed from + # [lib/puppet/file_serving/base.rb](https://github.com/puppetlabs/puppet/blob/master/lib/puppet/file_serving/base.rb) + + # Puppet 2.7 and beyond will have Puppet::Util.absolute_path? Fall back to a back-ported implementation otherwise. + if Puppet::Util.respond_to?(:absolute_path?) then + unless Puppet::Util.absolute_path?(arg, :posix) or Puppet::Util.absolute_path?(arg, :windows) + raise Puppet::ParseError, ("#{arg.inspect} is not an absolute path.") + end + else + # This code back-ported from 2.7.x's lib/puppet/util.rb Puppet::Util.absolute_path? + # Determine in a platform-specific way whether a path is absolute. This + # defaults to the local platform if none is specified. + # Escape once for the string literal, and once for the regex. + slash = '[\\\\/]' + name = '[^\\\\/]+' + regexes = { + :windows => %r!^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))!i, + :posix => %r!^/!, + } + + rval = (!!(arg =~ regexes[:posix])) || (!!(arg =~ regexes[:windows])) + rval or raise Puppet::ParseError, ("#{arg.inspect} is not an absolute path.") + end + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/validate_array.rb b/modules/stdlib/lib/puppet/parser/functions/validate_array.rb new file mode 100644 index 0000000..34b5118 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/validate_array.rb @@ -0,0 +1,33 @@ +module Puppet::Parser::Functions + + newfunction(:validate_array, :doc => <<-'ENDHEREDOC') do |args| + Validate that all passed values are array data structures. Abort catalog + compilation if any value fails this check. + + The following values will pass: + + $my_array = [ 'one', 'two' ] + validate_array($my_array) + + The following values will fail, causing compilation to abort: + + validate_array(true) + validate_array('some_string') + $undefined = undef + validate_array($undefined) + + ENDHEREDOC + + unless args.length > 0 then + raise Puppet::ParseError, ("validate_array(): wrong number of arguments (#{args.length}; must be > 0)") + end + + args.each do |arg| + unless arg.is_a?(Array) + raise Puppet::ParseError, ("#{arg.inspect} is not an Array. It looks to be a #{arg.class}") + end + end + + end + +end diff --git a/modules/stdlib/lib/puppet/parser/functions/validate_augeas.rb b/modules/stdlib/lib/puppet/parser/functions/validate_augeas.rb new file mode 100644 index 0000000..154d660 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/validate_augeas.rb @@ -0,0 +1,81 @@ +module Puppet::Parser::Functions + newfunction(:validate_augeas, :doc => <<-'ENDHEREDOC') do |args| + Perform validation of a string using an Augeas lens + The first argument of this function should be a string to + test, and the second argument should be the name of the Augeas lens to use. + If Augeas fails to parse the string with the lens, the compilation will + abort with a parse error. + + A third argument can be specified, listing paths which should + not be found in the file. The `$file` variable points to the location + of the temporary file being tested in the Augeas tree. + + For example, if you want to make sure your passwd content never contains + a user `foo`, you could write: + + validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo']) + + Or if you wanted to ensure that no users used the '/bin/barsh' shell, + you could use: + + validate_augeas($passwdcontent, 'Passwd.lns', ['$file/*[shell="/bin/barsh"]'] + + If a fourth argument is specified, this will be the error message raised and + seen by the user. + + A helpful error message can be returned like this: + + validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas') + + ENDHEREDOC + unless Puppet.features.augeas? + raise Puppet::ParseError, ("validate_augeas(): this function requires the augeas feature. See http://projects.puppetlabs.com/projects/puppet/wiki/Puppet_Augeas#Pre-requisites for how to activate it.") + end + + if (args.length < 2) or (args.length > 4) then + raise Puppet::ParseError, ("validate_augeas(): wrong number of arguments (#{args.length}; must be 2, 3, or 4)") + end + + msg = args[3] || "validate_augeas(): Failed to validate content against #{args[1].inspect}" + + require 'augeas' + aug = Augeas::open(nil, nil, Augeas::NO_MODL_AUTOLOAD) + begin + content = args[0] + + # Test content in a temporary file + tmpfile = Tempfile.new("validate_augeas") + begin + tmpfile.write(content) + ensure + tmpfile.close + end + + # Check for syntax + lens = args[1] + aug.transform( + :lens => lens, + :name => 'Validate_augeas', + :incl => tmpfile.path + ) + aug.load! + + unless aug.match("/augeas/files#{tmpfile.path}//error").empty? + error = aug.get("/augeas/files#{tmpfile.path}//error/message") + msg += " with error: #{error}" + raise Puppet::ParseError, (msg) + end + + # Launch unit tests + tests = args[2] || [] + aug.defvar('file', "/files#{tmpfile.path}") + tests.each do |t| + msg += " testing path #{t}" + raise Puppet::ParseError, (msg) unless aug.match(t).empty? + end + ensure + aug.close + tmpfile.unlink + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/validate_bool.rb b/modules/stdlib/lib/puppet/parser/functions/validate_bool.rb new file mode 100644 index 0000000..59a0805 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/validate_bool.rb @@ -0,0 +1,34 @@ +module Puppet::Parser::Functions + + newfunction(:validate_bool, :doc => <<-'ENDHEREDOC') do |args| + Validate that all passed values are either true or false. Abort catalog + compilation if any value fails this check. + + The following values will pass: + + $iamtrue = true + validate_bool(true) + validate_bool(true, true, false, $iamtrue) + + The following values will fail, causing compilation to abort: + + $some_array = [ true ] + validate_bool("false") + validate_bool("true") + validate_bool($some_array) + + ENDHEREDOC + + unless args.length > 0 then + raise Puppet::ParseError, ("validate_bool(): wrong number of arguments (#{args.length}; must be > 0)") + end + + args.each do |arg| + unless function_is_bool([arg]) + raise Puppet::ParseError, ("#{arg.inspect} is not a boolean. It looks to be a #{arg.class}") + end + end + + end + +end diff --git a/modules/stdlib/lib/puppet/parser/functions/validate_cmd.rb b/modules/stdlib/lib/puppet/parser/functions/validate_cmd.rb new file mode 100644 index 0000000..2ebe91c --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/validate_cmd.rb @@ -0,0 +1,48 @@ +require 'puppet/util/execution' + +module Puppet::Parser::Functions + newfunction(:validate_cmd, :doc => <<-'ENDHEREDOC') do |args| + Perform validation of a string with an external command. + The first argument of this function should be a string to + test, and the second argument should be a path to a test command + taking a file as last argument. If the command, launched against + a tempfile containing the passed string, returns a non-null value, + compilation will abort with a parse error. + + If a third argument is specified, this will be the error message raised and + seen by the user. + + A helpful error message can be returned like this: + + Example: + + validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content') + + ENDHEREDOC + if (args.length < 2) or (args.length > 3) then + raise Puppet::ParseError, ("validate_cmd(): wrong number of arguments (#{args.length}; must be 2 or 3)") + end + + msg = args[2] || "validate_cmd(): failed to validate content with command #{args[1].inspect}" + + content = args[0] + checkscript = args[1] + + # Test content in a temporary file + tmpfile = Tempfile.new("validate_cmd") + begin + tmpfile.write(content) + tmpfile.close + if Puppet::Util::Execution.respond_to?('execute') + Puppet::Util::Execution.execute("#{checkscript} #{tmpfile.path}") + else + Puppet::Util.execute("#{checkscript} #{tmpfile.path}") + end + rescue Puppet::ExecutionFailure => detail + msg += "\n#{detail}" + raise Puppet::ParseError, msg + ensure + tmpfile.unlink + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/validate_hash.rb b/modules/stdlib/lib/puppet/parser/functions/validate_hash.rb new file mode 100644 index 0000000..9bdd543 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/validate_hash.rb @@ -0,0 +1,33 @@ +module Puppet::Parser::Functions + + newfunction(:validate_hash, :doc => <<-'ENDHEREDOC') do |args| + Validate that all passed values are hash data structures. Abort catalog + compilation if any value fails this check. + + The following values will pass: + + $my_hash = { 'one' => 'two' } + validate_hash($my_hash) + + The following values will fail, causing compilation to abort: + + validate_hash(true) + validate_hash('some_string') + $undefined = undef + validate_hash($undefined) + + ENDHEREDOC + + unless args.length > 0 then + raise Puppet::ParseError, ("validate_hash(): wrong number of arguments (#{args.length}; must be > 0)") + end + + args.each do |arg| + unless arg.is_a?(Hash) + raise Puppet::ParseError, ("#{arg.inspect} is not a Hash. It looks to be a #{arg.class}") + end + end + + end + +end diff --git a/modules/stdlib/lib/puppet/parser/functions/validate_ipv4_address.rb b/modules/stdlib/lib/puppet/parser/functions/validate_ipv4_address.rb new file mode 100644 index 0000000..fc02748 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/validate_ipv4_address.rb @@ -0,0 +1,48 @@ +module Puppet::Parser::Functions + + newfunction(:validate_ipv4_address, :doc => <<-ENDHEREDOC + Validate that all values passed are valid IPv4 addresses. + Fail compilation if any value fails this check. + + The following values will pass: + + $my_ip = "1.2.3.4" + validate_ipv4_address($my_ip) + validate_bool("8.8.8.8", "172.16.0.1", $my_ip) + + The following values will fail, causing compilation to abort: + + $some_array = [ 1, true, false, "garbage string", "3ffe:505:2" ] + validate_ipv4_address($some_array) + + ENDHEREDOC + ) do |args| + + require "ipaddr" + rescuable_exceptions = [ ArgumentError ] + + if defined?(IPAddr::InvalidAddressError) + rescuable_exceptions << IPAddr::InvalidAddressError + end + + unless args.length > 0 then + raise Puppet::ParseError, ("validate_ipv4_address(): wrong number of arguments (#{args.length}; must be > 0)") + end + + args.each do |arg| + unless arg.is_a?(String) + raise Puppet::ParseError, "#{arg.inspect} is not a string." + end + + begin + unless IPAddr.new(arg).ipv4? + raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv4 address." + end + rescue *rescuable_exceptions + raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv4 address." + end + end + + end + +end diff --git a/modules/stdlib/lib/puppet/parser/functions/validate_ipv6_address.rb b/modules/stdlib/lib/puppet/parser/functions/validate_ipv6_address.rb new file mode 100644 index 0000000..b0f2558 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/validate_ipv6_address.rb @@ -0,0 +1,49 @@ +module Puppet::Parser::Functions + + newfunction(:validate_ipv6_address, :doc => <<-ENDHEREDOC + Validate that all values passed are valid IPv6 addresses. + Fail compilation if any value fails this check. + + The following values will pass: + + $my_ip = "3ffe:505:2" + validate_ipv6_address(1) + validate_ipv6_address($my_ip) + validate_bool("fe80::baf6:b1ff:fe19:7507", $my_ip) + + The following values will fail, causing compilation to abort: + + $some_array = [ true, false, "garbage string", "1.2.3.4" ] + validate_ipv6_address($some_array) + + ENDHEREDOC + ) do |args| + + require "ipaddr" + rescuable_exceptions = [ ArgumentError ] + + if defined?(IPAddr::InvalidAddressError) + rescuable_exceptions << IPAddr::InvalidAddressError + end + + unless args.length > 0 then + raise Puppet::ParseError, ("validate_ipv6_address(): wrong number of arguments (#{args.length}; must be > 0)") + end + + args.each do |arg| + unless arg.is_a?(String) + raise Puppet::ParseError, "#{arg.inspect} is not a string." + end + + begin + unless IPAddr.new(arg).ipv6? + raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv6 address." + end + rescue *rescuable_exceptions + raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv6 address." + end + end + + end + +end diff --git a/modules/stdlib/lib/puppet/parser/functions/validate_re.rb b/modules/stdlib/lib/puppet/parser/functions/validate_re.rb new file mode 100644 index 0000000..ca25a70 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/validate_re.rb @@ -0,0 +1,40 @@ +module Puppet::Parser::Functions + newfunction(:validate_re, :doc => <<-'ENDHEREDOC') do |args| + Perform simple validation of a string against one or more regular + expressions. The first argument of this function should be a string to + test, and the second argument should be a stringified regular expression + (without the // delimiters) or an array of regular expressions. If none + of the regular expressions match the string passed in, compilation will + abort with a parse error. + + If a third argument is specified, this will be the error message raised and + seen by the user. + + The following strings will validate against the regular expressions: + + validate_re('one', '^one$') + validate_re('one', [ '^one', '^two' ]) + + The following strings will fail to validate, causing compilation to abort: + + validate_re('one', [ '^two', '^three' ]) + + A helpful error message can be returned like this: + + validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7') + + ENDHEREDOC + if (args.length < 2) or (args.length > 3) then + raise Puppet::ParseError, ("validate_re(): wrong number of arguments (#{args.length}; must be 2 or 3)") + end + + msg = args[2] || "validate_re(): #{args[0].inspect} does not match #{args[1].inspect}" + + # We're using a flattened array here because we can't call String#any? in + # Ruby 1.9 like we can in Ruby 1.8 + raise Puppet::ParseError, (msg) unless [args[1]].flatten.any? do |re_str| + args[0] =~ Regexp.compile(re_str) + end + + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/validate_slength.rb b/modules/stdlib/lib/puppet/parser/functions/validate_slength.rb new file mode 100644 index 0000000..7d534f3 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/validate_slength.rb @@ -0,0 +1,71 @@ +module Puppet::Parser::Functions + + newfunction(:validate_slength, :doc => <<-'ENDHEREDOC') do |args| + Validate that the first argument is a string (or an array of strings), and + less/equal to than the length of the second argument. An optional third + parameter can be given a the minimum length. It fails if the first + argument is not a string or array of strings, and if arg 2 and arg 3 are + not convertable to a number. + + The following values will pass: + + validate_slength("discombobulate",17) + validate_slength(["discombobulate","moo"],17) + validate_slength(["discombobulate","moo"],17,3) + + The following valueis will not: + + validate_slength("discombobulate",1) + validate_slength(["discombobulate","thermometer"],5) + validate_slength(["discombobulate","moo"],17,10) + + ENDHEREDOC + + raise Puppet::ParseError, "validate_slength(): Wrong number of arguments (#{args.length}; must be 2 or 3)" unless args.length == 2 or args.length == 3 + + input, max_length, min_length = *args + + begin + max_length = Integer(max_length) + raise ArgumentError if max_length <= 0 + rescue ArgumentError, TypeError + raise Puppet::ParseError, "validate_slength(): Expected second argument to be a positive Numeric, got #{max_length}:#{max_length.class}" + end + + if min_length + begin + min_length = Integer(min_length) + raise ArgumentError if min_length < 0 + rescue ArgumentError, TypeError + raise Puppet::ParseError, "validate_slength(): Expected third argument to be unset or a positive Numeric, got #{min_length}:#{min_length.class}" + end + else + min_length = 0 + end + + if min_length > max_length + raise Puppet::ParseError, "validate_slength(): Expected second argument to be larger than third argument" + end + + validator = lambda do |str| + unless str.length <= max_length and str.length >= min_length + raise Puppet::ParseError, "validate_slength(): Expected length of #{input.inspect} to be between #{min_length} and #{max_length}, was #{input.length}" + end + end + + case input + when String + validator.call(input) + when Array + input.each_with_index do |arg, pos| + if arg.is_a? String + validator.call(arg) + else + raise Puppet::ParseError, "validate_slength(): Expected element at array position #{pos} to be a String, got #{arg.class}" + end + end + else + raise Puppet::ParseError, "validate_slength(): Expected first argument to be a String or Array, got #{input.class}" + end + end +end diff --git a/modules/stdlib/lib/puppet/parser/functions/validate_string.rb b/modules/stdlib/lib/puppet/parser/functions/validate_string.rb new file mode 100644 index 0000000..e667794 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/validate_string.rb @@ -0,0 +1,33 @@ +module Puppet::Parser::Functions + + newfunction(:validate_string, :doc => <<-'ENDHEREDOC') do |args| + Validate that all passed values are string data structures. Abort catalog + compilation if any value fails this check. + + The following values will pass: + + $my_string = "one two" + validate_string($my_string, 'three') + + The following values will fail, causing compilation to abort: + + validate_string(true) + validate_string([ 'some', 'array' ]) + $undefined = undef + validate_string($undefined) + + ENDHEREDOC + + unless args.length > 0 then + raise Puppet::ParseError, ("validate_string(): wrong number of arguments (#{args.length}; must be > 0)") + end + + args.each do |arg| + unless arg.is_a?(String) + raise Puppet::ParseError, ("#{arg.inspect} is not a string. It looks to be a #{arg.class}") + end + end + + end + +end diff --git a/modules/stdlib/lib/puppet/parser/functions/values.rb b/modules/stdlib/lib/puppet/parser/functions/values.rb new file mode 100644 index 0000000..1606756 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/values.rb @@ -0,0 +1,39 @@ +# +# values.rb +# + +module Puppet::Parser::Functions + newfunction(:values, :type => :rvalue, :doc => <<-EOS +When given a hash this function will return the values of that hash. + +*Examples:* + + $hash = { + 'a' => 1, + 'b' => 2, + 'c' => 3, + } + values($hash) + +This example would return: + + [1,2,3] + EOS + ) do |arguments| + + raise(Puppet::ParseError, "values(): Wrong number of arguments " + + "given (#{arguments.size} for 1)") if arguments.size < 1 + + hash = arguments[0] + + unless hash.is_a?(Hash) + raise(Puppet::ParseError, 'values(): Requires hash to work with') + end + + result = hash.values + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/values_at.rb b/modules/stdlib/lib/puppet/parser/functions/values_at.rb new file mode 100644 index 0000000..d3e69d9 --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/values_at.rb @@ -0,0 +1,98 @@ +# +# values_at.rb +# + +module Puppet::Parser::Functions + newfunction(:values_at, :type => :rvalue, :doc => <<-EOS +Finds value inside an array based on location. + +The first argument is the array you want to analyze, and the second element can +be a combination of: + +* A single numeric index +* A range in the form of 'start-stop' (eg. 4-9) +* An array combining the above + +*Examples*: + + values_at(['a','b','c'], 2) + +Would return ['c']. + + values_at(['a','b','c'], ["0-1"]) + +Would return ['a','b']. + + values_at(['a','b','c','d','e'], [0, "2-3"]) + +Would return ['a','c','d']. + EOS + ) do |arguments| + + raise(Puppet::ParseError, "values_at(): Wrong number of " + + "arguments given (#{arguments.size} for 2)") if arguments.size < 2 + + array = arguments.shift + + unless array.is_a?(Array) + raise(Puppet::ParseError, 'values_at(): Requires array to work with') + end + + indices = [arguments.shift].flatten() # Get them all ... Pokemon ... + + if not indices or indices.empty? + raise(Puppet::ParseError, 'values_at(): You must provide ' + + 'at least one positive index to collect') + end + + result = [] + indices_list = [] + + indices.each do |i| + if m = i.match(/^(\d+)(\.\.\.?|\-)(\d+)$/) + start = m[1].to_i + stop = m[3].to_i + + type = m[2] + + if start > stop + raise(Puppet::ParseError, 'values_at(): Stop index in ' + + 'given indices range is smaller than the start index') + elsif stop > array.size - 1 # First element is at index 0 is it not? + raise(Puppet::ParseError, 'values_at(): Stop index in ' + + 'given indices range exceeds array size') + end + + range = case type + when /^(\.\.|\-)$/ then (start .. stop) + when /^(\.\.\.)$/ then (start ... stop) # Exclusive of last element ... + end + + range.each { |i| indices_list << i.to_i } + else + # Only positive numbers allowed in this case ... + if not i.match(/^\d+$/) + raise(Puppet::ParseError, 'values_at(): Unknown format ' + + 'of given index') + end + + # In Puppet numbers are often string-encoded ... + i = i.to_i + + if i > array.size - 1 # Same story. First element is at index 0 ... + raise(Puppet::ParseError, 'values_at(): Given index ' + + 'exceeds array size') + end + + indices_list << i + end + end + + # We remove nil values as they make no sense in Puppet DSL ... + result = indices_list.collect { |i| array[i] }.compact + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/parser/functions/zip.rb b/modules/stdlib/lib/puppet/parser/functions/zip.rb new file mode 100644 index 0000000..2b56e9c --- /dev/null +++ b/modules/stdlib/lib/puppet/parser/functions/zip.rb @@ -0,0 +1,65 @@ +# +# zip.rb +# + +module Puppet::Parser::Functions + newfunction(:zip, :type => :rvalue, :doc => <<-EOS +Takes one element from first array and merges corresponding elements from second array. This generates a sequence of n-element arrays, where n is one more than the count of arguments. + +*Example:* + + zip(['1','2','3'],['4','5','6']) + +Would result in: + + ["1", "4"], ["2", "5"], ["3", "6"] + EOS + ) do |arguments| + + # Technically we support three arguments but only first is mandatory ... + raise(Puppet::ParseError, "zip(): Wrong number of arguments " + + "given (#{arguments.size} for 2)") if arguments.size < 2 + + a = arguments[0] + b = arguments[1] + + unless a.is_a?(Array) and b.is_a?(Array) + raise(Puppet::ParseError, 'zip(): Requires array to work with') + end + + flatten = arguments[2] if arguments[2] + + if flatten + klass = flatten.class + + # We can have either true or false, or string which resembles boolean ... + unless [FalseClass, TrueClass, String].include?(klass) + raise(Puppet::ParseError, 'zip(): Requires either ' + + 'boolean or string to work with') + end + + if flatten.is_a?(String) + # We consider all the yes, no, y, n and so on too ... + flatten = case flatten + # + # This is how undef looks like in Puppet ... + # We yield false in this case. + # + when /^$/, '' then false # Empty string will be false ... + when /^(1|t|y|true|yes)$/ then true + when /^(0|f|n|false|no)$/ then false + when /^(undef|undefined)$/ then false # This is not likely to happen ... + else + raise(Puppet::ParseError, 'zip(): Unknown type of boolean given') + end + end + end + + result = a.zip(b) + result = flatten ? result.flatten : result + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/modules/stdlib/lib/puppet/provider/file_line/ruby.rb b/modules/stdlib/lib/puppet/provider/file_line/ruby.rb new file mode 100644 index 0000000..94e7fac --- /dev/null +++ b/modules/stdlib/lib/puppet/provider/file_line/ruby.rb @@ -0,0 +1,83 @@ +Puppet::Type.type(:file_line).provide(:ruby) do + def exists? + lines.find do |line| + line.chomp == resource[:line].chomp + end + end + + def create + if resource[:match] + handle_create_with_match + elsif resource[:after] + handle_create_with_after + else + append_line + end + end + + def destroy + local_lines = lines + File.open(resource[:path],'w') do |fh| + fh.write(local_lines.reject{|l| l.chomp == resource[:line] }.join('')) + end + end + + private + def lines + # If this type is ever used with very large files, we should + # write this in a different way, using a temp + # file; for now assuming that this type is only used on + # small-ish config files that can fit into memory without + # too much trouble. + @lines ||= File.readlines(resource[:path]) + end + + def handle_create_with_match() + regex = resource[:match] ? Regexp.new(resource[:match]) : nil + match_count = lines.select { |l| regex.match(l) }.size + if match_count > 1 && resource[:multiple].to_s != 'true' + raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'" + end + File.open(resource[:path], 'w') do |fh| + lines.each do |l| + fh.puts(regex.match(l) ? resource[:line] : l) + end + + if (match_count == 0) + fh.puts(resource[:line]) + end + end + end + + def handle_create_with_after + regex = Regexp.new(resource[:after]) + + count = lines.count {|l| l.match(regex)} + + case count + when 1 # find the line to put our line after + File.open(resource[:path], 'w') do |fh| + lines.each do |l| + fh.puts(l) + if regex.match(l) then + fh.puts(resource[:line]) + end + end + end + when 0 # append the line to the end of the file + append_line + else + raise Puppet::Error, "#{count} lines match pattern '#{resource[:after]}' in file '#{resource[:path]}'. One or no line must match the pattern." + end + end + + ## + # append the line to the file. + # + # @api private + def append_line + File.open(resource[:path], 'a') do |fh| + fh.puts resource[:line] + end + end +end diff --git a/modules/stdlib/lib/puppet/type/anchor.rb b/modules/stdlib/lib/puppet/type/anchor.rb new file mode 100644 index 0000000..fe1e5aa --- /dev/null +++ b/modules/stdlib/lib/puppet/type/anchor.rb @@ -0,0 +1,46 @@ +Puppet::Type.newtype(:anchor) do + desc <<-'ENDOFDESC' + A simple resource type intended to be used as an anchor in a composite class. + + In Puppet 2.6, when a class declares another class, the resources in the + interior class are not contained by the exterior class. This interacts badly + with the pattern of composing complex modules from smaller classes, as it + makes it impossible for end users to specify order relationships between the + exterior class and other modules. + + The anchor type lets you work around this. By sandwiching any interior + classes between two no-op resources that _are_ contained by the exterior + class, you can ensure that all resources in the module are contained. + + class ntp { + # These classes will have the correct order relationship with each + # other. However, without anchors, they won't have any order + # relationship to Class['ntp']. + class { 'ntp::package': } + -> class { 'ntp::config': } + -> class { 'ntp::service': } + + # These two resources "anchor" the composed classes within the ntp + # class. + anchor { 'ntp::begin': } -> Class['ntp::package'] + Class['ntp::service'] -> anchor { 'ntp::end': } + } + + This allows the end user of the ntp module to establish require and before + relationships with Class['ntp']: + + class { 'ntp': } -> class { 'mcollective': } + class { 'mcollective': } -> class { 'ntp': } + + ENDOFDESC + + newparam :name do + desc "The name of the anchor resource." + end + + def refresh + # We don't do anything with them, but we need this to + # show that we are "refresh aware" and not break the + # chain of propagation. + end +end diff --git a/modules/stdlib/lib/puppet/type/file_line.rb b/modules/stdlib/lib/puppet/type/file_line.rb new file mode 100644 index 0000000..323fc4c --- /dev/null +++ b/modules/stdlib/lib/puppet/type/file_line.rb @@ -0,0 +1,79 @@ +Puppet::Type.newtype(:file_line) do + + desc <<-EOT + Ensures that a given line is contained within a file. The implementation + matches the full line, including whitespace at the beginning and end. If + the line is not contained in the given file, Puppet will add the line to + ensure the desired state. Multiple resources may be declared to manage + multiple lines in the same file. + + Example: + + file_line { 'sudo_rule': + path => '/etc/sudoers', + line => '%sudo ALL=(ALL) ALL', + } + file_line { 'sudo_rule_nopw': + path => '/etc/sudoers', + line => '%sudonopw ALL=(ALL) NOPASSWD: ALL', + } + + In this example, Puppet will ensure both of the specified lines are + contained in the file /etc/sudoers. + + EOT + + ensurable do + defaultvalues + defaultto :present + end + + newparam(:name, :namevar => true) do + desc 'An arbitrary name used as the identity of the resource.' + end + + newparam(:match) do + desc 'An optional regular expression to run against existing lines in the file;\n' + + 'if a match is found, we replace that line rather than adding a new line.' + end + + newparam(:multiple) do + desc 'An optional value to determine if match can change multiple lines.' + newvalues(true, false) + end + + newparam(:after) do + desc 'An optional value used to specify the line after which we will add any new lines. (Existing lines are added in place)' + end + + newparam(:line) do + desc 'The line to be appended to the file located by the path parameter.' + end + + newparam(:path) do + desc 'The file Puppet will ensure contains the line specified by the line parameter.' + validate do |value| + unless (Puppet.features.posix? and value =~ /^\//) or (Puppet.features.microsoft_windows? and (value =~ /^.:\// or value =~ /^\/\/[^\/]+\/[^\/]+/)) + raise(Puppet::Error, "File paths must be fully qualified, not '#{value}'") + end + end + end + + # Autorequire the file resource if it's being managed + autorequire(:file) do + self[:path] + end + + validate do + unless self[:line] and self[:path] + raise(Puppet::Error, "Both line and path are required attributes") + end + + if (self[:match]) + unless Regexp.new(self[:match]).match(self[:line]) + raise(Puppet::Error, "When providing a 'match' parameter, the value must be a regex that matches against the value of your 'line' parameter") + end + end + + end +end diff --git a/modules/stdlib/manifests/init.pp b/modules/stdlib/manifests/init.pp new file mode 100644 index 0000000..500ad77 --- /dev/null +++ b/modules/stdlib/manifests/init.pp @@ -0,0 +1,20 @@ +# Class: stdlib +# +# This module manages stdlib. Most of stdlib's features are automatically +# loaded by Puppet, but this class should be declared in order to use the +# standardized run stages. +# +# Parameters: none +# +# Actions: +# +# Declares all other classes in the stdlib module. Currently, this consists +# of stdlib::stages. +# +# Requires: nothing +# +class stdlib { + + class { 'stdlib::stages': } + +} diff --git a/modules/stdlib/manifests/stages.pp b/modules/stdlib/manifests/stages.pp new file mode 100644 index 0000000..eb15fd6 --- /dev/null +++ b/modules/stdlib/manifests/stages.pp @@ -0,0 +1,43 @@ +# Class: stdlib::stages +# +# This class manages a standard set of run stages for Puppet. It is managed by +# the stdlib class, and should not be declared independently. +# +# The high level stages are (in order): +# +# * setup +# * main +# * runtime +# * setup_infra +# * deploy_infra +# * setup_app +# * deploy_app +# * deploy +# +# Parameters: none +# +# Actions: +# +# Declares various run-stages for deploying infrastructure, +# language runtimes, and application layers. +# +# Requires: nothing +# +# Sample Usage: +# +# node default { +# include stdlib +# class { java: stage => 'runtime' } +# } +# +class stdlib::stages { + + stage { 'setup': before => Stage['main'] } + stage { 'runtime': require => Stage['main'] } + -> stage { 'setup_infra': } + -> stage { 'deploy_infra': } + -> stage { 'setup_app': } + -> stage { 'deploy_app': } + -> stage { 'deploy': } + +} diff --git a/modules/stdlib/metadata.json b/modules/stdlib/metadata.json new file mode 100644 index 0000000..1476071 --- /dev/null +++ b/modules/stdlib/metadata.json @@ -0,0 +1,111 @@ +{ + "name": "puppetlabs-stdlib", + "version": "4.2.2", + "author": "puppetlabs", + "summary": "Puppet Module Standard Library", + "license": "Apache 2.0", + "source": "git://github.com/puppetlabs/puppetlabs-stdlib.git", + "project_page": "https://github.com/puppetlabs/puppetlabs-stdlib", + "issues_url": "https://github.com/puppetlabs/puppetlabs-stdlib/issues", + "operatingsystem_support": [ + { + "operatingsystem": "RedHat", + "operatingsystemrelease": [ + "4", + "5", + "6", + "7" + ] + }, + { + "operatingsystem": "CentOS", + "operatingsystemrelease": [ + "4", + "5", + "6", + "7" + ] + }, + { + "operatingsystem": "OracleLinux", + "operatingsystemrelease": [ + "4", + "5", + "6", + "7" + ] + }, + { + "operatingsystem": "Scientific", + "operatingsystemrelease": [ + "4", + "5", + "6", + "7" + ] + }, + { + "operatingsystem": "SLES", + "operatingsystemrelease": [ + "11 SP1" + ] + }, + { + "operatingsystem": "Debian", + "operatingsystemrelease": [ + "6", + "7" + ] + }, + { + "operatingsystem": "Ubuntu", + "operatingsystemrelease": [ + "10.04", + "12.04", + "14.04" + ] + }, + { + "operatingsystem": "Solaris", + "operatingsystemrelease": [ + "10", + "11" + ] + }, + { + "operatingsystem": "Windows", + "operatingsystemrelease": [ + "Server 2003", + "Server 2003 R2", + "Server 2008", + "Server 2008 R2", + "Server 2012", + "Server 2012 R2", + "7", + "8" + ] + }, + { + "operatingsystem": "AIX", + "operatingsystemrelease": [ + "5.3", + "6.1", + "7.1" + ] + } + ], + "requirements": [ + { + "name": "pe", + "version_requirement": ">= 3.2.0 < 3.4.0" + }, + { + "name": "puppet", + "version_requirement": ">=2.7.20 <4.0.0" + } + ], + "description": "Standard Library for Puppet Modules", + "dependencies": [ + + ] +} diff --git a/modules/stdlib/spec/acceptance/abs_spec.rb b/modules/stdlib/spec/acceptance/abs_spec.rb new file mode 100755 index 0000000..8e05642 --- /dev/null +++ b/modules/stdlib/spec/acceptance/abs_spec.rb @@ -0,0 +1,30 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'abs function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should accept a string' do + pp = <<-EOS + $input = '-34.56' + $output = abs($input) + notify { $output: } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: 34.56/) + end + end + + it 'should accept a float' do + pp = <<-EOS + $input = -34.56 + $output = abs($input) + notify { $output: } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: 34.56/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/any2array_spec.rb b/modules/stdlib/spec/acceptance/any2array_spec.rb new file mode 100755 index 0000000..467d6af --- /dev/null +++ b/modules/stdlib/spec/acceptance/any2array_spec.rb @@ -0,0 +1,49 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'any2array function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should create an empty array' do + pp = <<-EOS + $input = '' + $output = any2array($input) + validate_array($output) + notify { "Output: ${output}": } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: Output: /) + end + end + + it 'should leave arrays modified' do + pp = <<-EOS + $input = ['test', 'array'] + $output = any2array($input) + validate_array($output) + notify { "Output: ${output}": } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: Output: testarray/) + end + end + + it 'should turn a hash into an array' do + pp = <<-EOS + $input = {'test' => 'array'} + $output = any2array($input) + + validate_array($output) + # Check each element of the array is a plain string. + validate_string($output[0]) + validate_string($output[1]) + notify { "Output: ${output}": } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: Output: testarray/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/base64_spec.rb b/modules/stdlib/spec/acceptance/base64_spec.rb new file mode 100755 index 0000000..97e1738 --- /dev/null +++ b/modules/stdlib/spec/acceptance/base64_spec.rb @@ -0,0 +1,18 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'base64 function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should encode then decode a string' do + pp = <<-EOS + $encodestring = base64('encode', 'thestring') + $decodestring = base64('decode', $encodestring) + notify { $decodestring: } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/thestring/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/bool2num_spec.rb b/modules/stdlib/spec/acceptance/bool2num_spec.rb new file mode 100755 index 0000000..7a70311 --- /dev/null +++ b/modules/stdlib/spec/acceptance/bool2num_spec.rb @@ -0,0 +1,34 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'bool2num function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + ['false', 'f', '0', 'n', 'no'].each do |bool| + it 'should convert a given boolean, #{bool}, to 0' do + pp = <<-EOS + $input = #{bool} + $output = bool2num($input) + notify { $output: } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: 0/) + end + end + end + + ['true', 't', '1', 'y', 'yes'].each do |bool| + it 'should convert a given boolean, #{bool}, to 1' do + pp = <<-EOS + $input = #{bool} + $output = bool2num($input) + notify { $output: } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: 1/) + end + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/build_csv.rb b/modules/stdlib/spec/acceptance/build_csv.rb new file mode 100755 index 0000000..62ecbf1 --- /dev/null +++ b/modules/stdlib/spec/acceptance/build_csv.rb @@ -0,0 +1,83 @@ +#!/usr/bin/env ruby +# vim: set sw=2 sts=2 et tw=80 : +require 'rspec' + +#XXX Super ugly hack to keep from starting beaker nodes +module Kernel + # make an alias of the original require + alias_method :original_require, :require + # rewrite require + def require name + original_require name if name != 'spec_helper_acceptance' + end +end +UNSUPPORTED_PLATFORMS = [] +def fact(*args) [] end +#XXX End hax + +# Get a list of functions for test coverage +function_list = Dir[File.join(File.dirname(__FILE__),"..","..","lib","puppet","parser","functions","*.rb")].collect do |function_rb| + File.basename(function_rb,".rb") +end + +## Configure rspec to parse tests +options = RSpec::Core::ConfigurationOptions.new(['spec/acceptance']) +configuration = RSpec::configuration +world = RSpec::world +options.parse_options +options.configure(configuration) +configuration.load_spec_files + +## Collect up tests and example groups into a hash +def get_tests(children) + children.inject({}) do |memo,c| + memo[c.description] = Hash.new + memo[c.description]["groups"] = get_tests(c.children) unless c.children.empty? + memo[c.description]["tests"] = c.examples.collect { |e| + e.description unless e.pending? + }.compact unless c.examples.empty? + memo[c.description]["pending_tests"] = c.examples.collect { |e| + e.description if e.pending? + }.compact unless c.examples.empty? + memo + end +end + +def count_test_types_in(type,group) + return 0 if group.nil? + group.inject(0) do |m,(k,v)| + m += v.length if k == type + m += count_tests_in(v) if v.is_a?(Hash) + m + end +end +def count_tests_in(group) + count_test_types_in('tests',group) +end +def count_pending_tests_in(group) + count_test_types_in('pending_tests',group) +end + +# Convert tests hash to csv format +def to_csv(function_list,tests) + function_list.collect do |function_name| + if v = tests["#{function_name} function"] + positive_tests = count_tests_in(v["groups"]["success"]) + negative_tests = count_tests_in(v["groups"]["failure"]) + pending_tests = + count_pending_tests_in(v["groups"]["failure"]) + + count_pending_tests_in(v["groups"]["failure"]) + else + positive_tests = 0 + negative_tests = 0 + pending_tests = 0 + end + sprintf("%-25s, %-9d, %-9d, %-9d", function_name,positive_tests,negative_tests,pending_tests) + end.compact +end + +tests = get_tests(world.example_groups) +csv = to_csv(function_list,tests) +percentage_tested = "#{tests.count*100/function_list.count}%" +printf("%-25s, %-9s, %-9s, %-9s\n","#{percentage_tested} have tests.","Positive","Negative","Pending") +puts csv diff --git a/modules/stdlib/spec/acceptance/capitalize_spec.rb b/modules/stdlib/spec/acceptance/capitalize_spec.rb new file mode 100755 index 0000000..e5e7b7b --- /dev/null +++ b/modules/stdlib/spec/acceptance/capitalize_spec.rb @@ -0,0 +1,33 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'capitalize function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should capitalize the first letter of a string' do + pp = <<-EOS + $input = 'this is a string' + $output = capitalize($input) + notify { $output: } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: This is a string/) + end + end + + it 'should capitalize the first letter of an array of strings' do + pp = <<-EOS + $input = ['this', 'is', 'a', 'string'] + $output = capitalize($input) + notify { $output: } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: This/) + expect(r.stdout).to match(/Notice: Is/) + expect(r.stdout).to match(/Notice: A/) + expect(r.stdout).to match(/Notice: String/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/chomp_spec.rb b/modules/stdlib/spec/acceptance/chomp_spec.rb new file mode 100755 index 0000000..f6c1595 --- /dev/null +++ b/modules/stdlib/spec/acceptance/chomp_spec.rb @@ -0,0 +1,21 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'chomp function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should eat the newline' do + pp = <<-EOS + $input = "test\n" + if size($input) != 5 { + fail("Size of ${input} is not 5.") + } + $output = chomp($input) + if size($output) != 4 { + fail("Size of ${input} is not 4.") + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + end +end diff --git a/modules/stdlib/spec/acceptance/chop_spec.rb b/modules/stdlib/spec/acceptance/chop_spec.rb new file mode 100755 index 0000000..dbc28da --- /dev/null +++ b/modules/stdlib/spec/acceptance/chop_spec.rb @@ -0,0 +1,45 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'chop function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should eat the last character' do + pp = <<-EOS + $input = "test" + if size($input) != 4 { + fail("Size of ${input} is not 4.") + } + $output = chop($input) + if size($output) != 3 { + fail("Size of ${input} is not 3.") + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + it 'should eat the last two characters of \r\n' do + pp = <<-EOS + $input = "test\r\n" + if size($input) != 6 { + fail("Size of ${input} is not 6.") + } + $output = chop($input) + if size($output) != 4 { + fail("Size of ${input} is not 4.") + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + + it 'should not fail on empty strings' do + pp = <<-EOS + $input = "" + $output = chop($input) + EOS + + apply_manifest(pp, :catch_failures => true) + end + end +end diff --git a/modules/stdlib/spec/acceptance/concat_spec.rb b/modules/stdlib/spec/acceptance/concat_spec.rb new file mode 100755 index 0000000..7bda365 --- /dev/null +++ b/modules/stdlib/spec/acceptance/concat_spec.rb @@ -0,0 +1,18 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'concat function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should concat one array to another' do + pp = <<-EOS + $output = concat(['1','2','3'],['4','5','6']) + validate_array($output) + if size($output) != 6 { + fail("${output} should have 6 elements.") + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + end +end diff --git a/modules/stdlib/spec/acceptance/count_spec.rb b/modules/stdlib/spec/acceptance/count_spec.rb new file mode 100755 index 0000000..51a40ba --- /dev/null +++ b/modules/stdlib/spec/acceptance/count_spec.rb @@ -0,0 +1,30 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'count function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should count elements in an array' do + pp = <<-EOS + $input = [1,2,3,4] + $output = count($input) + notify { $output: } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: 4/) + end + end + + it 'should count elements in an array that match a second argument' do + pp = <<-EOS + $input = [1,1,1,2] + $output = count($input, 1) + notify { $output: } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: 3/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/deep_merge_spec.rb b/modules/stdlib/spec/acceptance/deep_merge_spec.rb new file mode 100755 index 0000000..c0f9b12 --- /dev/null +++ b/modules/stdlib/spec/acceptance/deep_merge_spec.rb @@ -0,0 +1,20 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'deep_merge function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should deep merge two hashes' do + pp = <<-EOS + $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } + $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } } + $merged_hash = deep_merge($hash1, $hash2) + + if $merged_hash != { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } } { + fail("Hash was incorrectly merged.") + } + EOS + + apply_manifest(pp, :catch_failures => true) + end + end +end diff --git a/modules/stdlib/spec/acceptance/defined_with_params_spec.rb b/modules/stdlib/spec/acceptance/defined_with_params_spec.rb new file mode 100755 index 0000000..fc54450 --- /dev/null +++ b/modules/stdlib/spec/acceptance/defined_with_params_spec.rb @@ -0,0 +1,22 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'defined_with_params function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should successfully notify' do + pp = <<-EOS + user { 'dan': + ensure => present, + } + + if defined_with_params(User[dan], {'ensure' => 'present' }) { + notify { 'User defined with ensure=>present': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: User defined with ensure=>present/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/delete_at_spec.rb b/modules/stdlib/spec/acceptance/delete_at_spec.rb new file mode 100755 index 0000000..db0c01f --- /dev/null +++ b/modules/stdlib/spec/acceptance/delete_at_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'delete_at function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should delete elements of the array' do + pp = <<-EOS + $output = delete_at(['a','b','c','b'], 1) + if $output == ['a','c','b'] { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/delete_spec.rb b/modules/stdlib/spec/acceptance/delete_spec.rb new file mode 100755 index 0000000..a28604c --- /dev/null +++ b/modules/stdlib/spec/acceptance/delete_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'delete function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should delete elements of the array' do + pp = <<-EOS + $output = delete(['a','b','c','b'], 'b') + if $output == ['a','c'] { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/delete_undef_values_spec.rb b/modules/stdlib/spec/acceptance/delete_undef_values_spec.rb new file mode 100755 index 0000000..b7eda19 --- /dev/null +++ b/modules/stdlib/spec/acceptance/delete_undef_values_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'delete_undef_values function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should delete elements of the array' do + pp = <<-EOS + $output = delete_undef_values({a=>'A', b=>'', c=>undef, d => false}) + if $output == { a => 'A', b => '', d => false } { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/delete_values_spec.rb b/modules/stdlib/spec/acceptance/delete_values_spec.rb new file mode 100755 index 0000000..6d2369c --- /dev/null +++ b/modules/stdlib/spec/acceptance/delete_values_spec.rb @@ -0,0 +1,25 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'delete_values function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should delete elements of the hash' do + pp = <<-EOS + $a = { 'a' => 'A', 'b' => 'B', 'B' => 'C', 'd' => 'B' } + $b = { 'a' => 'A', 'B' => 'C' } + $o = delete_values($a, 'B') + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles non-hash arguments' + it 'handles improper argument counts' + end +end diff --git a/modules/stdlib/spec/acceptance/difference_spec.rb b/modules/stdlib/spec/acceptance/difference_spec.rb new file mode 100755 index 0000000..2fae5c4 --- /dev/null +++ b/modules/stdlib/spec/acceptance/difference_spec.rb @@ -0,0 +1,26 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'difference function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'returns non-duplicates in the first array' do + pp = <<-EOS + $a = ['a','b','c'] + $b = ['b','c','d'] + $c = ['a'] + $o = difference($a, $b) + if $o == $c { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles non-array arguments' + it 'handles improper argument counts' + end +end diff --git a/modules/stdlib/spec/acceptance/dirname_spec.rb b/modules/stdlib/spec/acceptance/dirname_spec.rb new file mode 100755 index 0000000..97913dd --- /dev/null +++ b/modules/stdlib/spec/acceptance/dirname_spec.rb @@ -0,0 +1,42 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'dirname function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + context 'absolute path' do + it 'returns the dirname' do + pp = <<-EOS + $a = '/path/to/a/file.txt' + $b = '/path/to/a' + $o = dirname($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + context 'relative path' do + it 'returns the dirname' do + pp = <<-EOS + $a = 'path/to/a/file.txt' + $b = 'path/to/a' + $o = dirname($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + end + describe 'failure' do + it 'handles improper argument counts' + end +end diff --git a/modules/stdlib/spec/acceptance/downcase_spec.rb b/modules/stdlib/spec/acceptance/downcase_spec.rb new file mode 100755 index 0000000..bc4e706 --- /dev/null +++ b/modules/stdlib/spec/acceptance/downcase_spec.rb @@ -0,0 +1,39 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'downcase function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'returns the downcase' do + pp = <<-EOS + $a = 'AOEU' + $b = 'aoeu' + $o = downcase($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'doesn\'t affect lowercase words' do + pp = <<-EOS + $a = 'aoeu aoeu' + $b = 'aoeu aoeu' + $o = downcase($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-strings' + end +end diff --git a/modules/stdlib/spec/acceptance/empty_spec.rb b/modules/stdlib/spec/acceptance/empty_spec.rb new file mode 100755 index 0000000..8b46aac --- /dev/null +++ b/modules/stdlib/spec/acceptance/empty_spec.rb @@ -0,0 +1,39 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'empty function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'recognizes empty strings' do + pp = <<-EOS + $a = '' + $b = true + $o = empty($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'recognizes non-empty strings' do + pp = <<-EOS + $a = 'aoeu' + $b = false + $o = empty($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-strings' + end +end diff --git a/modules/stdlib/spec/acceptance/ensure_packages_spec.rb b/modules/stdlib/spec/acceptance/ensure_packages_spec.rb new file mode 100755 index 0000000..aa7b14c --- /dev/null +++ b/modules/stdlib/spec/acceptance/ensure_packages_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'ensure_packages function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'ensure_packages a package' do + apply_manifest('package { "zsh": ensure => absent, }') + pp = <<-EOS + $a = "zsh" + ensure_packages($a) + EOS + + apply_manifest(pp, :expect_changes => true) do |r| + expect(r.stdout).to match(/Package\[zsh\]\/ensure: (created|ensure changed 'purged' to 'present')/) + end + end + it 'ensures a package already declared' + it 'takes defaults arguments' + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings' + end +end diff --git a/modules/stdlib/spec/acceptance/ensure_resource_spec.rb b/modules/stdlib/spec/acceptance/ensure_resource_spec.rb new file mode 100755 index 0000000..c4d8887 --- /dev/null +++ b/modules/stdlib/spec/acceptance/ensure_resource_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'ensure_resource function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'ensure_resource a package' do + apply_manifest('package { "zsh": ensure => absent, }') + pp = <<-EOS + $a = "zsh" + ensure_resource('package', $a) + EOS + + apply_manifest(pp, :expect_changes => true) do |r| + expect(r.stdout).to match(/Package\[zsh\]\/ensure: created/) + end + end + it 'ensures a resource already declared' + it 'takes defaults arguments' + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings' + end +end diff --git a/modules/stdlib/spec/acceptance/flatten_spec.rb b/modules/stdlib/spec/acceptance/flatten_spec.rb new file mode 100755 index 0000000..c4d66e0 --- /dev/null +++ b/modules/stdlib/spec/acceptance/flatten_spec.rb @@ -0,0 +1,39 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'flatten function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'flattens arrays' do + pp = <<-EOS + $a = ["a","b",["c",["d","e"],"f","g"]] + $b = ["a","b","c","d","e","f","g"] + $o = flatten($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'does not affect flat arrays' do + pp = <<-EOS + $a = ["a","b","c","d","e","f","g"] + $b = ["a","b","c","d","e","f","g"] + $o = flatten($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-strings' + end +end diff --git a/modules/stdlib/spec/acceptance/floor_spec.rb b/modules/stdlib/spec/acceptance/floor_spec.rb new file mode 100755 index 0000000..0dcdad9 --- /dev/null +++ b/modules/stdlib/spec/acceptance/floor_spec.rb @@ -0,0 +1,39 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'floor function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'floors floats' do + pp = <<-EOS + $a = 12.8 + $b = 12 + $o = floor($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'floors integers' do + pp = <<-EOS + $a = 7 + $b = 7 + $o = floor($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-numbers' + end +end diff --git a/modules/stdlib/spec/acceptance/fqdn_rotate_spec.rb b/modules/stdlib/spec/acceptance/fqdn_rotate_spec.rb new file mode 100755 index 0000000..fc8bea2 --- /dev/null +++ b/modules/stdlib/spec/acceptance/fqdn_rotate_spec.rb @@ -0,0 +1,34 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'fqdn_rotate function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + let(:facts_d) do + if fact('is_pe') == "true" + '/etc/puppetlabs/facter/facts.d' + else + '/etc/facter/facts.d' + end + end + after :each do + shell("if [ -f #{facts_d}/fqdn.txt ] ; then rm #{facts_d}/fqdn.txt ; fi") + end + it 'fqdn_rotates floats' do + shell("mkdir -p #{facts_d}") + shell("echo 'fqdn=fakehost.localdomain' > #{facts_d}/fqdn.txt") + pp = <<-EOS + $a = ['a','b','c','d'] + $o = fqdn_rotate($a) + notice(inline_template('fqdn_rotate is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/fqdn_rotate is \["c", "d", "a", "b"\]/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-numbers' + end +end diff --git a/modules/stdlib/spec/acceptance/get_module_path_spec.rb b/modules/stdlib/spec/acceptance/get_module_path_spec.rb new file mode 100755 index 0000000..34d91fa --- /dev/null +++ b/modules/stdlib/spec/acceptance/get_module_path_spec.rb @@ -0,0 +1,41 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'get_module_path function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'get_module_paths stdlib' do + pp = <<-EOS + $a = $::is_pe ? { + 'true' => '/opt/puppet/share/puppet/modules/stdlib', + 'false' => '/etc/puppet/modules/stdlib', + } + $o = get_module_path('stdlib') + if $o == $a { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'get_module_paths dne' do + pp = <<-EOS + $a = $::is_pe ? { + 'true' => '/etc/puppetlabs/puppet/modules/dne', + 'false' => '/etc/puppet/modules/dne', + } + $o = get_module_path('dne') + if $o == $a { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :expect_failures => true) + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-numbers' + end +end diff --git a/modules/stdlib/spec/acceptance/getparam_spec.rb b/modules/stdlib/spec/acceptance/getparam_spec.rb new file mode 100755 index 0000000..91fc9a0 --- /dev/null +++ b/modules/stdlib/spec/acceptance/getparam_spec.rb @@ -0,0 +1,25 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'getparam function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'getparam a package' do + pp = <<-EOS + user { "rspec": + ensure => present, + managehome => true, + } + $o = getparam(User['rspec'], 'managehome') + notice(inline_template('getparam is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/getparam is true/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings' + end +end diff --git a/modules/stdlib/spec/acceptance/getvar_spec.rb b/modules/stdlib/spec/acceptance/getvar_spec.rb new file mode 100755 index 0000000..333c467 --- /dev/null +++ b/modules/stdlib/spec/acceptance/getvar_spec.rb @@ -0,0 +1,26 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'getvar function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'getvars from classes' do + pp = <<-EOS + class a::data { $foo = 'aoeu' } + include a::data + $b = 'aoeu' + $o = getvar("a::data::foo") + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-numbers' + end +end diff --git a/modules/stdlib/spec/acceptance/grep_spec.rb b/modules/stdlib/spec/acceptance/grep_spec.rb new file mode 100755 index 0000000..b39d48e --- /dev/null +++ b/modules/stdlib/spec/acceptance/grep_spec.rb @@ -0,0 +1,26 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'grep function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'greps arrays' do + pp = <<-EOS + $a = ['aaabbb','bbbccc','dddeee'] + $b = 'bbb' + $c = ['aaabbb','bbbccc'] + $o = grep($a,$b) + if $o == $c { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/has_interface_with_spec.rb b/modules/stdlib/spec/acceptance/has_interface_with_spec.rb new file mode 100755 index 0000000..41ae19f --- /dev/null +++ b/modules/stdlib/spec/acceptance/has_interface_with_spec.rb @@ -0,0 +1,44 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'has_interface_with function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'has_interface_with existing ipaddress' do + pp = <<-EOS + $a = '127.0.0.1' + $o = has_interface_with('ipaddress', $a) + notice(inline_template('has_interface_with is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/has_interface_with is true/) + end + end + it 'has_interface_with absent ipaddress' do + pp = <<-EOS + $a = '128.0.0.1' + $o = has_interface_with('ipaddress', $a) + notice(inline_template('has_interface_with is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/has_interface_with is false/) + end + end + it 'has_interface_with existing interface' do + pp = <<-EOS + $a = 'lo' + $o = has_interface_with($a) + notice(inline_template('has_interface_with is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/has_interface_with is true/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings' + end +end diff --git a/modules/stdlib/spec/acceptance/has_ip_address_spec.rb b/modules/stdlib/spec/acceptance/has_ip_address_spec.rb new file mode 100755 index 0000000..7d5fd87 --- /dev/null +++ b/modules/stdlib/spec/acceptance/has_ip_address_spec.rb @@ -0,0 +1,33 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'has_ip_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'has_ip_address existing ipaddress' do + pp = <<-EOS + $a = '127.0.0.1' + $o = has_ip_address($a) + notice(inline_template('has_ip_address is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/has_ip_address is true/) + end + end + it 'has_ip_address absent ipaddress' do + pp = <<-EOS + $a = '128.0.0.1' + $o = has_ip_address($a) + notice(inline_template('has_ip_address is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/has_ip_address is false/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings' + end +end diff --git a/modules/stdlib/spec/acceptance/has_ip_network_spec.rb b/modules/stdlib/spec/acceptance/has_ip_network_spec.rb new file mode 100755 index 0000000..692eaf9 --- /dev/null +++ b/modules/stdlib/spec/acceptance/has_ip_network_spec.rb @@ -0,0 +1,33 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'has_ip_network function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'has_ip_network existing ipaddress' do + pp = <<-EOS + $a = '127.0.0.0' + $o = has_ip_network($a) + notice(inline_template('has_ip_network is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/has_ip_network is true/) + end + end + it 'has_ip_network absent ipaddress' do + pp = <<-EOS + $a = '128.0.0.0' + $o = has_ip_network($a) + notice(inline_template('has_ip_network is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/has_ip_network is false/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings' + end +end diff --git a/modules/stdlib/spec/acceptance/has_key_spec.rb b/modules/stdlib/spec/acceptance/has_key_spec.rb new file mode 100755 index 0000000..c8557cb --- /dev/null +++ b/modules/stdlib/spec/acceptance/has_key_spec.rb @@ -0,0 +1,41 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'has_key function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'has_keys in hashes' do + pp = <<-EOS + $a = { 'aaa' => 'bbb','bbb' => 'ccc','ddd' => 'eee' } + $b = 'bbb' + $c = true + $o = has_key($a,$b) + if $o == $c { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'has_keys not in hashes' do + pp = <<-EOS + $a = { 'aaa' => 'bbb','bbb' => 'ccc','ddd' => 'eee' } + $b = 'ccc' + $c = false + $o = has_key($a,$b) + if $o == $c { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-hashes' + end +end diff --git a/modules/stdlib/spec/acceptance/hash_spec.rb b/modules/stdlib/spec/acceptance/hash_spec.rb new file mode 100755 index 0000000..ed53834 --- /dev/null +++ b/modules/stdlib/spec/acceptance/hash_spec.rb @@ -0,0 +1,26 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'hash function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'hashs arrays' do + pp = <<-EOS + $a = ['aaa','bbb','bbb','ccc','ddd','eee'] + $b = { 'aaa' => 'bbb', 'bbb' => 'ccc', 'ddd' => 'eee' } + $o = hash($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'handles odd-length arrays' + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/intersection_spec.rb b/modules/stdlib/spec/acceptance/intersection_spec.rb new file mode 100755 index 0000000..66b8652 --- /dev/null +++ b/modules/stdlib/spec/acceptance/intersection_spec.rb @@ -0,0 +1,27 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'intersection function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'intersections arrays' do + pp = <<-EOS + $a = ['aaa','bbb','ccc'] + $b = ['bbb','ccc','ddd','eee'] + $c = ['bbb','ccc'] + $o = intersection($a,$b) + if $o == $c { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'intersections empty arrays' + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/is_array_spec.rb b/modules/stdlib/spec/acceptance/is_array_spec.rb new file mode 100755 index 0000000..9c6bad7 --- /dev/null +++ b/modules/stdlib/spec/acceptance/is_array_spec.rb @@ -0,0 +1,67 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'is_array function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'is_arrays arrays' do + pp = <<-EOS + $a = ['aaa','bbb','ccc'] + $b = true + $o = is_array($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_arrays empty arrays' do + pp = <<-EOS + $a = [] + $b = true + $o = is_array($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_arrays strings' do + pp = <<-EOS + $a = "aoeu" + $b = false + $o = is_array($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_arrays hashes' do + pp = <<-EOS + $a = {'aaa'=>'bbb'} + $b = false + $o = is_array($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/is_bool_spec.rb b/modules/stdlib/spec/acceptance/is_bool_spec.rb new file mode 100755 index 0000000..60079f9 --- /dev/null +++ b/modules/stdlib/spec/acceptance/is_bool_spec.rb @@ -0,0 +1,81 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'is_bool function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'is_bools arrays' do + pp = <<-EOS + $a = ['aaa','bbb','ccc'] + $b = false + $o = is_bool($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_bools true' do + pp = <<-EOS + $a = true + $b = true + $o = is_bool($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_bools false' do + pp = <<-EOS + $a = false + $b = true + $o = is_bool($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_bools strings' do + pp = <<-EOS + $a = "true" + $b = false + $o = is_bool($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_bools hashes' do + pp = <<-EOS + $a = {'aaa'=>'bbb'} + $b = false + $o = is_bool($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/is_domain_name_spec.rb b/modules/stdlib/spec/acceptance/is_domain_name_spec.rb new file mode 100755 index 0000000..e0f03fa --- /dev/null +++ b/modules/stdlib/spec/acceptance/is_domain_name_spec.rb @@ -0,0 +1,83 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'is_domain_name function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'is_domain_names arrays' do + pp = <<-EOS + $a = ['aaa.com','bbb','ccc'] + $o = is_domain_name($a) + notice(inline_template('is_domain_name is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_domain_name is false/) + end + end + it 'is_domain_names true' do + pp = <<-EOS + $a = true + $o = is_domain_name($a) + notice(inline_template('is_domain_name is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_domain_name is false/) + end + end + it 'is_domain_names false' do + pp = <<-EOS + $a = false + $o = is_domain_name($a) + notice(inline_template('is_domain_name is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_domain_name is false/) + end + end + it 'is_domain_names strings with hyphens' do + pp = <<-EOS + $a = "3foo-bar.2bar-fuzz.com" + $b = true + $o = is_domain_name($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_domain_names strings beginning with hyphens' do + pp = <<-EOS + $a = "-bar.2bar-fuzz.com" + $b = false + $o = is_domain_name($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_domain_names hashes' do + pp = <<-EOS + $a = {'aaa'=>'www.com'} + $o = is_domain_name($a) + notice(inline_template('is_domain_name is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_domain_name is false/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/is_float_spec.rb b/modules/stdlib/spec/acceptance/is_float_spec.rb new file mode 100755 index 0000000..338ba58 --- /dev/null +++ b/modules/stdlib/spec/acceptance/is_float_spec.rb @@ -0,0 +1,86 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'is_float function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'is_floats arrays' do + pp = <<-EOS + $a = ['aaa.com','bbb','ccc'] + $o = is_float($a) + notice(inline_template('is_float is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_float is false/) + end + end + it 'is_floats true' do + pp = <<-EOS + $a = true + $o = is_float($a) + notice(inline_template('is_float is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_float is false/) + end + end + it 'is_floats strings' do + pp = <<-EOS + $a = "3.5" + $b = true + $o = is_float($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_floats floats' do + pp = <<-EOS + $a = 3.5 + $b = true + $o = is_float($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_floats integers' do + pp = <<-EOS + $a = 3 + $b = false + $o = is_float($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_floats hashes' do + pp = <<-EOS + $a = {'aaa'=>'www.com'} + $o = is_float($a) + notice(inline_template('is_float is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_float is false/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/is_function_available_spec.rb b/modules/stdlib/spec/acceptance/is_function_available_spec.rb new file mode 100755 index 0000000..2b5dd6d --- /dev/null +++ b/modules/stdlib/spec/acceptance/is_function_available_spec.rb @@ -0,0 +1,58 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'is_function_available function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'is_function_availables arrays' do + pp = <<-EOS + $a = ['fail','include','require'] + $o = is_function_available($a) + notice(inline_template('is_function_available is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_function_available is false/) + end + end + it 'is_function_availables true' do + pp = <<-EOS + $a = true + $o = is_function_available($a) + notice(inline_template('is_function_available is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_function_available is false/) + end + end + it 'is_function_availables strings' do + pp = <<-EOS + $a = "fail" + $b = true + $o = is_function_available($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_function_availables function_availables' do + pp = <<-EOS + $a = "is_function_available" + $o = is_function_available($a) + notice(inline_template('is_function_available is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_function_available is true/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/is_hash_spec.rb b/modules/stdlib/spec/acceptance/is_hash_spec.rb new file mode 100755 index 0000000..2ef310a --- /dev/null +++ b/modules/stdlib/spec/acceptance/is_hash_spec.rb @@ -0,0 +1,63 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'is_hash function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'is_hashs arrays' do + pp = <<-EOS + $a = ['aaa','bbb','ccc'] + $o = is_hash($a) + notice(inline_template('is_hash is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_hash is false/) + end + end + it 'is_hashs empty hashs' do + pp = <<-EOS + $a = {} + $b = true + $o = is_hash($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_hashs strings' do + pp = <<-EOS + $a = "aoeu" + $b = false + $o = is_hash($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_hashs hashes' do + pp = <<-EOS + $a = {'aaa'=>'bbb'} + $b = true + $o = is_hash($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + end +end diff --git a/modules/stdlib/spec/acceptance/is_integer_spec.rb b/modules/stdlib/spec/acceptance/is_integer_spec.rb new file mode 100755 index 0000000..bf6902b --- /dev/null +++ b/modules/stdlib/spec/acceptance/is_integer_spec.rb @@ -0,0 +1,95 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'is_integer function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'is_integers arrays' do + pp = <<-EOS + $a = ['aaa.com','bbb','ccc'] + $b = false + $o = is_integer($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_integers true' do + pp = <<-EOS + $a = true + $b = false + $o = is_integer($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_integers strings' do + pp = <<-EOS + $a = "3" + $b = true + $o = is_integer($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_integers floats' do + pp = <<-EOS + $a = 3.5 + $b = false + $o = is_integer($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_integers integers' do + pp = <<-EOS + $a = 3 + $b = true + $o = is_integer($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_integers hashes' do + pp = <<-EOS + $a = {'aaa'=>'www.com'} + $b = false + $o = is_integer($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/is_ip_address_spec.rb b/modules/stdlib/spec/acceptance/is_ip_address_spec.rb new file mode 100755 index 0000000..ed7a854 --- /dev/null +++ b/modules/stdlib/spec/acceptance/is_ip_address_spec.rb @@ -0,0 +1,80 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'is_ip_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'is_ip_addresss ipv4' do + pp = <<-EOS + $a = '1.2.3.4' + $b = true + $o = is_ip_address($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_ip_addresss ipv6' do + pp = <<-EOS + $a = "fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74" + $b = true + $o = is_ip_address($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_ip_addresss ipv6 compressed' do + pp = <<-EOS + $a = "fe00::1" + $b = true + $o = is_ip_address($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_ip_addresss strings' do + pp = <<-EOS + $a = "aoeu" + $b = false + $o = is_ip_address($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_ip_addresss ipv4 out of range' do + pp = <<-EOS + $a = '1.2.3.400' + $b = false + $o = is_ip_address($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + end +end diff --git a/modules/stdlib/spec/acceptance/is_mac_address_spec.rb b/modules/stdlib/spec/acceptance/is_mac_address_spec.rb new file mode 100755 index 0000000..a2c892f --- /dev/null +++ b/modules/stdlib/spec/acceptance/is_mac_address_spec.rb @@ -0,0 +1,38 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'is_mac_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'is_mac_addresss a mac' do + pp = <<-EOS + $a = '00:a0:1f:12:7f:a0' + $b = true + $o = is_mac_address($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_mac_addresss a mac out of range' do + pp = <<-EOS + $a = '00:a0:1f:12:7f:g0' + $b = false + $o = is_mac_address($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + end +end diff --git a/modules/stdlib/spec/acceptance/is_numeric_spec.rb b/modules/stdlib/spec/acceptance/is_numeric_spec.rb new file mode 100755 index 0000000..21c8988 --- /dev/null +++ b/modules/stdlib/spec/acceptance/is_numeric_spec.rb @@ -0,0 +1,95 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'is_numeric function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'is_numerics arrays' do + pp = <<-EOS + $a = ['aaa.com','bbb','ccc'] + $b = false + $o = is_numeric($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_numerics true' do + pp = <<-EOS + $a = true + $b = false + $o = is_numeric($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_numerics strings' do + pp = <<-EOS + $a = "3" + $b = true + $o = is_numeric($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_numerics floats' do + pp = <<-EOS + $a = 3.5 + $b = true + $o = is_numeric($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_numerics integers' do + pp = <<-EOS + $a = 3 + $b = true + $o = is_numeric($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_numerics hashes' do + pp = <<-EOS + $a = {'aaa'=>'www.com'} + $b = false + $o = is_numeric($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + it 'handles non-arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/is_string_spec.rb b/modules/stdlib/spec/acceptance/is_string_spec.rb new file mode 100755 index 0000000..94d8e96 --- /dev/null +++ b/modules/stdlib/spec/acceptance/is_string_spec.rb @@ -0,0 +1,102 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'is_string function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'is_strings arrays' do + pp = <<-EOS + $a = ['aaa.com','bbb','ccc'] + $b = false + $o = is_string($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_strings true' do + pp = <<-EOS + $a = true + $b = false + $o = is_string($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_strings strings' do + pp = <<-EOS + $a = "aoeu" + $o = is_string($a) + notice(inline_template('is_string is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_string is true/) + end + end + it 'is_strings number strings' do + pp = <<-EOS + $a = "3" + $o = is_string($a) + notice(inline_template('is_string is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/is_string is false/) + end + end + it 'is_strings floats' do + pp = <<-EOS + $a = 3.5 + $b = false + $o = is_string($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_strings integers' do + pp = <<-EOS + $a = 3 + $b = false + $o = is_string($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'is_strings hashes' do + pp = <<-EOS + $a = {'aaa'=>'www.com'} + $b = false + $o = is_string($a) + if $o == $b { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + end + describe 'failure' do + it 'handles improper argument counts' + end +end diff --git a/modules/stdlib/spec/acceptance/join_keys_to_values_spec.rb b/modules/stdlib/spec/acceptance/join_keys_to_values_spec.rb new file mode 100755 index 0000000..70493fd --- /dev/null +++ b/modules/stdlib/spec/acceptance/join_keys_to_values_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'join_keys_to_values function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'join_keys_to_valuess hashes' do + pp = <<-EOS + $a = {'aaa'=>'bbb','ccc'=>'ddd'} + $b = ':' + $o = join_keys_to_values($a,$b) + notice(inline_template('join_keys_to_values is <%= @o.sort.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/join_keys_to_values is \["aaa:bbb", "ccc:ddd"\]/) + end + end + it 'handles non hashes' + it 'handles empty hashes' + end + describe 'failure' do + it 'handles improper argument counts' + end +end diff --git a/modules/stdlib/spec/acceptance/join_spec.rb b/modules/stdlib/spec/acceptance/join_spec.rb new file mode 100755 index 0000000..5397ce2 --- /dev/null +++ b/modules/stdlib/spec/acceptance/join_spec.rb @@ -0,0 +1,26 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'join function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'joins arrays' do + pp = <<-EOS + $a = ['aaa','bbb','ccc'] + $b = ':' + $c = 'aaa:bbb:ccc' + $o = join($a,$b) + if $o == $c { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'handles non arrays' + end + describe 'failure' do + it 'handles improper argument counts' + end +end diff --git a/modules/stdlib/spec/acceptance/keys_spec.rb b/modules/stdlib/spec/acceptance/keys_spec.rb new file mode 100755 index 0000000..176918e --- /dev/null +++ b/modules/stdlib/spec/acceptance/keys_spec.rb @@ -0,0 +1,23 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'keys function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'keyss hashes' do + pp = <<-EOS + $a = {'aaa'=>'bbb','ccc'=>'ddd'} + $o = keys($a) + notice(inline_template('keys is <%= @o.sort.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/keys is \["aaa", "ccc"\]/) + end + end + it 'handles non hashes' + it 'handles empty hashes' + end + describe 'failure' do + it 'handles improper argument counts' + end +end diff --git a/modules/stdlib/spec/acceptance/loadyaml_spec.rb b/modules/stdlib/spec/acceptance/loadyaml_spec.rb new file mode 100644 index 0000000..944a727 --- /dev/null +++ b/modules/stdlib/spec/acceptance/loadyaml_spec.rb @@ -0,0 +1,31 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'loadyaml function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'loadyamls array of values' do + shell('echo "--- + aaa: 1 + bbb: 2 + ccc: 3 + ddd: 4" > /testyaml.yaml') + pp = <<-EOS + $o = loadyaml('/testyaml.yaml') + notice(inline_template('loadyaml[aaa] is <%= @o["aaa"].inspect %>')) + notice(inline_template('loadyaml[bbb] is <%= @o["bbb"].inspect %>')) + notice(inline_template('loadyaml[ccc] is <%= @o["ccc"].inspect %>')) + notice(inline_template('loadyaml[ddd] is <%= @o["ddd"].inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/loadyaml\[aaa\] is 1/) + expect(r.stdout).to match(/loadyaml\[bbb\] is 2/) + expect(r.stdout).to match(/loadyaml\[ccc\] is 3/) + expect(r.stdout).to match(/loadyaml\[ddd\] is 4/) + end + end + end + describe 'failure' do + it 'fails with no arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/lstrip_spec.rb b/modules/stdlib/spec/acceptance/lstrip_spec.rb new file mode 100755 index 0000000..3dc952f --- /dev/null +++ b/modules/stdlib/spec/acceptance/lstrip_spec.rb @@ -0,0 +1,34 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'lstrip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'lstrips arrays' do + pp = <<-EOS + $a = [" the "," public "," art","galleries "] + # Anagram: Large picture halls, I bet + $o = lstrip($a) + notice(inline_template('lstrip is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/lstrip is \["the ", "public ", "art", "galleries "\]/) + end + end + it 'lstrips strings' do + pp = <<-EOS + $a = " blowzy night-frumps vex'd jack q " + $o = lstrip($a) + notice(inline_template('lstrip is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/lstrip is "blowzy night-frumps vex'd jack q "/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings or arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/max_spec.rb b/modules/stdlib/spec/acceptance/max_spec.rb new file mode 100755 index 0000000..f04e3d2 --- /dev/null +++ b/modules/stdlib/spec/acceptance/max_spec.rb @@ -0,0 +1,20 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'max function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'maxs arrays' do + pp = <<-EOS + $o = max("the","public","art","galleries") + notice(inline_template('max is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/max is "the"/) + end + end + end + describe 'failure' do + it 'handles no arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/member_spec.rb b/modules/stdlib/spec/acceptance/member_spec.rb new file mode 100755 index 0000000..b467dbb --- /dev/null +++ b/modules/stdlib/spec/acceptance/member_spec.rb @@ -0,0 +1,26 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'member function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'members arrays' do + pp = <<-EOS + $a = ['aaa','bbb','ccc'] + $b = 'ccc' + $c = true + $o = member($a,$b) + if $o == $c { + notify { 'output correct': } + } + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/Notice: output correct/) + end + end + it 'members arrays without members' + end + describe 'failure' do + it 'handles improper argument counts' + end +end diff --git a/modules/stdlib/spec/acceptance/merge_spec.rb b/modules/stdlib/spec/acceptance/merge_spec.rb new file mode 100755 index 0000000..a60e784 --- /dev/null +++ b/modules/stdlib/spec/acceptance/merge_spec.rb @@ -0,0 +1,23 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'merge function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'should merge two hashes' do + pp = <<-EOS + $a = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } + $b = {'two' => 'dos', 'three' => { 'five' => 5 } } + $o = merge($a, $b) + notice(inline_template('merge[one] is <%= @o["one"].inspect %>')) + notice(inline_template('merge[two] is <%= @o["two"].inspect %>')) + notice(inline_template('merge[three] is <%= @o["three"].inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/merge\[one\] is "1"/) + expect(r.stdout).to match(/merge\[two\] is "dos"/) + expect(r.stdout).to match(/merge\[three\] is {"five"=>"5"}/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/min_spec.rb b/modules/stdlib/spec/acceptance/min_spec.rb new file mode 100755 index 0000000..509092d --- /dev/null +++ b/modules/stdlib/spec/acceptance/min_spec.rb @@ -0,0 +1,20 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'min function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'mins arrays' do + pp = <<-EOS + $o = min("the","public","art","galleries") + notice(inline_template('min is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/min is "art"/) + end + end + end + describe 'failure' do + it 'handles no arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/nodesets/centos-6-vcloud.yml b/modules/stdlib/spec/acceptance/nodesets/centos-6-vcloud.yml new file mode 100644 index 0000000..ca9c1d3 --- /dev/null +++ b/modules/stdlib/spec/acceptance/nodesets/centos-6-vcloud.yml @@ -0,0 +1,15 @@ +HOSTS: + 'centos-6-vcloud': + roles: + - master + platform: el-6-x86_64 + hypervisor: vcloud + template: centos-6-x86_64 +CONFIG: + type: foss + ssh: + keys: "~/.ssh/id_rsa-acceptance" + datastore: instance0 + folder: Delivery/Quality Assurance/Enterprise/Dynamic + resourcepool: delivery/Quality Assurance/Enterprise/Dynamic + pooling_api: http://vcloud.delivery.puppetlabs.net/ diff --git a/modules/stdlib/spec/acceptance/nodesets/centos-64-x64-pe.yml b/modules/stdlib/spec/acceptance/nodesets/centos-64-x64-pe.yml new file mode 100644 index 0000000..7d9242f --- /dev/null +++ b/modules/stdlib/spec/acceptance/nodesets/centos-64-x64-pe.yml @@ -0,0 +1,12 @@ +HOSTS: + centos-64-x64: + roles: + - master + - database + - dashboard + platform: el-6-x86_64 + box : centos-64-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: pe diff --git a/modules/stdlib/spec/acceptance/nodesets/centos-64-x64.yml b/modules/stdlib/spec/acceptance/nodesets/centos-64-x64.yml new file mode 100644 index 0000000..05540ed --- /dev/null +++ b/modules/stdlib/spec/acceptance/nodesets/centos-64-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-64-x64: + roles: + - master + platform: el-6-x86_64 + box : centos-64-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/stdlib/spec/acceptance/nodesets/default.yml b/modules/stdlib/spec/acceptance/nodesets/default.yml new file mode 100644 index 0000000..4e2cb80 --- /dev/null +++ b/modules/stdlib/spec/acceptance/nodesets/default.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-65-x64: + roles: + - master + platform: el-6-x86_64 + box : centos-65-x64-vbox436-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-65-x64-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/stdlib/spec/acceptance/nodesets/fedora-18-x64.yml b/modules/stdlib/spec/acceptance/nodesets/fedora-18-x64.yml new file mode 100644 index 0000000..1361649 --- /dev/null +++ b/modules/stdlib/spec/acceptance/nodesets/fedora-18-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + fedora-18-x64: + roles: + - master + platform: fedora-18-x86_64 + box : fedora-18-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/fedora-18-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/stdlib/spec/acceptance/nodesets/sles-11-x64.yml b/modules/stdlib/spec/acceptance/nodesets/sles-11-x64.yml new file mode 100644 index 0000000..41abe21 --- /dev/null +++ b/modules/stdlib/spec/acceptance/nodesets/sles-11-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + sles-11-x64.local: + roles: + - master + platform: sles-11-x64 + box : sles-11sp1-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/sles-11sp1-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/stdlib/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml b/modules/stdlib/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml new file mode 100644 index 0000000..5ca1514 --- /dev/null +++ b/modules/stdlib/spec/acceptance/nodesets/ubuntu-server-10044-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + ubuntu-server-10044-x64: + roles: + - master + platform: ubuntu-10.04-amd64 + box : ubuntu-server-10044-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-10044-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/stdlib/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml b/modules/stdlib/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml new file mode 100644 index 0000000..d065b30 --- /dev/null +++ b/modules/stdlib/spec/acceptance/nodesets/ubuntu-server-12042-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + ubuntu-server-12042-x64: + roles: + - master + platform: ubuntu-12.04-amd64 + box : ubuntu-server-12042-x64-vbox4210-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-12042-x64-vbox4210-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/modules/stdlib/spec/acceptance/num2bool_spec.rb b/modules/stdlib/spec/acceptance/num2bool_spec.rb new file mode 100755 index 0000000..1d99ba0 --- /dev/null +++ b/modules/stdlib/spec/acceptance/num2bool_spec.rb @@ -0,0 +1,76 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'num2bool function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'bools positive numbers and numeric strings as true' do + pp = <<-EOS + $a = 1 + $b = "1" + $c = "50" + $ao = num2bool($a) + $bo = num2bool($b) + $co = num2bool($c) + notice(inline_template('a is <%= @ao.inspect %>')) + notice(inline_template('b is <%= @bo.inspect %>')) + notice(inline_template('c is <%= @co.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/a is true/) + expect(r.stdout).to match(/b is true/) + expect(r.stdout).to match(/c is true/) + end + end + it 'bools negative numbers as false' do + pp = <<-EOS + $a = 0 + $b = -0.1 + $c = ["-50","1"] + $ao = num2bool($a) + $bo = num2bool($b) + $co = num2bool($c) + notice(inline_template('a is <%= @ao.inspect %>')) + notice(inline_template('b is <%= @bo.inspect %>')) + notice(inline_template('c is <%= @co.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/a is false/) + expect(r.stdout).to match(/b is false/) + expect(r.stdout).to match(/c is false/) + end + end + end + describe 'failure' do + it 'fails on words' do + pp = <<-EOS + $a = "a" + $ao = num2bool($a) + notice(inline_template('a is <%= @ao.inspect %>')) + EOS + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/not look like a number/) + end + + it 'fails on numberwords' do + pp = <<-EOS + $b = "1b" + $bo = num2bool($b) + notice(inline_template('b is <%= @bo.inspect %>')) + EOS + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/not look like a number/) + + end + + it 'fails on non-numeric/strings' do + pending "The function will call .to_s.to_i on anything not a Numeric or + String, and results in 0. Is this intended?" + pp = <<-EOS + $c = {"c" => "-50"} + $co = num2bool($c) + notice(inline_template('c is <%= @co.inspect %>')) + EOS + expect(apply_manifest(ppc :expect_failures => true).stderr).to match(/Unable to parse/) + end + end +end diff --git a/modules/stdlib/spec/acceptance/parsejson_spec.rb b/modules/stdlib/spec/acceptance/parsejson_spec.rb new file mode 100755 index 0000000..5097810 --- /dev/null +++ b/modules/stdlib/spec/acceptance/parsejson_spec.rb @@ -0,0 +1,34 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'parsejson function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'parses valid json' do + pp = <<-EOS + $a = '{"hunter": "washere", "tests": "passing"}' + $ao = parsejson($a) + $tests = $ao['tests'] + notice(inline_template('tests are <%= @tests.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/tests are "passing"/) + end + end + end + describe 'failure' do + it 'raises error on incorrect json' do + pp = <<-EOS + $a = '{"hunter": "washere", "tests": "passing",}' + $ao = parsejson($a) + notice(inline_template('a is <%= @ao.inspect %>')) + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/expected next name/) + end + end + + it 'raises error on incorrect number of arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/parseyaml_spec.rb b/modules/stdlib/spec/acceptance/parseyaml_spec.rb new file mode 100755 index 0000000..5819837 --- /dev/null +++ b/modules/stdlib/spec/acceptance/parseyaml_spec.rb @@ -0,0 +1,35 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'parseyaml function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'parses valid yaml' do + pp = <<-EOS + $a = "---\nhunter: washere\ntests: passing\n" + $o = parseyaml($a) + $tests = $o['tests'] + notice(inline_template('tests are <%= @tests.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/tests are "passing"/) + end + end + end + describe 'failure' do + it 'raises error on incorrect yaml' do + pp = <<-EOS + $a = "---\nhunter: washere\ntests: passing\n:" + $o = parseyaml($a) + $tests = $o['tests'] + notice(inline_template('tests are <%= @tests.inspect %>')) + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/(syntax error|did not find expected key)/) + end + end + + it 'raises error on incorrect number of arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/pick_default_spec.rb b/modules/stdlib/spec/acceptance/pick_default_spec.rb new file mode 100755 index 0000000..a663f54 --- /dev/null +++ b/modules/stdlib/spec/acceptance/pick_default_spec.rb @@ -0,0 +1,54 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'pick_default function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'pick_defaults a default value' do + pp = <<-EOS + $a = undef + $o = pick_default($a, 'default') + notice(inline_template('picked is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/picked is "default"/) + end + end + it 'pick_defaults with no value' do + pp = <<-EOS + $a = undef + $b = undef + $o = pick_default($a,$b) + notice(inline_template('picked is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/picked is ""/) + end + end + it 'pick_defaults the first set value' do + pp = <<-EOS + $a = "something" + $b = "long" + $o = pick_default($a, $b, 'default') + notice(inline_template('picked is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/picked is "something"/) + end + end + end + describe 'failure' do + it 'raises error with no values' do + pp = <<-EOS + $o = pick_default() + notice(inline_template('picked is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/Must receive at least one argument/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/pick_spec.rb b/modules/stdlib/spec/acceptance/pick_spec.rb new file mode 100755 index 0000000..46cf63f --- /dev/null +++ b/modules/stdlib/spec/acceptance/pick_spec.rb @@ -0,0 +1,44 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'pick function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'picks a default value' do + pp = <<-EOS + $a = undef + $o = pick($a, 'default') + notice(inline_template('picked is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/picked is "default"/) + end + end + it 'picks the first set value' do + pp = <<-EOS + $a = "something" + $b = "long" + $o = pick($a, $b, 'default') + notice(inline_template('picked is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/picked is "something"/) + end + end + end + describe 'failure' do + it 'raises error with all undef values' do + pp = <<-EOS + $a = undef + $b = undef + $o = pick($a, $b) + notice(inline_template('picked is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :expect_failures => true) do |r| + expect(r.stderr).to match(/must receive at least one non empty value/) + end + end + end +end diff --git a/modules/stdlib/spec/acceptance/prefix_spec.rb b/modules/stdlib/spec/acceptance/prefix_spec.rb new file mode 100755 index 0000000..de55530 --- /dev/null +++ b/modules/stdlib/spec/acceptance/prefix_spec.rb @@ -0,0 +1,42 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'prefix function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'prefixes array of values' do + pp = <<-EOS + $o = prefix(['a','b','c'],'p') + notice(inline_template('prefix is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/prefix is \["pa", "pb", "pc"\]/) + end + end + it 'prefixs with empty array' do + pp = <<-EOS + $o = prefix([],'p') + notice(inline_template('prefix is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/prefix is \[\]/) + end + end + it 'prefixs array of values with undef' do + pp = <<-EOS + $o = prefix(['a','b','c'], undef) + notice(inline_template('prefix is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/prefix is \["a", "b", "c"\]/) + end + end + end + describe 'failure' do + it 'fails with no arguments' + it 'fails when first argument is not array' + it 'fails when second argument is not string' + end +end diff --git a/modules/stdlib/spec/acceptance/range_spec.rb b/modules/stdlib/spec/acceptance/range_spec.rb new file mode 100755 index 0000000..a3ccd33 --- /dev/null +++ b/modules/stdlib/spec/acceptance/range_spec.rb @@ -0,0 +1,36 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'range function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'ranges letters' do + pp = <<-EOS + $o = range('a','d') + notice(inline_template('range is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/range is \["a", "b", "c", "d"\]/) + end + end + it 'ranges letters with a step' do + pp = <<-EOS + $o = range('a','d', '2') + notice(inline_template('range is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/range is \["a", "c"\]/) + end + end + it 'ranges letters with a negative step' + it 'ranges numbers' + it 'ranges numbers with a step' + it 'ranges numbers with a negative step' + it 'ranges numeric strings' + it 'ranges zero padded numbers' + end + describe 'failure' do + it 'fails with no arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/reject_spec.rb b/modules/stdlib/spec/acceptance/reject_spec.rb new file mode 100755 index 0000000..7f16a00 --- /dev/null +++ b/modules/stdlib/spec/acceptance/reject_spec.rb @@ -0,0 +1,42 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'reject function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'rejects array of values' do + pp = <<-EOS + $o = reject(['aaa','bbb','ccc','aaaddd'], 'aaa') + notice(inline_template('reject is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/reject is \["bbb", "ccc"\]/) + end + end + it 'rejects with empty array' do + pp = <<-EOS + $o = reject([],'aaa') + notice(inline_template('reject is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/reject is \[\]/) + end + end + it 'rejects array of values with undef' do + pp = <<-EOS + $o = reject(['aaa','bbb','ccc','aaaddd'], undef) + notice(inline_template('reject is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/reject is \[\]/) + end + end + end + describe 'failure' do + it 'fails with no arguments' + it 'fails when first argument is not array' + it 'fails when second argument is not string' + end +end diff --git a/modules/stdlib/spec/acceptance/reverse_spec.rb b/modules/stdlib/spec/acceptance/reverse_spec.rb new file mode 100755 index 0000000..c3f0156 --- /dev/null +++ b/modules/stdlib/spec/acceptance/reverse_spec.rb @@ -0,0 +1,23 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'reverse function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'reverses strings' do + pp = <<-EOS + $a = "the public art galleries" + # Anagram: Large picture halls, I bet + $o = reverse($a) + notice(inline_template('reverse is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/reverse is "seirellag tra cilbup eht"/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings or arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/rstrip_spec.rb b/modules/stdlib/spec/acceptance/rstrip_spec.rb new file mode 100755 index 0000000..b57a8b0 --- /dev/null +++ b/modules/stdlib/spec/acceptance/rstrip_spec.rb @@ -0,0 +1,34 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'rstrip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'rstrips arrays' do + pp = <<-EOS + $a = [" the "," public "," art","galleries "] + # Anagram: Large picture halls, I bet + $o = rstrip($a) + notice(inline_template('rstrip is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/rstrip is \[" the", " public", " art", "galleries"\]/) + end + end + it 'rstrips strings' do + pp = <<-EOS + $a = " blowzy night-frumps vex'd jack q " + $o = rstrip($a) + notice(inline_template('rstrip is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/rstrip is " blowzy night-frumps vex'd jack q"/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings or arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/shuffle_spec.rb b/modules/stdlib/spec/acceptance/shuffle_spec.rb new file mode 100755 index 0000000..b840d1f --- /dev/null +++ b/modules/stdlib/spec/acceptance/shuffle_spec.rb @@ -0,0 +1,34 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'shuffle function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'shuffles arrays' do + pp = <<-EOS + $a = ["1", "2", "3", "4", "5", "6", "7", "8", "the","public","art","galleries"] + # Anagram: Large picture halls, I bet + $o = shuffle($a) + notice(inline_template('shuffle is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to_not match(/shuffle is \["1", "2", "3", "4", "5", "6", "7", "8", "the", "public", "art", "galleries"\]/) + end + end + it 'shuffles strings' do + pp = <<-EOS + $a = "blowzy night-frumps vex'd jack q" + $o = shuffle($a) + notice(inline_template('shuffle is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to_not match(/shuffle is "blowzy night-frumps vex'd jack q"/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings or arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/size_spec.rb b/modules/stdlib/spec/acceptance/size_spec.rb new file mode 100755 index 0000000..a52b778 --- /dev/null +++ b/modules/stdlib/spec/acceptance/size_spec.rb @@ -0,0 +1,55 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'size function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'single string size' do + pp = <<-EOS + $a = 'discombobulate' + $o = size($a) + notice(inline_template('size is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/size is 14/) + end + end + it 'with empty string' do + pp = <<-EOS + $a = '' + $o = size($a) + notice(inline_template('size is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/size is 0/) + end + end + it 'with undef' do + pp = <<-EOS + $a = undef + $o = size($a) + notice(inline_template('size is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/size is 0/) + end + end + it 'strings in array' do + pp = <<-EOS + $a = ['discombobulate', 'moo'] + $o = size($a) + notice(inline_template('size is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/size is 2/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings or arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/sort_spec.rb b/modules/stdlib/spec/acceptance/sort_spec.rb new file mode 100755 index 0000000..c85bfab --- /dev/null +++ b/modules/stdlib/spec/acceptance/sort_spec.rb @@ -0,0 +1,34 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'sort function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'sorts arrays' do + pp = <<-EOS + $a = ["the","public","art","galleries"] + # Anagram: Large picture halls, I bet + $o = sort($a) + notice(inline_template('sort is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/sort is \["art", "galleries", "public", "the"\]/) + end + end + it 'sorts strings' do + pp = <<-EOS + $a = "blowzy night-frumps vex'd jack q" + $o = sort($a) + notice(inline_template('sort is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/sort is " '-abcdefghijklmnopqrstuvwxyz"/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings or arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/squeeze_spec.rb b/modules/stdlib/spec/acceptance/squeeze_spec.rb new file mode 100755 index 0000000..400a458 --- /dev/null +++ b/modules/stdlib/spec/acceptance/squeeze_spec.rb @@ -0,0 +1,47 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'squeeze function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'squeezes arrays' do + pp = <<-EOS + # Real words! + $a = ["wallless", "laparohysterosalpingooophorectomy", "brrr", "goddessship"] + $o = squeeze($a) + notice(inline_template('squeeze is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/squeeze is \["wales", "laparohysterosalpingophorectomy", "br", "godeship"\]/) + end + end + it 'squeezez arrays with an argument' + it 'squeezes strings' do + pp = <<-EOS + $a = "wallless laparohysterosalpingooophorectomy brrr goddessship" + $o = squeeze($a) + notice(inline_template('squeeze is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/squeeze is "wales laparohysterosalpingophorectomy br godeship"/) + end + end + + it 'squeezes strings with an argument' do + pp = <<-EOS + $a = "countessship duchessship governessship hostessship" + $o = squeeze($a, 's') + notice(inline_template('squeeze is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/squeeze is "counteship ducheship governeship hosteship"/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings or arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/str2bool_spec.rb b/modules/stdlib/spec/acceptance/str2bool_spec.rb new file mode 100755 index 0000000..cf549da --- /dev/null +++ b/modules/stdlib/spec/acceptance/str2bool_spec.rb @@ -0,0 +1,31 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'str2bool function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'works with "y"' do + pp = <<-EOS + $o = str2bool('y') + notice(inline_template('str2bool is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/str2bool is true/) + end + end + it 'works with "Y"' + it 'works with "yes"' + it 'works with "1"' + it 'works with "true"' + it 'works with "n"' + it 'works with "N"' + it 'works with "no"' + it 'works with "0"' + it 'works with "false"' + it 'works with undef' + end + describe 'failure' do + it 'handles no arguments' + it 'handles non arrays or strings' + end +end diff --git a/modules/stdlib/spec/acceptance/str2saltedsha512_spec.rb b/modules/stdlib/spec/acceptance/str2saltedsha512_spec.rb new file mode 100755 index 0000000..993e63b --- /dev/null +++ b/modules/stdlib/spec/acceptance/str2saltedsha512_spec.rb @@ -0,0 +1,22 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'str2saltedsha512 function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'works with "y"' do + pp = <<-EOS + $o = str2saltedsha512('password') + notice(inline_template('str2saltedsha512 is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/str2saltedsha512 is "[a-f0-9]{136}"/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles more than one argument' + it 'handles non strings' + end +end diff --git a/modules/stdlib/spec/acceptance/strftime_spec.rb b/modules/stdlib/spec/acceptance/strftime_spec.rb new file mode 100755 index 0000000..53b7f90 --- /dev/null +++ b/modules/stdlib/spec/acceptance/strftime_spec.rb @@ -0,0 +1,22 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'strftime function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'gives the Century' do + pp = <<-EOS + $o = strftime('%C') + notice(inline_template('strftime is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/strftime is "20"/) + end + end + it 'takes a timezone argument' + end + describe 'failure' do + it 'handles no arguments' + it 'handles invalid format strings' + end +end diff --git a/modules/stdlib/spec/acceptance/strip_spec.rb b/modules/stdlib/spec/acceptance/strip_spec.rb new file mode 100755 index 0000000..906fd7a --- /dev/null +++ b/modules/stdlib/spec/acceptance/strip_spec.rb @@ -0,0 +1,34 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'strip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'strips arrays' do + pp = <<-EOS + $a = [" the "," public "," art","galleries "] + # Anagram: Large picture halls, I bet + $o = strip($a) + notice(inline_template('strip is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/strip is \["the", "public", "art", "galleries"\]/) + end + end + it 'strips strings' do + pp = <<-EOS + $a = " blowzy night-frumps vex'd jack q " + $o = strip($a) + notice(inline_template('strip is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/strip is "blowzy night-frumps vex'd jack q"/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings or arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/suffix_spec.rb b/modules/stdlib/spec/acceptance/suffix_spec.rb new file mode 100755 index 0000000..630f866 --- /dev/null +++ b/modules/stdlib/spec/acceptance/suffix_spec.rb @@ -0,0 +1,42 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'suffix function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'suffixes array of values' do + pp = <<-EOS + $o = suffix(['a','b','c'],'p') + notice(inline_template('suffix is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/suffix is \["ap", "bp", "cp"\]/) + end + end + it 'suffixs with empty array' do + pp = <<-EOS + $o = suffix([],'p') + notice(inline_template('suffix is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/suffix is \[\]/) + end + end + it 'suffixs array of values with undef' do + pp = <<-EOS + $o = suffix(['a','b','c'], undef) + notice(inline_template('suffix is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/suffix is \["a", "b", "c"\]/) + end + end + end + describe 'failure' do + it 'fails with no arguments' + it 'fails when first argument is not array' + it 'fails when second argument is not string' + end +end diff --git a/modules/stdlib/spec/acceptance/swapcase_spec.rb b/modules/stdlib/spec/acceptance/swapcase_spec.rb new file mode 100755 index 0000000..b7894fb --- /dev/null +++ b/modules/stdlib/spec/acceptance/swapcase_spec.rb @@ -0,0 +1,22 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'swapcase function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'works with strings' do + pp = <<-EOS + $o = swapcase('aBcD') + notice(inline_template('swapcase is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/swapcase is "AbCd"/) + end + end + it 'works with arrays' + end + describe 'failure' do + it 'handles no arguments' + it 'handles non arrays or strings' + end +end diff --git a/modules/stdlib/spec/acceptance/time_spec.rb b/modules/stdlib/spec/acceptance/time_spec.rb new file mode 100755 index 0000000..cdb2960 --- /dev/null +++ b/modules/stdlib/spec/acceptance/time_spec.rb @@ -0,0 +1,36 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'time function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'gives the time' do + pp = <<-EOS + $o = time() + notice(inline_template('time is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + m = r.stdout.match(/time is (\d+)\D/) + + # When I wrote this test + expect(Integer(m[1])).to be > 1398894170 + end + end + it 'takes a timezone argument' do + pp = <<-EOS + $o = time('UTC') + notice(inline_template('time is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + m = r.stdout.match(/time is (\d+)\D/) + + expect(Integer(m[1])).to be > 1398894170 + end + end + end + describe 'failure' do + it 'handles more arguments' + it 'handles invalid timezones' + end +end diff --git a/modules/stdlib/spec/acceptance/to_bytes_spec.rb b/modules/stdlib/spec/acceptance/to_bytes_spec.rb new file mode 100755 index 0000000..2b4c61f --- /dev/null +++ b/modules/stdlib/spec/acceptance/to_bytes_spec.rb @@ -0,0 +1,27 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'to_bytes function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'converts kB to B' do + pp = <<-EOS + $o = to_bytes('4 kB') + notice(inline_template('to_bytes is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + m = r.stdout.match(/to_bytes is (\d+)\D/) + expect(m[1]).to eq("4096") + end + end + it 'works without the B in unit' + it 'works without a space before unit' + it 'works without a unit' + it 'converts fractions' + end + describe 'failure' do + it 'handles no arguments' + it 'handles non integer arguments' + it 'handles unknown units like uB' + end +end diff --git a/modules/stdlib/spec/acceptance/type_spec.rb b/modules/stdlib/spec/acceptance/type_spec.rb new file mode 100755 index 0000000..0043aad --- /dev/null +++ b/modules/stdlib/spec/acceptance/type_spec.rb @@ -0,0 +1,37 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'type function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'types arrays' do + pp = <<-EOS + $a = ["the","public","art","galleries"] + # Anagram: Large picture halls, I bet + $o = type($a) + notice(inline_template('type is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/type is "array"/) + end + end + it 'types strings' do + pp = <<-EOS + $a = "blowzy night-frumps vex'd jack q" + $o = type($a) + notice(inline_template('type is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/type is "string"/) + end + end + it 'types hashes' + it 'types integers' + it 'types floats' + it 'types booleans' + end + describe 'failure' do + it 'handles no arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/union_spec.rb b/modules/stdlib/spec/acceptance/union_spec.rb new file mode 100755 index 0000000..6db8d0c --- /dev/null +++ b/modules/stdlib/spec/acceptance/union_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'union function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'unions arrays' do + pp = <<-EOS + $a = ["the","public"] + $b = ["art","galleries"] + # Anagram: Large picture halls, I bet + $o = union($a,$b) + notice(inline_template('union is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/union is \["the", "public", "art", "galleries"\]/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/unique_spec.rb b/modules/stdlib/spec/acceptance/unique_spec.rb new file mode 100755 index 0000000..bfadad1 --- /dev/null +++ b/modules/stdlib/spec/acceptance/unique_spec.rb @@ -0,0 +1,33 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'unique function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'uniques arrays' do + pp = <<-EOS + $a = ["wallless", "wallless", "brrr", "goddessship"] + $o = unique($a) + notice(inline_template('unique is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/unique is \["wallless", "brrr", "goddessship"\]/) + end + end + it 'uniques strings' do + pp = <<-EOS + $a = "wallless laparohysterosalpingooophorectomy brrr goddessship" + $o = unique($a) + notice(inline_template('unique is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/unique is "wales prohytingcmbd"/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings or arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/unsupported_spec.rb b/modules/stdlib/spec/acceptance/unsupported_spec.rb new file mode 100755 index 0000000..1c559f6 --- /dev/null +++ b/modules/stdlib/spec/acceptance/unsupported_spec.rb @@ -0,0 +1,11 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'unsupported distributions and OSes', :if => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + it 'should fail' do + pp = <<-EOS + class { 'mysql::server': } + EOS + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/unsupported osfamily/i) + end +end diff --git a/modules/stdlib/spec/acceptance/upcase_spec.rb b/modules/stdlib/spec/acceptance/upcase_spec.rb new file mode 100755 index 0000000..3d2906d --- /dev/null +++ b/modules/stdlib/spec/acceptance/upcase_spec.rb @@ -0,0 +1,33 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'upcase function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'upcases arrays' do + pp = <<-EOS + $a = ["wallless", "laparohysterosalpingooophorectomy", "brrr", "goddessship"] + $o = upcase($a) + notice(inline_template('upcase is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/upcase is \["WALLLESS", "LAPAROHYSTEROSALPINGOOOPHORECTOMY", "BRRR", "GODDESSSHIP"\]/) + end + end + it 'upcases strings' do + pp = <<-EOS + $a = "wallless laparohysterosalpingooophorectomy brrr goddessship" + $o = upcase($a) + notice(inline_template('upcase is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/upcase is "WALLLESS LAPAROHYSTEROSALPINGOOOPHORECTOMY BRRR GODDESSSHIP"/) + end + end + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings or arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/uriescape_spec.rb b/modules/stdlib/spec/acceptance/uriescape_spec.rb new file mode 100755 index 0000000..7e30205 --- /dev/null +++ b/modules/stdlib/spec/acceptance/uriescape_spec.rb @@ -0,0 +1,23 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'uriescape function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'uriescape strings' do + pp = <<-EOS + $a = ":/?#[]@!$&'()*+,;= \\\"{}" + $o = uriescape($a) + notice(inline_template('uriescape is <%= @o.inspect %>')) + EOS + + apply_manifest(pp, :catch_failures => true) do |r| + expect(r.stdout).to match(/uriescape is ":\/\?%23\[\]@!\$&'\(\)\*\+,;=%20%22%7B%7D"/) + end + end + it 'does nothing if a string is already safe' + end + describe 'failure' do + it 'handles no arguments' + it 'handles non strings or arrays' + end +end diff --git a/modules/stdlib/spec/acceptance/validate_absolute_path_spec.rb b/modules/stdlib/spec/acceptance/validate_absolute_path_spec.rb new file mode 100755 index 0000000..7082e84 --- /dev/null +++ b/modules/stdlib/spec/acceptance/validate_absolute_path_spec.rb @@ -0,0 +1,31 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'validate_absolute_path function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + %w{ + C:/ + C:\\\\ + C:\\\\WINDOWS\\\\System32 + C:/windows/system32 + X:/foo/bar + X:\\\\foo\\\\bar + /var/tmp + /var/lib/puppet + /var/opt/../lib/puppet + }.each do |path| + it "validates a single argument #{path}" do + pp = <<-EOS + $one = '#{path}' + validate_absolute_path($one) + EOS + + apply_manifest(pp, :catch_failures => true) + end + end + end + describe 'failure' do + it 'handles improper number of arguments' + it 'handles relative paths' + end +end diff --git a/modules/stdlib/spec/acceptance/validate_array_spec.rb b/modules/stdlib/spec/acceptance/validate_array_spec.rb new file mode 100755 index 0000000..b53e98c --- /dev/null +++ b/modules/stdlib/spec/acceptance/validate_array_spec.rb @@ -0,0 +1,37 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'validate_array function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'validates a single argument' do + pp = <<-EOS + $one = ['a', 'b'] + validate_array($one) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates an multiple arguments' do + pp = <<-EOS + $one = ['a', 'b'] + $two = [['c'], 'd'] + validate_array($one,$two) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates a non-array' do + { + %{validate_array({'a' => 'hash' })} => "Hash", + %{validate_array('string')} => "String", + %{validate_array(false)} => "FalseClass", + %{validate_array(undef)} => "String" + }.each do |pp,type| + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/a #{type}/) + end + end + end + describe 'failure' do + it 'handles improper number of arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/validate_augeas_spec.rb b/modules/stdlib/spec/acceptance/validate_augeas_spec.rb new file mode 100755 index 0000000..aeec67a --- /dev/null +++ b/modules/stdlib/spec/acceptance/validate_augeas_spec.rb @@ -0,0 +1,63 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'validate_augeas function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'prep' do + it 'installs augeas for tests' + end + describe 'success' do + context 'valid inputs with no 3rd argument' do + { + 'root:x:0:0:root:/root:/bin/bash\n' => 'Passwd.lns', + 'proc /proc proc nodev,noexec,nosuid 0 0\n' => 'Fstab.lns' + }.each do |line,lens| + it "validates a single argument for #{lens}" do + pp = <<-EOS + $line = "#{line}" + $lens = "#{lens}" + validate_augeas($line, $lens) + EOS + + apply_manifest(pp, :catch_failures => true) + end + end + end + context 'valid inputs with 3rd and 4th arguments' do + it "validates a restricted value" do + line = 'root:x:0:0:root:/root:/bin/barsh\n' + lens = 'Passwd.lns' + restriction = '$file/*[shell="/bin/barsh"]' + pp = <<-EOS + $line = "#{line}" + $lens = "#{lens}" + $restriction = ['#{restriction}'] + validate_augeas($line, $lens, $restriction, "my custom failure message") + EOS + + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/my custom failure message/) + end + end + context 'invalid inputs' do + { + 'root:x:0:0:root' => 'Passwd.lns', + '127.0.1.1' => 'Hosts.lns' + }.each do |line,lens| + it "validates a single argument for #{lens}" do + pp = <<-EOS + $line = "#{line}" + $lens = "#{lens}" + validate_augeas($line, $lens) + EOS + + apply_manifest(pp, :expect_failures => true) + end + end + end + context 'garbage inputs' do + it 'raises an error on invalid inputs' + end + end + describe 'failure' do + it 'handles improper number of arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/validate_bool_spec.rb b/modules/stdlib/spec/acceptance/validate_bool_spec.rb new file mode 100755 index 0000000..c837f08 --- /dev/null +++ b/modules/stdlib/spec/acceptance/validate_bool_spec.rb @@ -0,0 +1,37 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'validate_bool function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'validates a single argument' do + pp = <<-EOS + $one = true + validate_bool($one) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates an multiple arguments' do + pp = <<-EOS + $one = true + $two = false + validate_bool($one,$two) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates a non-bool' do + { + %{validate_bool('true')} => "String", + %{validate_bool('false')} => "String", + %{validate_bool([true])} => "Array", + %{validate_bool(undef)} => "String", + }.each do |pp,type| + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/a #{type}/) + end + end + end + describe 'failure' do + it 'handles improper number of arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/validate_cmd_spec.rb b/modules/stdlib/spec/acceptance/validate_cmd_spec.rb new file mode 100755 index 0000000..385676d --- /dev/null +++ b/modules/stdlib/spec/acceptance/validate_cmd_spec.rb @@ -0,0 +1,50 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'validate_cmd function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'validates a true command' do + pp = <<-EOS + $one = 'foo' + if $::osfamily == 'windows' { + $two = 'echo' #shell built-in + } else { + $two = '/bin/echo' + } + validate_cmd($one,$two) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates a fail command' do + pp = <<-EOS + $one = 'foo' + if $::osfamily == 'windows' { + $two = 'C:/aoeu' + } else { + $two = '/bin/aoeu' + } + validate_cmd($one,$two) + EOS + + apply_manifest(pp, :expect_failures => true) + end + it 'validates a fail command with a custom error message' do + pp = <<-EOS + $one = 'foo' + if $::osfamily == 'windows' { + $two = 'C:/aoeu' + } else { + $two = '/bin/aoeu' + } + validate_cmd($one,$two,"aoeu is dvorak) + EOS + + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/aoeu is dvorak/) + end + end + describe 'failure' do + it 'handles improper number of arguments' + it 'handles improper argument types' + end +end diff --git a/modules/stdlib/spec/acceptance/validate_hash_spec.rb b/modules/stdlib/spec/acceptance/validate_hash_spec.rb new file mode 100755 index 0000000..52fb615 --- /dev/null +++ b/modules/stdlib/spec/acceptance/validate_hash_spec.rb @@ -0,0 +1,37 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'validate_hash function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'validates a single argument' do + pp = <<-EOS + $one = { 'a' => 1 } + validate_hash($one) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates an multiple arguments' do + pp = <<-EOS + $one = { 'a' => 1 } + $two = { 'b' => 2 } + validate_hash($one,$two) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates a non-hash' do + { + %{validate_hash('{ "not" => "hash" }')} => "String", + %{validate_hash('string')} => "String", + %{validate_hash(["array"])} => "Array", + %{validate_hash(undef)} => "String", + }.each do |pp,type| + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/a #{type}/) + end + end + end + describe 'failure' do + it 'handles improper number of arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/validate_ipv4_address_spec.rb b/modules/stdlib/spec/acceptance/validate_ipv4_address_spec.rb new file mode 100755 index 0000000..64841c3 --- /dev/null +++ b/modules/stdlib/spec/acceptance/validate_ipv4_address_spec.rb @@ -0,0 +1,31 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'validate_ipv4_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'validates a single argument' do + pp = <<-EOS + $one = '1.2.3.4' + validate_ipv4_address($one) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates an multiple arguments' do + pp = <<-EOS + $one = '1.2.3.4' + $two = '5.6.7.8' + validate_ipv4_address($one,$two) + EOS + + apply_manifest(pp, :catch_failures => true) + end + end + describe 'failure' do + it 'handles improper number of arguments' + it 'handles ipv6 addresses' + it 'handles non-ipv4 strings' + it 'handles numbers' + it 'handles no arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/validate_ipv6_address_spec.rb b/modules/stdlib/spec/acceptance/validate_ipv6_address_spec.rb new file mode 100755 index 0000000..6426d1a --- /dev/null +++ b/modules/stdlib/spec/acceptance/validate_ipv6_address_spec.rb @@ -0,0 +1,31 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'validate_ipv6_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'validates a single argument' do + pp = <<-EOS + $one = '3ffe:0505:0002::' + validate_ipv6_address($one) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates an multiple arguments' do + pp = <<-EOS + $one = '3ffe:0505:0002::' + $two = '3ffe:0505:0001::' + validate_ipv6_address($one,$two) + EOS + + apply_manifest(pp, :catch_failures => true) + end + end + describe 'failure' do + it 'handles improper number of arguments' + it 'handles ipv6 addresses' + it 'handles non-ipv6 strings' + it 'handles numbers' + it 'handles no arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/validate_re_spec.rb b/modules/stdlib/spec/acceptance/validate_re_spec.rb new file mode 100755 index 0000000..22f6d47 --- /dev/null +++ b/modules/stdlib/spec/acceptance/validate_re_spec.rb @@ -0,0 +1,47 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'validate_re function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'validates a string' do + pp = <<-EOS + $one = 'one' + $two = '^one$' + validate_re($one,$two) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates an array' do + pp = <<-EOS + $one = 'one' + $two = ['^one$', '^two'] + validate_re($one,$two) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates a failed array' do + pp = <<-EOS + $one = 'one' + $two = ['^two$', '^three'] + validate_re($one,$two) + EOS + + apply_manifest(pp, :expect_failures => true) + end + it 'validates a failed array with a custom error message' do + pp = <<-EOS + $one = '3.4.3' + $two = '^2.7' + validate_re($one,$two,"The $puppetversion fact does not match 2.7") + EOS + + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/does not match/) + end + end + describe 'failure' do + it 'handles improper number of arguments' + it 'handles improper argument types' + end +end diff --git a/modules/stdlib/spec/acceptance/validate_slength_spec.rb b/modules/stdlib/spec/acceptance/validate_slength_spec.rb new file mode 100755 index 0000000..1ab2bb9 --- /dev/null +++ b/modules/stdlib/spec/acceptance/validate_slength_spec.rb @@ -0,0 +1,72 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'validate_slength function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'validates a single string max' do + pp = <<-EOS + $one = 'discombobulate' + $two = 17 + validate_slength($one,$two) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates multiple string maxes' do + pp = <<-EOS + $one = ['discombobulate', 'moo'] + $two = 17 + validate_slength($one,$two) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates min/max of strings in array' do + pp = <<-EOS + $one = ['discombobulate', 'moo'] + $two = 17 + $three = 3 + validate_slength($one,$two,$three) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates a single string max of incorrect length' do + pp = <<-EOS + $one = 'discombobulate' + $two = 1 + validate_slength($one,$two) + EOS + + apply_manifest(pp, :expect_failures => true) + end + it 'validates multiple string maxes of incorrect length' do + pp = <<-EOS + $one = ['discombobulate', 'moo'] + $two = 3 + validate_slength($one,$two) + EOS + + apply_manifest(pp, :expect_failures => true) + end + it 'validates multiple strings min/maxes of incorrect length' do + pp = <<-EOS + $one = ['discombobulate', 'moo'] + $two = 17 + $three = 10 + validate_slength($one,$two,$three) + EOS + + apply_manifest(pp, :expect_failures => true) + end + end + describe 'failure' do + it 'handles improper number of arguments' + it 'handles improper first argument type' + it 'handles non-strings in array of first argument' + it 'handles improper second argument type' + it 'handles improper third argument type' + it 'handles negative ranges' + it 'handles improper ranges' + end +end diff --git a/modules/stdlib/spec/acceptance/validate_string_spec.rb b/modules/stdlib/spec/acceptance/validate_string_spec.rb new file mode 100755 index 0000000..8956f48 --- /dev/null +++ b/modules/stdlib/spec/acceptance/validate_string_spec.rb @@ -0,0 +1,36 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'validate_string function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'validates a single argument' do + pp = <<-EOS + $one = 'string' + validate_string($one) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates an multiple arguments' do + pp = <<-EOS + $one = 'string' + $two = 'also string' + validate_string($one,$two) + EOS + + apply_manifest(pp, :catch_failures => true) + end + it 'validates a non-string' do + { + %{validate_string({ 'a' => 'hash' })} => "Hash", + %{validate_string(['array'])} => "Array", + %{validate_string(false)} => "FalseClass", + }.each do |pp,type| + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/a #{type}/) + end + end + end + describe 'failure' do + it 'handles improper number of arguments' + end +end diff --git a/modules/stdlib/spec/acceptance/values_at_spec.rb b/modules/stdlib/spec/acceptance/values_at_spec.rb new file mode 100755 index 0000000..da63cf3 --- /dev/null +++ b/modules/stdlib/spec/acceptance/values_at_spec.rb @@ -0,0 +1,73 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'values_at function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'returns a specific value' do + pp = <<-EOS + $one = ['a','b','c','d','e'] + $two = 1 + $output = values_at($one,$two) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["b"\]/) + end + it 'returns a specific negative index value' do + pending("negative numbers don't work") + pp = <<-EOS + $one = ['a','b','c','d','e'] + $two = -1 + $output = values_at($one,$two) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["e"\]/) + end + it 'returns a range of values' do + pp = <<-EOS + $one = ['a','b','c','d','e'] + $two = "1-3" + $output = values_at($one,$two) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["b", "c", "d"\]/) + end + it 'returns a negative specific value and range of values' do + pp = <<-EOS + $one = ['a','b','c','d','e'] + $two = ["1-3",0] + $output = values_at($one,$two) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["b", "c", "d", "a"\]/) + end + end + describe 'failure' do + it 'handles improper number of arguments' do + pp = <<-EOS + $one = ['a','b','c','d','e'] + $output = values_at($one) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/Wrong number of arguments/) + end + it 'handles non-indicies arguments' do + pp = <<-EOS + $one = ['a','b','c','d','e'] + $two = [] + $output = values_at($one,$two) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/at least one positive index/) + end + + it 'detects index ranges smaller than the start range' + it 'handles index ranges larger than array' + it 'handles non-integer indicies' + end +end diff --git a/modules/stdlib/spec/acceptance/values_spec.rb b/modules/stdlib/spec/acceptance/values_spec.rb new file mode 100755 index 0000000..7ef956e --- /dev/null +++ b/modules/stdlib/spec/acceptance/values_spec.rb @@ -0,0 +1,31 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' + +describe 'values function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'returns an array of values' do + pp = <<-EOS + $arg = { + 'a' => 1, + 'b' => 2, + 'c' => 3, + } + $output = values($arg) + notice(inline_template('<%= @output.sort.inspect %>')) + EOS + + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["1", "2", "3"\]/) + end + end + describe 'failure' do + it 'handles non-hash arguments' do + pp = <<-EOS + $arg = "foo" + $output = values($arg) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/Requires hash/) + end + end +end diff --git a/modules/stdlib/spec/acceptance/zip_spec.rb b/modules/stdlib/spec/acceptance/zip_spec.rb new file mode 100755 index 0000000..0e924e8 --- /dev/null +++ b/modules/stdlib/spec/acceptance/zip_spec.rb @@ -0,0 +1,74 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper_acceptance' +require 'puppet' + +describe 'zip function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do + describe 'success' do + it 'zips two arrays of numbers together' do + pp = <<-EOS + $one = [1,2,3,4] + $two = [5,6,7,8] + $output = zip($one,$two) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\["1", "5"\], \["2", "6"\], \["3", "7"\], \["4", "8"\]\]/) + end + it 'zips two arrays of numbers & bools together' do + pp = <<-EOS + $one = [1,2,"three",4] + $two = [true,true,false,false] + $output = zip($one,$two) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\["1", true\], \["2", true\], \["three", false\], \["4", false\]\]/) + end + it 'zips two arrays of numbers together and flattens them' do + # XXX This only tests the argument `true`, even though the following are valid: + # 1 t y true yes + # 0 f n false no + # undef undefined + pp = <<-EOS + $one = [1,2,3,4] + $two = [5,6,7,8] + $output = zip($one,$two,true) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["1", "5", "2", "6", "3", "7", "4", "8"\]/) + end + it 'handles unmatched length' do + # XXX Is this expected behavior? + pp = <<-EOS + $one = [1,2] + $two = [5,6,7,8] + $output = zip($one,$two) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\["1", "5"\], \["2", "6"\]\]/) + end + end + describe 'failure' do + it 'handles improper number of arguments' do + pp = <<-EOS + $one = [1,2] + $output = zip($one) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/Wrong number of arguments/) + end + it 'handles improper argument types' do + pp = <<-EOS + $one = "a string" + $two = [5,6,7,8] + $output = zip($one,$two) + notice(inline_template('<%= @output.inspect %>')) + EOS + + expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/Requires array/) + end + end +end diff --git a/modules/stdlib/spec/classes/anchor_spec.rb b/modules/stdlib/spec/classes/anchor_spec.rb new file mode 100755 index 0000000..2d4455e --- /dev/null +++ b/modules/stdlib/spec/classes/anchor_spec.rb @@ -0,0 +1,30 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' +require 'puppet_spec/compiler' + +describe "anchorrefresh" do + include PuppetSpec::Compiler + + let :transaction do + apply_compiled_manifest(<<-ANCHORCLASS) + class anchored { + anchor { 'anchored::begin': } + ~> anchor { 'anchored::end': } + } + + class anchorrefresh { + notify { 'first': } + ~> class { 'anchored': } + ~> anchor { 'final': } + } + + include anchorrefresh + ANCHORCLASS + end + + it 'propagates events through the anchored class' do + resource = transaction.resource_status('Anchor[final]') + + expect(resource.restarted).to eq(true) + end +end diff --git a/modules/stdlib/spec/fixtures/dscacheutil/root b/modules/stdlib/spec/fixtures/dscacheutil/root new file mode 100644 index 0000000..1e34519 --- /dev/null +++ b/modules/stdlib/spec/fixtures/dscacheutil/root @@ -0,0 +1,8 @@ +name: root +password: * +uid: 0 +gid: 0 +dir: /var/root +shell: /bin/bash +gecos: rawr Root + diff --git a/modules/stdlib/spec/fixtures/manifests/site.pp b/modules/stdlib/spec/fixtures/manifests/site.pp new file mode 100644 index 0000000..e69de29 diff --git a/modules/stdlib/spec/functions/abs_spec.rb b/modules/stdlib/spec/functions/abs_spec.rb new file mode 100755 index 0000000..c0b4297 --- /dev/null +++ b/modules/stdlib/spec/functions/abs_spec.rb @@ -0,0 +1,25 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe "the abs function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("abs").should == "function_abs" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_abs([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should convert a negative number into a positive" do + result = scope.function_abs(["-34"]) + result.should(eq(34)) + end + + it "should do nothing with a positive number" do + result = scope.function_abs(["5678"]) + result.should(eq(5678)) + end +end diff --git a/modules/stdlib/spec/functions/any2array_spec.rb b/modules/stdlib/spec/functions/any2array_spec.rb new file mode 100755 index 0000000..b266e84 --- /dev/null +++ b/modules/stdlib/spec/functions/any2array_spec.rb @@ -0,0 +1,55 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the any2array function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("any2array").should == "function_any2array" + end + + it "should return an empty array if there is less than 1 argument" do + result = scope.function_any2array([]) + result.should(eq([])) + end + + it "should convert boolean true to [ true ] " do + result = scope.function_any2array([true]) + result.should(eq([true])) + end + + it "should convert one object to [object]" do + result = scope.function_any2array(['one']) + result.should(eq(['one'])) + end + + it "should convert multiple objects to [objects]" do + result = scope.function_any2array(['one', 'two']) + result.should(eq(['one', 'two'])) + end + + it "should return empty array it was called with" do + result = scope.function_any2array([[]]) + result.should(eq([])) + end + + it "should return one-member array it was called with" do + result = scope.function_any2array([['string']]) + result.should(eq(['string'])) + end + + it "should return multi-member array it was called with" do + result = scope.function_any2array([['one', 'two']]) + result.should(eq(['one', 'two'])) + end + + it "should return members of a hash it was called with" do + result = scope.function_any2array([{ 'key' => 'value' }]) + result.should(eq(['key', 'value'])) + end + + it "should return an empty array if it was called with an empty hash" do + result = scope.function_any2array([{ }]) + result.should(eq([])) + end +end diff --git a/modules/stdlib/spec/functions/base64_spec.rb b/modules/stdlib/spec/functions/base64_spec.rb new file mode 100755 index 0000000..5faa5e6 --- /dev/null +++ b/modules/stdlib/spec/functions/base64_spec.rb @@ -0,0 +1,34 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe "the base64 function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("base64").should == "function_base64" + end + + it "should raise a ParseError if there are other than 2 arguments" do + expect { scope.function_base64([]) }.to(raise_error(Puppet::ParseError)) + expect { scope.function_base64(["asdf"]) }.to(raise_error(Puppet::ParseError)) + expect { scope.function_base64(["asdf","moo","cow"]) }.to(raise_error(Puppet::ParseError)) + end + + it "should raise a ParseError if argument 1 isn't 'encode' or 'decode'" do + expect { scope.function_base64(["bees","astring"]) }.to(raise_error(Puppet::ParseError, /first argument must be one of/)) + end + + it "should raise a ParseError if argument 2 isn't a string" do + expect { scope.function_base64(["encode",["2"]]) }.to(raise_error(Puppet::ParseError, /second argument must be a string/)) + end + + it "should encode a encoded string" do + result = scope.function_base64(["encode",'thestring']) + result.should =~ /\AdGhlc3RyaW5n\n\Z/ + end + it "should decode a base64 encoded string" do + result = scope.function_base64(["decode",'dGhlc3RyaW5n']) + result.should == 'thestring' + end +end diff --git a/modules/stdlib/spec/functions/bool2num_spec.rb b/modules/stdlib/spec/functions/bool2num_spec.rb new file mode 100755 index 0000000..518ac85 --- /dev/null +++ b/modules/stdlib/spec/functions/bool2num_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the bool2num function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("bool2num").should == "function_bool2num" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_bool2num([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should convert true to 1" do + result = scope.function_bool2num([true]) + result.should(eq(1)) + end + + it "should convert false to 0" do + result = scope.function_bool2num([false]) + result.should(eq(0)) + end +end diff --git a/modules/stdlib/spec/functions/capitalize_spec.rb b/modules/stdlib/spec/functions/capitalize_spec.rb new file mode 100755 index 0000000..69c9758 --- /dev/null +++ b/modules/stdlib/spec/functions/capitalize_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the capitalize function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("capitalize").should == "function_capitalize" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_capitalize([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should capitalize the beginning of a string" do + result = scope.function_capitalize(["abc"]) + result.should(eq("Abc")) + end +end diff --git a/modules/stdlib/spec/functions/chomp_spec.rb b/modules/stdlib/spec/functions/chomp_spec.rb new file mode 100755 index 0000000..e425365 --- /dev/null +++ b/modules/stdlib/spec/functions/chomp_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the chomp function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("chomp").should == "function_chomp" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_chomp([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should chomp the end of a string" do + result = scope.function_chomp(["abc\n"]) + result.should(eq("abc")) + end +end diff --git a/modules/stdlib/spec/functions/chop_spec.rb b/modules/stdlib/spec/functions/chop_spec.rb new file mode 100755 index 0000000..9e466de --- /dev/null +++ b/modules/stdlib/spec/functions/chop_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the chop function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("chop").should == "function_chop" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_chop([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should chop the end of a string" do + result = scope.function_chop(["asdf\n"]) + result.should(eq("asdf")) + end +end diff --git a/modules/stdlib/spec/functions/concat_spec.rb b/modules/stdlib/spec/functions/concat_spec.rb new file mode 100755 index 0000000..6e67620 --- /dev/null +++ b/modules/stdlib/spec/functions/concat_spec.rb @@ -0,0 +1,30 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the concat function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should raise a ParseError if the client does not provide two arguments" do + lambda { scope.function_concat([]) }.should(raise_error(Puppet::ParseError)) + end + + it "should raise a ParseError if the first parameter is not an array" do + lambda { scope.function_concat([1, []])}.should(raise_error(Puppet::ParseError)) + end + + it "should be able to concat an array" do + result = scope.function_concat([['1','2','3'],['4','5','6']]) + result.should(eq(['1','2','3','4','5','6'])) + end + + it "should be able to concat a primitive to an array" do + result = scope.function_concat([['1','2','3'],'4']) + result.should(eq(['1','2','3','4'])) + end + + it "should not accidentally flatten nested arrays" do + result = scope.function_concat([['1','2','3'],[['4','5'],'6']]) + result.should(eq(['1','2','3',['4','5'],'6'])) + end + +end diff --git a/modules/stdlib/spec/functions/count_spec.rb b/modules/stdlib/spec/functions/count_spec.rb new file mode 100755 index 0000000..2453815 --- /dev/null +++ b/modules/stdlib/spec/functions/count_spec.rb @@ -0,0 +1,31 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe "the count function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("count").should == "function_count" + end + + it "should raise a ArgumentError if there is more than 2 arguments" do + lambda { scope.function_count(['foo', 'bar', 'baz']) }.should( raise_error(ArgumentError)) + end + + it "should be able to count arrays" do + scope.function_count([["1","2","3"]]).should(eq(3)) + end + + it "should be able to count matching elements in arrays" do + scope.function_count([["1", "2", "2"], "2"]).should(eq(2)) + end + + it "should not count nil or empty strings" do + scope.function_count([["foo","bar",nil,""]]).should(eq(2)) + end + + it 'does not count an undefined hash key or an out of bound array index (which are both :undef)' do + expect(scope.function_count([["foo",:undef,:undef]])).to eq(1) + end +end diff --git a/modules/stdlib/spec/functions/deep_merge_spec.rb b/modules/stdlib/spec/functions/deep_merge_spec.rb new file mode 100755 index 0000000..f134701 --- /dev/null +++ b/modules/stdlib/spec/functions/deep_merge_spec.rb @@ -0,0 +1,105 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:deep_merge) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + describe 'when calling deep_merge from puppet' do + it "should not compile when no arguments are passed" do + pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ + Puppet[:code] = '$x = deep_merge()' + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /wrong number of arguments/) + end + + it "should not compile when 1 argument is passed" do + pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ + Puppet[:code] = "$my_hash={'one' => 1}\n$x = deep_merge($my_hash)" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /wrong number of arguments/) + end + end + + describe 'when calling deep_merge on the scope instance' do + it 'should require all parameters are hashes' do + expect { new_hash = scope.function_deep_merge([{}, '2'])}.to raise_error(Puppet::ParseError, /unexpected argument type String/) + expect { new_hash = scope.function_deep_merge([{}, 2])}.to raise_error(Puppet::ParseError, /unexpected argument type Fixnum/) + end + + it 'should accept empty strings as puppet undef' do + expect { new_hash = scope.function_deep_merge([{}, ''])}.not_to raise_error + end + + it 'should be able to deep_merge two hashes' do + new_hash = scope.function_deep_merge([{'one' => '1', 'two' => '1'}, {'two' => '2', 'three' => '2'}]) + new_hash['one'].should == '1' + new_hash['two'].should == '2' + new_hash['three'].should == '2' + end + + it 'should deep_merge multiple hashes' do + hash = scope.function_deep_merge([{'one' => 1}, {'one' => '2'}, {'one' => '3'}]) + hash['one'].should == '3' + end + + it 'should accept empty hashes' do + scope.function_deep_merge([{},{},{}]).should == {} + end + + it 'should deep_merge subhashes' do + hash = scope.function_deep_merge([{'one' => 1}, {'two' => 2, 'three' => { 'four' => 4 } }]) + hash['one'].should == 1 + hash['two'].should == 2 + hash['three'].should == { 'four' => 4 } + end + + it 'should append to subhashes' do + hash = scope.function_deep_merge([{'one' => { 'two' => 2 } }, { 'one' => { 'three' => 3 } }]) + hash['one'].should == { 'two' => 2, 'three' => 3 } + end + + it 'should append to subhashes 2' do + hash = scope.function_deep_merge([{'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } }, {'two' => 'dos', 'three' => { 'five' => 5 } }]) + hash['one'].should == 1 + hash['two'].should == 'dos' + hash['three'].should == { 'four' => 4, 'five' => 5 } + end + + it 'should append to subhashes 3' do + hash = scope.function_deep_merge([{ 'key1' => { 'a' => 1, 'b' => 2 }, 'key2' => { 'c' => 3 } }, { 'key1' => { 'b' => 99 } }]) + hash['key1'].should == { 'a' => 1, 'b' => 99 } + hash['key2'].should == { 'c' => 3 } + end + + it 'should not change the original hashes' do + hash1 = {'one' => { 'two' => 2 } } + hash2 = { 'one' => { 'three' => 3 } } + hash = scope.function_deep_merge([hash1, hash2]) + hash1.should == {'one' => { 'two' => 2 } } + hash2.should == { 'one' => { 'three' => 3 } } + hash['one'].should == { 'two' => 2, 'three' => 3 } + end + + it 'should not change the original hashes 2' do + hash1 = {'one' => { 'two' => [1,2] } } + hash2 = { 'one' => { 'three' => 3 } } + hash = scope.function_deep_merge([hash1, hash2]) + hash1.should == {'one' => { 'two' => [1,2] } } + hash2.should == { 'one' => { 'three' => 3 } } + hash['one'].should == { 'two' => [1,2], 'three' => 3 } + end + + it 'should not change the original hashes 3' do + hash1 = {'one' => { 'two' => [1,2, {'two' => 2} ] } } + hash2 = { 'one' => { 'three' => 3 } } + hash = scope.function_deep_merge([hash1, hash2]) + hash1.should == {'one' => { 'two' => [1,2, {'two' => 2}] } } + hash2.should == { 'one' => { 'three' => 3 } } + hash['one'].should == { 'two' => [1,2, {'two' => 2} ], 'three' => 3 } + hash['one']['two'].should == [1,2, {'two' => 2}] + end + end +end diff --git a/modules/stdlib/spec/functions/defined_with_params_spec.rb b/modules/stdlib/spec/functions/defined_with_params_spec.rb new file mode 100755 index 0000000..28dbab3 --- /dev/null +++ b/modules/stdlib/spec/functions/defined_with_params_spec.rb @@ -0,0 +1,37 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +require 'rspec-puppet' +describe 'defined_with_params' do + describe 'when a resource is not specified' do + it { should run.with_params().and_raise_error(ArgumentError) } + end + describe 'when compared against a resource with no attributes' do + let :pre_condition do + 'user { "dan": }' + end + it do + should run.with_params('User[dan]', {}).and_return(true) + should run.with_params('User[bob]', {}).and_return(false) + should run.with_params('User[dan]', {'foo' => 'bar'}).and_return(false) + end + end + + describe 'when compared against a resource with attributes' do + let :pre_condition do + 'user { "dan": ensure => present, shell => "/bin/csh", managehome => false}' + end + it do + should run.with_params('User[dan]', {}).and_return(true) + should run.with_params('User[dan]', '').and_return(true) + should run.with_params('User[dan]', {'ensure' => 'present'} + ).and_return(true) + should run.with_params('User[dan]', + {'ensure' => 'present', 'managehome' => false} + ).and_return(true) + should run.with_params('User[dan]', + {'ensure' => 'absent', 'managehome' => false} + ).and_return(false) + end + end +end diff --git a/modules/stdlib/spec/functions/delete_at_spec.rb b/modules/stdlib/spec/functions/delete_at_spec.rb new file mode 100755 index 0000000..593cf45 --- /dev/null +++ b/modules/stdlib/spec/functions/delete_at_spec.rb @@ -0,0 +1,25 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the delete_at function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("delete_at").should == "function_delete_at" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_delete_at([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should delete an item at specified location from an array" do + result = scope.function_delete_at([['a','b','c'],1]) + result.should(eq(['a','c'])) + end + + it "should not change origin array passed as argument" do + origin_array = ['a','b','c','d'] + result = scope.function_delete_at([origin_array, 1]) + origin_array.should(eq(['a','b','c','d'])) + end +end diff --git a/modules/stdlib/spec/functions/delete_spec.rb b/modules/stdlib/spec/functions/delete_spec.rb new file mode 100755 index 0000000..1508a63 --- /dev/null +++ b/modules/stdlib/spec/functions/delete_spec.rb @@ -0,0 +1,56 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the delete function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("delete").should == "function_delete" + end + + it "should raise a ParseError if there are fewer than 2 arguments" do + lambda { scope.function_delete([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should raise a ParseError if there are greater than 2 arguments" do + lambda { scope.function_delete([[], 'foo', 'bar']) }.should( raise_error(Puppet::ParseError)) + end + + it "should raise a TypeError if a number is passed as the first argument" do + lambda { scope.function_delete([1, 'bar']) }.should( raise_error(TypeError)) + end + + it "should delete all instances of an element from an array" do + result = scope.function_delete([['a','b','c','b'],'b']) + result.should(eq(['a','c'])) + end + + it "should delete all instances of a substring from a string" do + result = scope.function_delete(['foobarbabarz','bar']) + result.should(eq('foobaz')) + end + + it "should delete a key from a hash" do + result = scope.function_delete([{ 'a' => 1, 'b' => 2, 'c' => 3 },'b']) + result.should(eq({ 'a' => 1, 'c' => 3 })) + end + + it "should not change origin array passed as argument" do + origin_array = ['a','b','c','d'] + result = scope.function_delete([origin_array, 'b']) + origin_array.should(eq(['a','b','c','d'])) + end + + it "should not change the origin string passed as argument" do + origin_string = 'foobarbabarz' + result = scope.function_delete([origin_string,'bar']) + origin_string.should(eq('foobarbabarz')) + end + + it "should not change origin hash passed as argument" do + origin_hash = { 'a' => 1, 'b' => 2, 'c' => 3 } + result = scope.function_delete([origin_hash, 'b']) + origin_hash.should(eq({ 'a' => 1, 'b' => 2, 'c' => 3 })) + end + +end diff --git a/modules/stdlib/spec/functions/delete_undef_values_spec.rb b/modules/stdlib/spec/functions/delete_undef_values_spec.rb new file mode 100755 index 0000000..b341d88 --- /dev/null +++ b/modules/stdlib/spec/functions/delete_undef_values_spec.rb @@ -0,0 +1,41 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the delete_undef_values function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("delete_undef_values").should == "function_delete_undef_values" + end + + it "should raise a ParseError if there is less than 1 argument" do + lambda { scope.function_delete_undef_values([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should raise a ParseError if the argument is not Array nor Hash" do + lambda { scope.function_delete_undef_values(['']) }.should( raise_error(Puppet::ParseError)) + lambda { scope.function_delete_undef_values([nil]) }.should( raise_error(Puppet::ParseError)) + end + + it "should delete all undef items from Array and only these" do + result = scope.function_delete_undef_values([['a',:undef,'c','undef']]) + result.should(eq(['a','c','undef'])) + end + + it "should delete all undef items from Hash and only these" do + result = scope.function_delete_undef_values([{'a'=>'A','b'=>:undef,'c'=>'C','d'=>'undef'}]) + result.should(eq({'a'=>'A','c'=>'C','d'=>'undef'})) + end + + it "should not change origin array passed as argument" do + origin_array = ['a',:undef,'c','undef'] + result = scope.function_delete_undef_values([origin_array]) + origin_array.should(eq(['a',:undef,'c','undef'])) + end + + it "should not change origin hash passed as argument" do + origin_hash = { 'a' => 1, 'b' => :undef, 'c' => 'undef' } + result = scope.function_delete_undef_values([origin_hash]) + origin_hash.should(eq({ 'a' => 1, 'b' => :undef, 'c' => 'undef' })) + end +end diff --git a/modules/stdlib/spec/functions/delete_values_spec.rb b/modules/stdlib/spec/functions/delete_values_spec.rb new file mode 100755 index 0000000..8d7f231 --- /dev/null +++ b/modules/stdlib/spec/functions/delete_values_spec.rb @@ -0,0 +1,36 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the delete_values function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("delete_values").should == "function_delete_values" + end + + it "should raise a ParseError if there are fewer than 2 arguments" do + lambda { scope.function_delete_values([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should raise a ParseError if there are greater than 2 arguments" do + lambda { scope.function_delete_values([[], 'foo', 'bar']) }.should( raise_error(Puppet::ParseError)) + end + + it "should raise a TypeError if the argument is not a hash" do + lambda { scope.function_delete_values([1,'bar']) }.should( raise_error(TypeError)) + lambda { scope.function_delete_values(['foo','bar']) }.should( raise_error(TypeError)) + lambda { scope.function_delete_values([[],'bar']) }.should( raise_error(TypeError)) + end + + it "should delete all instances of a value from a hash" do + result = scope.function_delete_values([{ 'a'=>'A', 'b'=>'B', 'B'=>'C', 'd'=>'B' },'B']) + result.should(eq({ 'a'=>'A', 'B'=>'C' })) + end + + it "should not change origin hash passed as argument" do + origin_hash = { 'a' => 1, 'b' => 2, 'c' => 3 } + result = scope.function_delete_values([origin_hash, 2]) + origin_hash.should(eq({ 'a' => 1, 'b' => 2, 'c' => 3 })) + end + +end diff --git a/modules/stdlib/spec/functions/difference_spec.rb b/modules/stdlib/spec/functions/difference_spec.rb new file mode 100755 index 0000000..9feff09 --- /dev/null +++ b/modules/stdlib/spec/functions/difference_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the difference function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("difference").should == "function_difference" + end + + it "should raise a ParseError if there are fewer than 2 arguments" do + lambda { scope.function_difference([]) }.should( raise_error(Puppet::ParseError) ) + end + + it "should return the difference between two arrays" do + result = scope.function_difference([["a","b","c"],["b","c","d"]]) + result.should(eq(["a"])) + end +end diff --git a/modules/stdlib/spec/functions/dirname_spec.rb b/modules/stdlib/spec/functions/dirname_spec.rb new file mode 100755 index 0000000..fb3b4fe --- /dev/null +++ b/modules/stdlib/spec/functions/dirname_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the dirname function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("dirname").should == "function_dirname" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_dirname([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return dirname for an absolute path" do + result = scope.function_dirname(['/path/to/a/file.ext']) + result.should(eq('/path/to/a')) + end + + it "should return dirname for a relative path" do + result = scope.function_dirname(['path/to/a/file.ext']) + result.should(eq('path/to/a')) + end +end diff --git a/modules/stdlib/spec/functions/downcase_spec.rb b/modules/stdlib/spec/functions/downcase_spec.rb new file mode 100755 index 0000000..acef1f0 --- /dev/null +++ b/modules/stdlib/spec/functions/downcase_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the downcase function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("downcase").should == "function_downcase" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_downcase([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should downcase a string" do + result = scope.function_downcase(["ASFD"]) + result.should(eq("asfd")) + end + + it "should do nothing to a string that is already downcase" do + result = scope.function_downcase(["asdf asdf"]) + result.should(eq("asdf asdf")) + end +end diff --git a/modules/stdlib/spec/functions/empty_spec.rb b/modules/stdlib/spec/functions/empty_spec.rb new file mode 100755 index 0000000..7745875 --- /dev/null +++ b/modules/stdlib/spec/functions/empty_spec.rb @@ -0,0 +1,23 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the empty function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + it "should exist" do + Puppet::Parser::Functions.function("empty").should == "function_empty" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_empty([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return a true for an empty string" do + result = scope.function_empty(['']) + result.should(eq(true)) + end + + it "should return a false for a non-empty string" do + result = scope.function_empty(['asdf']) + result.should(eq(false)) + end +end diff --git a/modules/stdlib/spec/functions/ensure_packages_spec.rb b/modules/stdlib/spec/functions/ensure_packages_spec.rb new file mode 100755 index 0000000..436be10 --- /dev/null +++ b/modules/stdlib/spec/functions/ensure_packages_spec.rb @@ -0,0 +1,81 @@ +#! /usr/bin/env ruby + +require 'spec_helper' +require 'rspec-puppet' +require 'puppet_spec/compiler' + +describe 'ensure_packages' do + include PuppetSpec::Compiler + + before :each do + Puppet::Parser::Functions.autoloader.loadall + Puppet::Parser::Functions.function(:ensure_packages) + Puppet::Parser::Functions.function(:ensure_resource) + Puppet::Parser::Functions.function(:defined_with_params) + Puppet::Parser::Functions.function(:create_resources) + end + + let :node do Puppet::Node.new('localhost') end + let :compiler do Puppet::Parser::Compiler.new(node) end + let :scope do + if Puppet.version.to_f >= 3.0 + Puppet::Parser::Scope.new(compiler) + else + newscope = Puppet::Parser::Scope.new + newscope.compiler = compiler + newscope.source = Puppet::Resource::Type.new(:node, :localhost) + newscope + end + end + + describe 'argument handling' do + it 'fails with no arguments' do + expect { + scope.function_ensure_packages([]) + }.to raise_error(Puppet::ParseError, /0 for 1 or 2/) + end + + it 'accepts an array of values' do + scope.function_ensure_packages([['foo']]) + end + + it 'accepts a single package name as a string' do + scope.function_ensure_packages(['foo']) + end + end + + context 'given a catalog with puppet package => absent' do + let :catalog do + compile_to_catalog(<<-EOS + ensure_packages(['facter']) + package { puppet: ensure => absent } + EOS + ) + end + + it 'has no effect on Package[puppet]' do + expect(catalog.resource(:package, 'puppet')['ensure']).to eq('absent') + end + end + + context 'given a clean catalog' do + let :catalog do + compile_to_catalog('ensure_packages(["facter"])') + end + + it 'declares package resources with ensure => present' do + expect(catalog.resource(:package, 'facter')['ensure']).to eq('present') + end + end + + context 'given a clean catalog and specified defaults' do + let :catalog do + compile_to_catalog('ensure_packages(["facter"], {"provider" => "gem"})') + end + + it 'declares package resources with ensure => present' do + expect(catalog.resource(:package, 'facter')['ensure']).to eq('present') + expect(catalog.resource(:package, 'facter')['provider']).to eq('gem') + end + end +end diff --git a/modules/stdlib/spec/functions/ensure_resource_spec.rb b/modules/stdlib/spec/functions/ensure_resource_spec.rb new file mode 100755 index 0000000..33bcac0 --- /dev/null +++ b/modules/stdlib/spec/functions/ensure_resource_spec.rb @@ -0,0 +1,113 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' +require 'rspec-puppet' +require 'puppet_spec/compiler' + +describe 'ensure_resource' do + include PuppetSpec::Compiler + + before :all do + Puppet::Parser::Functions.autoloader.loadall + Puppet::Parser::Functions.function(:ensure_packages) + end + + let :node do Puppet::Node.new('localhost') end + let :compiler do Puppet::Parser::Compiler.new(node) end + let :scope do Puppet::Parser::Scope.new(compiler) end + + describe 'when a type or title is not specified' do + it { expect { scope.function_ensure_resource([]) }.to raise_error } + it { expect { scope.function_ensure_resource(['type']) }.to raise_error } + end + + describe 'when compared against a resource with no attributes' do + let :catalog do + compile_to_catalog(<<-EOS + user { "dan": } + ensure_resource('user', 'dan', {}) + EOS + ) + end + + it 'should contain the the ensured resources' do + expect(catalog.resource(:user, 'dan').to_s).to eq('User[dan]') + end + end + + describe 'works when compared against a resource with non-conflicting attributes' do + [ + "ensure_resource('User', 'dan', {})", + "ensure_resource('User', 'dan', '')", + "ensure_resource('User', 'dan', {'ensure' => 'present'})", + "ensure_resource('User', 'dan', {'ensure' => 'present', 'managehome' => false})" + ].each do |ensure_resource| + pp = <<-EOS + user { "dan": ensure => present, shell => "/bin/csh", managehome => false} + #{ensure_resource} + EOS + + it { expect { compile_to_catalog(pp) }.to_not raise_error } + end + end + + describe 'fails when compared against a resource with conflicting attributes' do + pp = <<-EOS + user { "dan": ensure => present, shell => "/bin/csh", managehome => false} + ensure_resource('User', 'dan', {'ensure' => 'absent', 'managehome' => false}) + EOS + + it { expect { compile_to_catalog(pp) }.to raise_error } + end + + describe 'when an array of new resources are passed in' do + let :catalog do + compile_to_catalog("ensure_resource('User', ['dan', 'alex'], {})") + end + + it 'should contain the ensured resources' do + expect(catalog.resource('User[dan]').to_s).to eq('User[dan]') + expect(catalog.resource('User[alex]').to_s).to eq('User[alex]') + end + end + + describe 'when an array of existing resources is compared against existing resources' do + pp = <<-EOS + user { 'dan': ensure => present; 'alex': ensure => present } + ensure_resource('User', ['dan', 'alex'], {}) + EOS + + let :catalog do + compile_to_catalog(pp) + end + + it 'should return the existing resources' do + expect(catalog.resource('User[dan]').to_s).to eq('User[dan]') + expect(catalog.resource('User[alex]').to_s).to eq('User[alex]') + end + end + + describe 'works when compared against existing resources with attributes' do + [ + "ensure_resource('User', ['dan', 'alex'], {})", + "ensure_resource('User', ['dan', 'alex'], '')", + "ensure_resource('User', ['dan', 'alex'], {'ensure' => 'present'})", + ].each do |ensure_resource| + pp = <<-EOS + user { 'dan': ensure => present; 'alex': ensure => present } + #{ensure_resource} + EOS + + it { expect { compile_to_catalog(pp) }.to_not raise_error } + end + end + + describe 'fails when compared against existing resources with conflicting attributes' do + pp = <<-EOS + user { 'dan': ensure => present; 'alex': ensure => present } + ensure_resource('User', ['dan', 'alex'], {'ensure' => 'absent'}) + EOS + + it { expect { compile_to_catalog(pp) }.to raise_error } + end + +end diff --git a/modules/stdlib/spec/functions/flatten_spec.rb b/modules/stdlib/spec/functions/flatten_spec.rb new file mode 100755 index 0000000..dba7a6b --- /dev/null +++ b/modules/stdlib/spec/functions/flatten_spec.rb @@ -0,0 +1,27 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the flatten function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + it "should exist" do + Puppet::Parser::Functions.function("flatten").should == "function_flatten" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_flatten([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should raise a ParseError if there is more than 1 argument" do + lambda { scope.function_flatten([[], []]) }.should( raise_error(Puppet::ParseError)) + end + + it "should flatten a complex data structure" do + result = scope.function_flatten([["a","b",["c",["d","e"],"f","g"]]]) + result.should(eq(["a","b","c","d","e","f","g"])) + end + + it "should do nothing to a structure that is already flat" do + result = scope.function_flatten([["a","b","c","d"]]) + result.should(eq(["a","b","c","d"])) + end +end diff --git a/modules/stdlib/spec/functions/floor_spec.rb b/modules/stdlib/spec/functions/floor_spec.rb new file mode 100755 index 0000000..dbc8c77 --- /dev/null +++ b/modules/stdlib/spec/functions/floor_spec.rb @@ -0,0 +1,39 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe "the floor function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("floor").should == "function_floor" + end + + it "should raise a ParseError if there is less than 1 argument" do + lambda { scope.function_floor([]) }.should( raise_error(Puppet::ParseError, /Wrong number of arguments/)) + end + + it "should should raise a ParseError if input isn't numeric (eg. String)" do + lambda { scope.function_floor(["foo"]) }.should( raise_error(Puppet::ParseError, /Wrong argument type/)) + end + + it "should should raise a ParseError if input isn't numeric (eg. Boolean)" do + lambda { scope.function_floor([true]) }.should( raise_error(Puppet::ParseError, /Wrong argument type/)) + end + + it "should return an integer when a numeric type is passed" do + result = scope.function_floor([12.4]) + result.is_a?(Integer).should(eq(true)) + end + + it "should return the input when an integer is passed" do + result = scope.function_floor([7]) + result.should(eq(7)) + end + + it "should return the largest integer less than or equal to the input" do + result = scope.function_floor([3.8]) + result.should(eq(3)) + end +end + diff --git a/modules/stdlib/spec/functions/fqdn_rotate_spec.rb b/modules/stdlib/spec/functions/fqdn_rotate_spec.rb new file mode 100755 index 0000000..2577723 --- /dev/null +++ b/modules/stdlib/spec/functions/fqdn_rotate_spec.rb @@ -0,0 +1,33 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the fqdn_rotate function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("fqdn_rotate").should == "function_fqdn_rotate" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_fqdn_rotate([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should rotate a string and the result should be the same size" do + scope.expects(:lookupvar).with("::fqdn").returns("127.0.0.1") + result = scope.function_fqdn_rotate(["asdf"]) + result.size.should(eq(4)) + end + + it "should rotate a string to give the same results for one host" do + scope.expects(:lookupvar).with("::fqdn").returns("127.0.0.1").twice + scope.function_fqdn_rotate(["abcdefg"]).should eql(scope.function_fqdn_rotate(["abcdefg"])) + end + + it "should rotate a string to give different values on different hosts" do + scope.expects(:lookupvar).with("::fqdn").returns("127.0.0.1") + val1 = scope.function_fqdn_rotate(["abcdefghijklmnopqrstuvwxyz01234567890987654321"]) + scope.expects(:lookupvar).with("::fqdn").returns("127.0.0.2") + val2 = scope.function_fqdn_rotate(["abcdefghijklmnopqrstuvwxyz01234567890987654321"]) + val1.should_not eql(val2) + end +end diff --git a/modules/stdlib/spec/functions/get_module_path_spec.rb b/modules/stdlib/spec/functions/get_module_path_spec.rb new file mode 100755 index 0000000..486bef6 --- /dev/null +++ b/modules/stdlib/spec/functions/get_module_path_spec.rb @@ -0,0 +1,46 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:get_module_path) do + Internals = PuppetlabsSpec::PuppetInternals + class StubModule + attr_reader :path + def initialize(path) + @path = path + end + end + + def scope(environment = "production") + Internals.scope(:compiler => Internals.compiler(:node => Internals.node(:environment => environment))) + end + + it 'should only allow one argument' do + expect { scope.function_get_module_path([]) }.to raise_error(Puppet::ParseError, /Wrong number of arguments, expects one/) + expect { scope.function_get_module_path(['1','2','3']) }.to raise_error(Puppet::ParseError, /Wrong number of arguments, expects one/) + end + it 'should raise an exception when the module cannot be found' do + expect { scope.function_get_module_path(['foo']) }.to raise_error(Puppet::ParseError, /Could not find module/) + end + describe 'when locating a module' do + let(:modulepath) { "/tmp/does_not_exist" } + let(:path_of_module_foo) { StubModule.new("/tmp/does_not_exist/foo") } + + before(:each) { Puppet[:modulepath] = modulepath } + + it 'should be able to find module paths from the modulepath setting' do + Puppet::Module.expects(:find).with('foo', 'production').returns(path_of_module_foo) + scope.function_get_module_path(['foo']).should == path_of_module_foo.path + end + it 'should be able to find module paths when the modulepath is a list' do + Puppet[:modulepath] = modulepath + ":/tmp" + Puppet::Module.expects(:find).with('foo', 'production').returns(path_of_module_foo) + scope.function_get_module_path(['foo']).should == path_of_module_foo.path + end + it 'should respect the environment' do + pending("Disabled on Puppet 2.6.x") if Puppet.version =~ /^2\.6\b/ + Puppet.settings[:environment] = 'danstestenv' + Puppet::Module.expects(:find).with('foo', 'danstestenv').returns(path_of_module_foo) + scope('danstestenv').function_get_module_path(['foo']).should == path_of_module_foo.path + end + end +end diff --git a/modules/stdlib/spec/functions/getparam_spec.rb b/modules/stdlib/spec/functions/getparam_spec.rb new file mode 100755 index 0000000..bf024af --- /dev/null +++ b/modules/stdlib/spec/functions/getparam_spec.rb @@ -0,0 +1,76 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' +require 'rspec-puppet' +require 'puppet_spec/compiler' + +describe 'getparam' do + include PuppetSpec::Compiler + + before :each do + Puppet::Parser::Functions.autoloader.loadall + Puppet::Parser::Functions.function(:getparam) + end + + let :node do Puppet::Node.new('localhost') end + let :compiler do Puppet::Parser::Compiler.new(node) end + if Puppet.version.to_f >= 3.0 + let :scope do Puppet::Parser::Scope.new(compiler) end + else + let :scope do + newscope = Puppet::Parser::Scope.new + newscope.compiler = compiler + newscope.source = Puppet::Resource::Type.new(:node, :localhost) + newscope + end + end + + it "should exist" do + Puppet::Parser::Functions.function("getparam").should == "function_getparam" + end + + describe 'when a resource is not specified' do + it { expect { scope.function_getparam([]) }.to raise_error } + it { expect { scope.function_getparam(['User[dan]']) }.to raise_error } + it { expect { scope.function_getparam(['User[dan]']) }.to raise_error } + it { expect { scope.function_getparam(['User[dan]', {}]) }.to raise_error } + # This seems to be OK because we just check for a string. + it { expect { scope.function_getparam(['User[dan]', '']) }.to_not raise_error } + end + + describe 'when compared against a resource with no params' do + let :catalog do + compile_to_catalog(<<-EOS + user { "dan": } + EOS + ) + end + + it do + expect(scope.function_getparam(['User[dan]', 'shell'])).to eq('') + end + end + + describe 'when compared against a resource with params' do + let :catalog do + compile_to_catalog(<<-EOS + user { 'dan': ensure => present, shell => '/bin/sh', managehome => false} + $test = getparam(User[dan], 'shell') + EOS + ) + end + + it do + resource = Puppet::Parser::Resource.new(:user, 'dan', {:scope => scope}) + resource.set_parameter('ensure', 'present') + resource.set_parameter('shell', '/bin/sh') + resource.set_parameter('managehome', false) + compiler.add_resource(scope, resource) + + expect(scope.function_getparam(['User[dan]', 'shell'])).to eq('/bin/sh') + expect(scope.function_getparam(['User[dan]', ''])).to eq('') + expect(scope.function_getparam(['User[dan]', 'ensure'])).to eq('present') + # TODO: Expected this to be false, figure out why we're getting '' back. + expect(scope.function_getparam(['User[dan]', 'managehome'])).to eq('') + end + end +end diff --git a/modules/stdlib/spec/functions/getvar_spec.rb b/modules/stdlib/spec/functions/getvar_spec.rb new file mode 100755 index 0000000..5ff834e --- /dev/null +++ b/modules/stdlib/spec/functions/getvar_spec.rb @@ -0,0 +1,37 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:getvar) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + describe 'when calling getvar from puppet' do + + it "should not compile when no arguments are passed" do + pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ + Puppet[:code] = '$foo = getvar()' + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /wrong number of arguments/) + end + + it "should not compile when too many arguments are passed" do + pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ + Puppet[:code] = '$foo = getvar("foo::bar", "baz")' + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /wrong number of arguments/) + end + + it "should lookup variables in other namespaces" do + pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ + Puppet[:code] = <<-'ENDofPUPPETcode' + class site::data { $foo = 'baz' } + include site::data + $foo = getvar("site::data::foo") + if $foo != 'baz' { + fail('getvar did not return what we expect') + } + ENDofPUPPETcode + scope.compiler.compile + end + end +end diff --git a/modules/stdlib/spec/functions/grep_spec.rb b/modules/stdlib/spec/functions/grep_spec.rb new file mode 100755 index 0000000..a93b842 --- /dev/null +++ b/modules/stdlib/spec/functions/grep_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the grep function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("grep").should == "function_grep" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_grep([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should grep contents from an array" do + result = scope.function_grep([["aaabbb","bbbccc","dddeee"], "bbb"]) + result.should(eq(["aaabbb","bbbccc"])) + end +end diff --git a/modules/stdlib/spec/functions/has_interface_with_spec.rb b/modules/stdlib/spec/functions/has_interface_with_spec.rb new file mode 100755 index 0000000..c5264e4 --- /dev/null +++ b/modules/stdlib/spec/functions/has_interface_with_spec.rb @@ -0,0 +1,64 @@ +#!/usr/bin/env ruby -S rspec +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:has_interface_with) do + + let(:scope) do + PuppetlabsSpec::PuppetInternals.scope + end + + # The subject of these examples is the method itself. + subject do + function_name = Puppet::Parser::Functions.function(:has_interface_with) + scope.method(function_name) + end + + # We need to mock out the Facts so we can specify how we expect this function + # to behave on different platforms. + context "On Mac OS X Systems" do + before :each do + scope.stubs(:lookupvar).with("interfaces").returns('lo0,gif0,stf0,en1,p2p0,fw0,en0,vmnet1,vmnet8,utun0') + end + it 'should have loopback (lo0)' do + subject.call(['lo0']).should be_true + end + it 'should not have loopback (lo)' do + subject.call(['lo']).should be_false + end + end + context "On Linux Systems" do + before :each do + scope.stubs(:lookupvar).with("interfaces").returns('eth0,lo') + scope.stubs(:lookupvar).with("ipaddress").returns('10.0.0.1') + scope.stubs(:lookupvar).with("ipaddress_lo").returns('127.0.0.1') + scope.stubs(:lookupvar).with("ipaddress_eth0").returns('10.0.0.1') + scope.stubs(:lookupvar).with('muppet').returns('kermit') + scope.stubs(:lookupvar).with('muppet_lo').returns('mspiggy') + scope.stubs(:lookupvar).with('muppet_eth0').returns('kermit') + end + it 'should have loopback (lo)' do + subject.call(['lo']).should be_true + end + it 'should not have loopback (lo0)' do + subject.call(['lo0']).should be_false + end + it 'should have ipaddress with 127.0.0.1' do + subject.call(['ipaddress', '127.0.0.1']).should be_true + end + it 'should have ipaddress with 10.0.0.1' do + subject.call(['ipaddress', '10.0.0.1']).should be_true + end + it 'should not have ipaddress with 10.0.0.2' do + subject.call(['ipaddress', '10.0.0.2']).should be_false + end + it 'should have muppet named kermit' do + subject.call(['muppet', 'kermit']).should be_true + end + it 'should have muppet named mspiggy' do + subject.call(['muppet', 'mspiggy']).should be_true + end + it 'should not have muppet named bigbird' do + subject.call(['muppet', 'bigbird']).should be_false + end + end +end diff --git a/modules/stdlib/spec/functions/has_ip_address_spec.rb b/modules/stdlib/spec/functions/has_ip_address_spec.rb new file mode 100755 index 0000000..5a68460 --- /dev/null +++ b/modules/stdlib/spec/functions/has_ip_address_spec.rb @@ -0,0 +1,39 @@ +#!/usr/bin/env ruby -S rspec +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:has_ip_address) do + + let(:scope) do + PuppetlabsSpec::PuppetInternals.scope + end + + subject do + function_name = Puppet::Parser::Functions.function(:has_ip_address) + scope.method(function_name) + end + + context "On Linux Systems" do + before :each do + scope.stubs(:lookupvar).with('interfaces').returns('eth0,lo') + scope.stubs(:lookupvar).with('ipaddress').returns('10.0.2.15') + scope.stubs(:lookupvar).with('ipaddress_eth0').returns('10.0.2.15') + scope.stubs(:lookupvar).with('ipaddress_lo').returns('127.0.0.1') + end + + it 'should have primary address (10.0.2.15)' do + subject.call(['10.0.2.15']).should be_true + end + + it 'should have lookupback address (127.0.0.1)' do + subject.call(['127.0.0.1']).should be_true + end + + it 'should not have other address' do + subject.call(['192.1681.1.1']).should be_false + end + + it 'should not have "mspiggy" on an interface' do + subject.call(['mspiggy']).should be_false + end + end +end diff --git a/modules/stdlib/spec/functions/has_ip_network_spec.rb b/modules/stdlib/spec/functions/has_ip_network_spec.rb new file mode 100755 index 0000000..c3a289e --- /dev/null +++ b/modules/stdlib/spec/functions/has_ip_network_spec.rb @@ -0,0 +1,36 @@ +#!/usr/bin/env ruby -S rspec +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:has_ip_network) do + + let(:scope) do + PuppetlabsSpec::PuppetInternals.scope + end + + subject do + function_name = Puppet::Parser::Functions.function(:has_ip_network) + scope.method(function_name) + end + + context "On Linux Systems" do + before :each do + scope.stubs(:lookupvar).with('interfaces').returns('eth0,lo') + scope.stubs(:lookupvar).with('network').returns(:undefined) + scope.stubs(:lookupvar).with('network_eth0').returns('10.0.2.0') + scope.stubs(:lookupvar).with('network_lo').returns('127.0.0.1') + end + + it 'should have primary network (10.0.2.0)' do + subject.call(['10.0.2.0']).should be_true + end + + it 'should have loopback network (127.0.0.0)' do + subject.call(['127.0.0.1']).should be_true + end + + it 'should not have other network' do + subject.call(['192.168.1.0']).should be_false + end + end +end + diff --git a/modules/stdlib/spec/functions/has_key_spec.rb b/modules/stdlib/spec/functions/has_key_spec.rb new file mode 100755 index 0000000..490daea --- /dev/null +++ b/modules/stdlib/spec/functions/has_key_spec.rb @@ -0,0 +1,42 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:has_key) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + describe 'when calling has_key from puppet' do + it "should not compile when no arguments are passed" do + pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ + Puppet[:code] = '$x = has_key()' + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /wrong number of arguments/) + end + + it "should not compile when 1 argument is passed" do + pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ + Puppet[:code] = "$x = has_key('foo')" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /wrong number of arguments/) + end + + it "should require the first value to be a Hash" do + pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ + Puppet[:code] = "$x = has_key('foo', 'bar')" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /expects the first argument to be a hash/) + end + end + + describe 'when calling the function has_key from a scope instance' do + it 'should detect existing keys' do + scope.function_has_key([{'one' => 1}, 'one']).should be_true + end + + it 'should detect existing keys' do + scope.function_has_key([{'one' => 1}, 'two']).should be_false + end + end +end diff --git a/modules/stdlib/spec/functions/hash_spec.rb b/modules/stdlib/spec/functions/hash_spec.rb new file mode 100755 index 0000000..7c91be9 --- /dev/null +++ b/modules/stdlib/spec/functions/hash_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the hash function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("hash").should == "function_hash" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_hash([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should convert an array to a hash" do + result = scope.function_hash([['a',1,'b',2,'c',3]]) + result.should(eq({'a'=>1,'b'=>2,'c'=>3})) + end +end diff --git a/modules/stdlib/spec/functions/intersection_spec.rb b/modules/stdlib/spec/functions/intersection_spec.rb new file mode 100755 index 0000000..fd44f7f --- /dev/null +++ b/modules/stdlib/spec/functions/intersection_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the intersection function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("intersection").should == "function_intersection" + end + + it "should raise a ParseError if there are fewer than 2 arguments" do + lambda { scope.function_intersection([]) }.should( raise_error(Puppet::ParseError) ) + end + + it "should return the intersection of two arrays" do + result = scope.function_intersection([["a","b","c"],["b","c","d"]]) + result.should(eq(["b","c"])) + end +end diff --git a/modules/stdlib/spec/functions/is_array_spec.rb b/modules/stdlib/spec/functions/is_array_spec.rb new file mode 100755 index 0000000..e7f4bcd --- /dev/null +++ b/modules/stdlib/spec/functions/is_array_spec.rb @@ -0,0 +1,29 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the is_array function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("is_array").should == "function_is_array" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_is_array([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if passed an array" do + result = scope.function_is_array([[1,2,3]]) + result.should(eq(true)) + end + + it "should return false if passed a hash" do + result = scope.function_is_array([{'a'=>1}]) + result.should(eq(false)) + end + + it "should return false if passed a string" do + result = scope.function_is_array(["asdf"]) + result.should(eq(false)) + end +end diff --git a/modules/stdlib/spec/functions/is_bool_spec.rb b/modules/stdlib/spec/functions/is_bool_spec.rb new file mode 100755 index 0000000..c94e83a --- /dev/null +++ b/modules/stdlib/spec/functions/is_bool_spec.rb @@ -0,0 +1,44 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the is_bool function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("is_bool").should == "function_is_bool" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_is_bool([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if passed a TrueClass" do + result = scope.function_is_bool([true]) + result.should(eq(true)) + end + + it "should return true if passed a FalseClass" do + result = scope.function_is_bool([false]) + result.should(eq(true)) + end + + it "should return false if passed the string 'true'" do + result = scope.function_is_bool(['true']) + result.should(eq(false)) + end + + it "should return false if passed the string 'false'" do + result = scope.function_is_bool(['false']) + result.should(eq(false)) + end + + it "should return false if passed an array" do + result = scope.function_is_bool([["a","b"]]) + result.should(eq(false)) + end + + it "should return false if passed a hash" do + result = scope.function_is_bool([{"a" => "b"}]) + result.should(eq(false)) + end +end diff --git a/modules/stdlib/spec/functions/is_domain_name_spec.rb b/modules/stdlib/spec/functions/is_domain_name_spec.rb new file mode 100755 index 0000000..f2ea76d --- /dev/null +++ b/modules/stdlib/spec/functions/is_domain_name_spec.rb @@ -0,0 +1,64 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the is_domain_name function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("is_domain_name").should == "function_is_domain_name" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_is_domain_name([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if a valid short domain name" do + result = scope.function_is_domain_name(["x.com"]) + result.should(be_true) + end + + it "should return true if the domain is ." do + result = scope.function_is_domain_name(["."]) + result.should(be_true) + end + + it "should return true if the domain is x.com." do + result = scope.function_is_domain_name(["x.com."]) + result.should(be_true) + end + + it "should return true if a valid domain name" do + result = scope.function_is_domain_name(["foo.bar.com"]) + result.should(be_true) + end + + it "should allow domain parts to start with numbers" do + result = scope.function_is_domain_name(["3foo.2bar.com"]) + result.should(be_true) + end + + it "should allow domain to end with a dot" do + result = scope.function_is_domain_name(["3foo.2bar.com."]) + result.should(be_true) + end + + it "should allow a single part domain" do + result = scope.function_is_domain_name(["orange"]) + result.should(be_true) + end + + it "should return false if domain parts start with hyphens" do + result = scope.function_is_domain_name(["-3foo.2bar.com"]) + result.should(be_false) + end + + it "should return true if domain contains hyphens" do + result = scope.function_is_domain_name(["3foo-bar.2bar-fuzz.com"]) + result.should(be_true) + end + + it "should return false if domain name contains spaces" do + result = scope.function_is_domain_name(["not valid"]) + result.should(be_false) + end +end diff --git a/modules/stdlib/spec/functions/is_float_spec.rb b/modules/stdlib/spec/functions/is_float_spec.rb new file mode 100755 index 0000000..b7d73b0 --- /dev/null +++ b/modules/stdlib/spec/functions/is_float_spec.rb @@ -0,0 +1,33 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the is_float function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("is_float").should == "function_is_float" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_is_float([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if a float" do + result = scope.function_is_float(["0.12"]) + result.should(eq(true)) + end + + it "should return false if a string" do + result = scope.function_is_float(["asdf"]) + result.should(eq(false)) + end + + it "should return false if an integer" do + result = scope.function_is_float(["3"]) + result.should(eq(false)) + end + it "should return true if a float is created from an arithmetical operation" do + result = scope.function_is_float([3.2*2]) + result.should(eq(true)) + end +end diff --git a/modules/stdlib/spec/functions/is_function_available.rb b/modules/stdlib/spec/functions/is_function_available.rb new file mode 100755 index 0000000..d5669a7 --- /dev/null +++ b/modules/stdlib/spec/functions/is_function_available.rb @@ -0,0 +1,31 @@ +#!/usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the is_function_available function" do + before :all do + Puppet::Parser::Functions.autoloader.loadall + end + + before :each do + @scope = Puppet::Parser::Scope.new + end + + it "should exist" do + Puppet::Parser::Functions.function("is_function_available").should == "function_is_function_available" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { @scope.function_is_function_available([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return false if a nonexistent function is passed" do + result = @scope.function_is_function_available(['jeff_mccunes_left_sock']) + result.should(eq(false)) + end + + it "should return true if an available function is passed" do + result = @scope.function_is_function_available(['require']) + result.should(eq(true)) + end + +end diff --git a/modules/stdlib/spec/functions/is_hash_spec.rb b/modules/stdlib/spec/functions/is_hash_spec.rb new file mode 100755 index 0000000..bbebf39 --- /dev/null +++ b/modules/stdlib/spec/functions/is_hash_spec.rb @@ -0,0 +1,29 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the is_hash function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("is_hash").should == "function_is_hash" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_is_hash([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if passed a hash" do + result = scope.function_is_hash([{"a"=>1,"b"=>2}]) + result.should(eq(true)) + end + + it "should return false if passed an array" do + result = scope.function_is_hash([["a","b"]]) + result.should(eq(false)) + end + + it "should return false if passed a string" do + result = scope.function_is_hash(["asdf"]) + result.should(eq(false)) + end +end diff --git a/modules/stdlib/spec/functions/is_integer_spec.rb b/modules/stdlib/spec/functions/is_integer_spec.rb new file mode 100755 index 0000000..24141cc --- /dev/null +++ b/modules/stdlib/spec/functions/is_integer_spec.rb @@ -0,0 +1,69 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the is_integer function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("is_integer").should == "function_is_integer" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_is_integer([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if an integer" do + result = scope.function_is_integer(["3"]) + result.should(eq(true)) + end + + it "should return true if a negative integer" do + result = scope.function_is_integer(["-7"]) + result.should(eq(true)) + end + + it "should return false if a float" do + result = scope.function_is_integer(["3.2"]) + result.should(eq(false)) + end + + it "should return false if a string" do + result = scope.function_is_integer(["asdf"]) + result.should(eq(false)) + end + + it "should return true if an integer is created from an arithmetical operation" do + result = scope.function_is_integer([3*2]) + result.should(eq(true)) + end + + it "should return false if an array" do + result = scope.function_is_numeric([["asdf"]]) + result.should(eq(false)) + end + + it "should return false if a hash" do + result = scope.function_is_numeric([{"asdf" => false}]) + result.should(eq(false)) + end + + it "should return false if a boolean" do + result = scope.function_is_numeric([true]) + result.should(eq(false)) + end + + it "should return false if a whitespace is in the string" do + result = scope.function_is_numeric([" -1324"]) + result.should(eq(false)) + end + + it "should return false if it is zero prefixed" do + result = scope.function_is_numeric(["0001234"]) + result.should(eq(false)) + end + + it "should return false if it is wrapped inside an array" do + result = scope.function_is_numeric([[1234]]) + result.should(eq(false)) + end +end diff --git a/modules/stdlib/spec/functions/is_ip_address_spec.rb b/modules/stdlib/spec/functions/is_ip_address_spec.rb new file mode 100755 index 0000000..c0debb3 --- /dev/null +++ b/modules/stdlib/spec/functions/is_ip_address_spec.rb @@ -0,0 +1,39 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the is_ip_address function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("is_ip_address").should == "function_is_ip_address" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_is_ip_address([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if an IPv4 address" do + result = scope.function_is_ip_address(["1.2.3.4"]) + result.should(eq(true)) + end + + it "should return true if a full IPv6 address" do + result = scope.function_is_ip_address(["fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74"]) + result.should(eq(true)) + end + + it "should return true if a compressed IPv6 address" do + result = scope.function_is_ip_address(["fe00::1"]) + result.should(eq(true)) + end + + it "should return false if not valid" do + result = scope.function_is_ip_address(["asdf"]) + result.should(eq(false)) + end + + it "should return false if IP octets out of range" do + result = scope.function_is_ip_address(["1.1.1.300"]) + result.should(eq(false)) + end +end diff --git a/modules/stdlib/spec/functions/is_mac_address_spec.rb b/modules/stdlib/spec/functions/is_mac_address_spec.rb new file mode 100755 index 0000000..ca9c590 --- /dev/null +++ b/modules/stdlib/spec/functions/is_mac_address_spec.rb @@ -0,0 +1,29 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the is_mac_address function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("is_mac_address").should == "function_is_mac_address" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_is_mac_address([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if a valid mac address" do + result = scope.function_is_mac_address(["00:a0:1f:12:7f:a0"]) + result.should(eq(true)) + end + + it "should return false if octets are out of range" do + result = scope.function_is_mac_address(["00:a0:1f:12:7f:g0"]) + result.should(eq(false)) + end + + it "should return false if not valid" do + result = scope.function_is_mac_address(["not valid"]) + result.should(eq(false)) + end +end diff --git a/modules/stdlib/spec/functions/is_numeric_spec.rb b/modules/stdlib/spec/functions/is_numeric_spec.rb new file mode 100755 index 0000000..1df1497 --- /dev/null +++ b/modules/stdlib/spec/functions/is_numeric_spec.rb @@ -0,0 +1,119 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the is_numeric function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("is_numeric").should == "function_is_numeric" + end + + it "should raise a ParseError if there is less than 1 argument" do + lambda { scope.function_is_numeric([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if an integer" do + result = scope.function_is_numeric(["3"]) + result.should(eq(true)) + end + + it "should return true if a float" do + result = scope.function_is_numeric(["3.2"]) + result.should(eq(true)) + end + + it "should return true if an integer is created from an arithmetical operation" do + result = scope.function_is_numeric([3*2]) + result.should(eq(true)) + end + + it "should return true if a float is created from an arithmetical operation" do + result = scope.function_is_numeric([3.2*2]) + result.should(eq(true)) + end + + it "should return false if a string" do + result = scope.function_is_numeric(["asdf"]) + result.should(eq(false)) + end + + it "should return false if an array" do + result = scope.function_is_numeric([["asdf"]]) + result.should(eq(false)) + end + + it "should return false if an array of integers" do + result = scope.function_is_numeric([[1,2,3,4]]) + result.should(eq(false)) + end + + it "should return false if a hash" do + result = scope.function_is_numeric([{"asdf" => false}]) + result.should(eq(false)) + end + + it "should return false if a hash with numbers in it" do + result = scope.function_is_numeric([{1 => 2}]) + result.should(eq(false)) + end + + it "should return false if a boolean" do + result = scope.function_is_numeric([true]) + result.should(eq(false)) + end + + it "should return true if a negative float with exponent" do + result = scope.function_is_numeric(["-342.2315e-12"]) + result.should(eq(true)) + end + + it "should return false if a negative integer with whitespaces before/after the dash" do + result = scope.function_is_numeric([" - 751"]) + result.should(eq(false)) + end + +# it "should return true if a hexadecimal" do +# result = scope.function_is_numeric(["0x52F8c"]) +# result.should(eq(true)) +# end +# +# it "should return true if a hexadecimal with uppercase 0X prefix" do +# result = scope.function_is_numeric(["0X52F8c"]) +# result.should(eq(true)) +# end +# +# it "should return false if a hexadecimal without a prefix" do +# result = scope.function_is_numeric(["52F8c"]) +# result.should(eq(false)) +# end +# +# it "should return true if a octal" do +# result = scope.function_is_numeric(["0751"]) +# result.should(eq(true)) +# end +# +# it "should return true if a negative hexadecimal" do +# result = scope.function_is_numeric(["-0x52F8c"]) +# result.should(eq(true)) +# end +# +# it "should return true if a negative octal" do +# result = scope.function_is_numeric(["-0751"]) +# result.should(eq(true)) +# end +# +# it "should return false if a negative octal with whitespaces before/after the dash" do +# result = scope.function_is_numeric([" - 0751"]) +# result.should(eq(false)) +# end +# +# it "should return false if a bad hexadecimal" do +# result = scope.function_is_numeric(["0x23d7g"]) +# result.should(eq(false)) +# end +# +# it "should return false if a bad octal" do +# result = scope.function_is_numeric(["0287"]) +# result.should(eq(false)) +# end +end diff --git a/modules/stdlib/spec/functions/is_string_spec.rb b/modules/stdlib/spec/functions/is_string_spec.rb new file mode 100755 index 0000000..3756bea --- /dev/null +++ b/modules/stdlib/spec/functions/is_string_spec.rb @@ -0,0 +1,34 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the is_string function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("is_string").should == "function_is_string" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_is_string([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if a string" do + result = scope.function_is_string(["asdf"]) + result.should(eq(true)) + end + + it "should return false if an integer" do + result = scope.function_is_string(["3"]) + result.should(eq(false)) + end + + it "should return false if a float" do + result = scope.function_is_string(["3.23"]) + result.should(eq(false)) + end + + it "should return false if an array" do + result = scope.function_is_string([["a","b","c"]]) + result.should(eq(false)) + end +end diff --git a/modules/stdlib/spec/functions/join_keys_to_values_spec.rb b/modules/stdlib/spec/functions/join_keys_to_values_spec.rb new file mode 100755 index 0000000..a52fb71 --- /dev/null +++ b/modules/stdlib/spec/functions/join_keys_to_values_spec.rb @@ -0,0 +1,40 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the join_keys_to_values function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("join_keys_to_values").should == "function_join_keys_to_values" + end + + it "should raise a ParseError if there are fewer than two arguments" do + lambda { scope.function_join_keys_to_values([{}]) }.should raise_error Puppet::ParseError + end + + it "should raise a ParseError if there are greater than two arguments" do + lambda { scope.function_join_keys_to_values([{}, 'foo', 'bar']) }.should raise_error Puppet::ParseError + end + + it "should raise a TypeError if the first argument is an array" do + lambda { scope.function_join_keys_to_values([[1,2], ',']) }.should raise_error TypeError + end + + it "should raise a TypeError if the second argument is an array" do + lambda { scope.function_join_keys_to_values([{}, [1,2]]) }.should raise_error TypeError + end + + it "should raise a TypeError if the second argument is a number" do + lambda { scope.function_join_keys_to_values([{}, 1]) }.should raise_error TypeError + end + + it "should return an empty array given an empty hash" do + result = scope.function_join_keys_to_values([{}, ":"]) + result.should == [] + end + + it "should join hash's keys to its values" do + result = scope.function_join_keys_to_values([{'a'=>1,2=>'foo',:b=>nil}, ":"]) + result.should =~ ['a:1','2:foo','b:'] + end +end diff --git a/modules/stdlib/spec/functions/join_spec.rb b/modules/stdlib/spec/functions/join_spec.rb new file mode 100755 index 0000000..aafa1a7 --- /dev/null +++ b/modules/stdlib/spec/functions/join_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the join function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("join").should == "function_join" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_join([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should join an array into a string" do + result = scope.function_join([["a","b","c"], ":"]) + result.should(eq("a:b:c")) + end +end diff --git a/modules/stdlib/spec/functions/keys_spec.rb b/modules/stdlib/spec/functions/keys_spec.rb new file mode 100755 index 0000000..fdd7a70 --- /dev/null +++ b/modules/stdlib/spec/functions/keys_spec.rb @@ -0,0 +1,21 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the keys function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("keys").should == "function_keys" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_keys([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return an array of keys when given a hash" do + result = scope.function_keys([{'a'=>1, 'b'=>2}]) + # =~ performs 'array with same elements' (set) matching + # For more info see RSpec::Matchers::MatchArray + result.should =~ ['a','b'] + end +end diff --git a/modules/stdlib/spec/functions/loadyaml_spec.rb b/modules/stdlib/spec/functions/loadyaml_spec.rb new file mode 100755 index 0000000..fe16318 --- /dev/null +++ b/modules/stdlib/spec/functions/loadyaml_spec.rb @@ -0,0 +1,25 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the loadyaml function" do + include PuppetlabsSpec::Files + + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("loadyaml").should == "function_loadyaml" + end + + it "should raise a ParseError if there is less than 1 arguments" do + expect { scope.function_loadyaml([]) }.to raise_error(Puppet::ParseError) + end + + it "should convert YAML file to a data structure" do + yaml_file = tmpfilename ('yamlfile') + File.open(yaml_file, 'w') do |fh| + fh.write("---\n aaa: 1\n bbb: 2\n ccc: 3\n ddd: 4\n") + end + result = scope.function_loadyaml([yaml_file]) + result.should == {"aaa" => 1, "bbb" => 2, "ccc" => 3, "ddd" => 4 } + end +end diff --git a/modules/stdlib/spec/functions/lstrip_spec.rb b/modules/stdlib/spec/functions/lstrip_spec.rb new file mode 100755 index 0000000..b280ae7 --- /dev/null +++ b/modules/stdlib/spec/functions/lstrip_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the lstrip function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("lstrip").should == "function_lstrip" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_lstrip([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should lstrip a string" do + result = scope.function_lstrip([" asdf"]) + result.should(eq('asdf')) + end +end diff --git a/modules/stdlib/spec/functions/max_spec.rb b/modules/stdlib/spec/functions/max_spec.rb new file mode 100755 index 0000000..ff6f2b3 --- /dev/null +++ b/modules/stdlib/spec/functions/max_spec.rb @@ -0,0 +1,27 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe "the max function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("max").should == "function_max" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_max([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should be able to compare strings" do + scope.function_max(["albatross","dog","horse"]).should(eq("horse")) + end + + it "should be able to compare numbers" do + scope.function_max([6,8,4]).should(eq(8)) + end + + it "should be able to compare a number with a stringified number" do + scope.function_max([1,"2"]).should(eq("2")) + end +end diff --git a/modules/stdlib/spec/functions/member_spec.rb b/modules/stdlib/spec/functions/member_spec.rb new file mode 100755 index 0000000..6e9a023 --- /dev/null +++ b/modules/stdlib/spec/functions/member_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the member function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("member").should == "function_member" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_member([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if a member is in an array" do + result = scope.function_member([["a","b","c"], "a"]) + result.should(eq(true)) + end + + it "should return false if a member is not in an array" do + result = scope.function_member([["a","b","c"], "d"]) + result.should(eq(false)) + end +end diff --git a/modules/stdlib/spec/functions/merge_spec.rb b/modules/stdlib/spec/functions/merge_spec.rb new file mode 100755 index 0000000..15a5d94 --- /dev/null +++ b/modules/stdlib/spec/functions/merge_spec.rb @@ -0,0 +1,52 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:merge) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + describe 'when calling merge from puppet' do + it "should not compile when no arguments are passed" do + pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ + Puppet[:code] = '$x = merge()' + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /wrong number of arguments/) + end + + it "should not compile when 1 argument is passed" do + pending("Fails on 2.6.x, see bug #15912") if Puppet.version =~ /^2\.6\./ + Puppet[:code] = "$my_hash={'one' => 1}\n$x = merge($my_hash)" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /wrong number of arguments/) + end + end + + describe 'when calling merge on the scope instance' do + it 'should require all parameters are hashes' do + expect { new_hash = scope.function_merge([{}, '2'])}.to raise_error(Puppet::ParseError, /unexpected argument type String/) + expect { new_hash = scope.function_merge([{}, 2])}.to raise_error(Puppet::ParseError, /unexpected argument type Fixnum/) + end + + it 'should accept empty strings as puppet undef' do + expect { new_hash = scope.function_merge([{}, ''])}.not_to raise_error + end + + it 'should be able to merge two hashes' do + new_hash = scope.function_merge([{'one' => '1', 'two' => '1'}, {'two' => '2', 'three' => '2'}]) + new_hash['one'].should == '1' + new_hash['two'].should == '2' + new_hash['three'].should == '2' + end + + it 'should merge multiple hashes' do + hash = scope.function_merge([{'one' => 1}, {'one' => '2'}, {'one' => '3'}]) + hash['one'].should == '3' + end + + it 'should accept empty hashes' do + scope.function_merge([{},{},{}]).should == {} + end + end +end diff --git a/modules/stdlib/spec/functions/min_spec.rb b/modules/stdlib/spec/functions/min_spec.rb new file mode 100755 index 0000000..71d593e --- /dev/null +++ b/modules/stdlib/spec/functions/min_spec.rb @@ -0,0 +1,27 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe "the min function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("min").should == "function_min" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_min([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should be able to compare strings" do + scope.function_min(["albatross","dog","horse"]).should(eq("albatross")) + end + + it "should be able to compare numbers" do + scope.function_min([6,8,4]).should(eq(4)) + end + + it "should be able to compare a number with a stringified number" do + scope.function_min([1,"2"]).should(eq(1)) + end +end diff --git a/modules/stdlib/spec/functions/num2bool_spec.rb b/modules/stdlib/spec/functions/num2bool_spec.rb new file mode 100755 index 0000000..b56196d --- /dev/null +++ b/modules/stdlib/spec/functions/num2bool_spec.rb @@ -0,0 +1,67 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the num2bool function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("num2bool").should == "function_num2bool" + end + + it "should raise a ParseError if there are no arguments" do + lambda { scope.function_num2bool([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should raise a ParseError if there are more than 1 arguments" do + lambda { scope.function_num2bool(["foo","bar"]) }.should( raise_error(Puppet::ParseError)) + end + + it "should raise a ParseError if passed something non-numeric" do + lambda { scope.function_num2bool(["xyzzy"]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return true if passed string 1" do + result = scope.function_num2bool(["1"]) + result.should(be_true) + end + + it "should return true if passed string 1.5" do + result = scope.function_num2bool(["1.5"]) + result.should(be_true) + end + + it "should return true if passed number 1" do + result = scope.function_num2bool([1]) + result.should(be_true) + end + + it "should return false if passed string 0" do + result = scope.function_num2bool(["0"]) + result.should(be_false) + end + + it "should return false if passed number 0" do + result = scope.function_num2bool([0]) + result.should(be_false) + end + + it "should return false if passed string -1" do + result = scope.function_num2bool(["-1"]) + result.should(be_false) + end + + it "should return false if passed string -1.5" do + result = scope.function_num2bool(["-1.5"]) + result.should(be_false) + end + + it "should return false if passed number -1" do + result = scope.function_num2bool([-1]) + result.should(be_false) + end + + it "should return false if passed float -1.5" do + result = scope.function_num2bool([-1.5]) + result.should(be_false) + end +end diff --git a/modules/stdlib/spec/functions/parsejson_spec.rb b/modules/stdlib/spec/functions/parsejson_spec.rb new file mode 100755 index 0000000..f179ac1 --- /dev/null +++ b/modules/stdlib/spec/functions/parsejson_spec.rb @@ -0,0 +1,22 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the parsejson function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("parsejson").should == "function_parsejson" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_parsejson([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should convert JSON to a data structure" do + json = <<-EOS +["aaa","bbb","ccc"] +EOS + result = scope.function_parsejson([json]) + result.should(eq(['aaa','bbb','ccc'])) + end +end diff --git a/modules/stdlib/spec/functions/parseyaml_spec.rb b/modules/stdlib/spec/functions/parseyaml_spec.rb new file mode 100755 index 0000000..0c7aea8 --- /dev/null +++ b/modules/stdlib/spec/functions/parseyaml_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the parseyaml function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("parseyaml").should == "function_parseyaml" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_parseyaml([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should convert YAML to a data structure" do + yaml = <<-EOS +- aaa +- bbb +- ccc +EOS + result = scope.function_parseyaml([yaml]) + result.should(eq(['aaa','bbb','ccc'])) + end +end diff --git a/modules/stdlib/spec/functions/pick_default_spec.rb b/modules/stdlib/spec/functions/pick_default_spec.rb new file mode 100755 index 0000000..c9235b5 --- /dev/null +++ b/modules/stdlib/spec/functions/pick_default_spec.rb @@ -0,0 +1,58 @@ +#!/usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the pick_default function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("pick_default").should == "function_pick_default" + end + + it 'should return the correct value' do + scope.function_pick_default(['first', 'second']).should == 'first' + end + + it 'should return the correct value if the first value is empty' do + scope.function_pick_default(['', 'second']).should == 'second' + end + + it 'should skip empty string values' do + scope.function_pick_default(['', 'first']).should == 'first' + end + + it 'should skip :undef values' do + scope.function_pick_default([:undef, 'first']).should == 'first' + end + + it 'should skip :undefined values' do + scope.function_pick_default([:undefined, 'first']).should == 'first' + end + + it 'should return the empty string if it is the last possibility' do + scope.function_pick_default([:undef, :undefined, '']).should == '' + end + + it 'should return :undef if it is the last possibility' do + scope.function_pick_default(['', :undefined, :undef]).should == :undef + end + + it 'should return :undefined if it is the last possibility' do + scope.function_pick_default([:undef, '', :undefined]).should == :undefined + end + + it 'should return the empty string if it is the only possibility' do + scope.function_pick_default(['']).should == '' + end + + it 'should return :undef if it is the only possibility' do + scope.function_pick_default([:undef]).should == :undef + end + + it 'should return :undefined if it is the only possibility' do + scope.function_pick_default([:undefined]).should == :undefined + end + + it 'should error if no values are passed' do + expect { scope.function_pick_default([]) }.to raise_error(Puppet::Error, /Must receive at least one argument./) + end +end diff --git a/modules/stdlib/spec/functions/pick_spec.rb b/modules/stdlib/spec/functions/pick_spec.rb new file mode 100755 index 0000000..f53fa80 --- /dev/null +++ b/modules/stdlib/spec/functions/pick_spec.rb @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the pick function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("pick").should == "function_pick" + end + + it 'should return the correct value' do + scope.function_pick(['first', 'second']).should == 'first' + end + + it 'should return the correct value if the first value is empty' do + scope.function_pick(['', 'second']).should == 'second' + end + + it 'should remove empty string values' do + scope.function_pick(['', 'first']).should == 'first' + end + + it 'should remove :undef values' do + scope.function_pick([:undef, 'first']).should == 'first' + end + + it 'should remove :undefined values' do + scope.function_pick([:undefined, 'first']).should == 'first' + end + + it 'should error if no values are passed' do + expect { scope.function_pick([]) }.to( raise_error(Puppet::ParseError, "pick(): must receive at least one non empty value")) + end +end diff --git a/modules/stdlib/spec/functions/prefix_spec.rb b/modules/stdlib/spec/functions/prefix_spec.rb new file mode 100755 index 0000000..6e8ddc5 --- /dev/null +++ b/modules/stdlib/spec/functions/prefix_spec.rb @@ -0,0 +1,28 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the prefix function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "raises a ParseError if there is less than 1 arguments" do + expect { scope.function_prefix([]) }.to raise_error(Puppet::ParseError, /number of arguments/) + end + + it "raises an error if the first argument is not an array" do + expect { + scope.function_prefix([Object.new]) + }.to raise_error(Puppet::ParseError, /expected first argument to be an Array/) + end + + + it "raises an error if the second argument is not a string" do + expect { + scope.function_prefix([['first', 'second'], 42]) + }.to raise_error(Puppet::ParseError, /expected second argument to be a String/) + end + + it "returns a prefixed array" do + result = scope.function_prefix([['a','b','c'], 'p']) + result.should(eq(['pa','pb','pc'])) + end +end diff --git a/modules/stdlib/spec/functions/range_spec.rb b/modules/stdlib/spec/functions/range_spec.rb new file mode 100755 index 0000000..0e1ad37 --- /dev/null +++ b/modules/stdlib/spec/functions/range_spec.rb @@ -0,0 +1,70 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the range function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "exists" do + Puppet::Parser::Functions.function("range").should == "function_range" + end + + it "raises a ParseError if there is less than 1 arguments" do + expect { scope.function_range([]) }.to raise_error Puppet::ParseError, /Wrong number of arguments.*0 for 1/ + end + + describe 'with a letter range' do + it "returns a letter range" do + result = scope.function_range(["a","d"]) + result.should eq ['a','b','c','d'] + end + + it "returns a letter range given a step of 1" do + result = scope.function_range(["a","d","1"]) + result.should eq ['a','b','c','d'] + end + + it "returns a stepped letter range" do + result = scope.function_range(["a","d","2"]) + result.should eq ['a','c'] + end + + it "returns a stepped letter range given a negative step" do + result = scope.function_range(["a","d","-2"]) + result.should eq ['a','c'] + end + end + + describe 'with a number range' do + it "returns a number range" do + result = scope.function_range(["1","4"]) + result.should eq [1,2,3,4] + end + + it "returns a number range given a step of 1" do + result = scope.function_range(["1","4","1"]) + result.should eq [1,2,3,4] + end + + it "returns a stepped number range" do + result = scope.function_range(["1","4","2"]) + result.should eq [1,3] + end + + it "returns a stepped number range given a negative step" do + result = scope.function_range(["1","4","-2"]) + result.should eq [1,3] + end + end + + describe 'with a numeric-like string range' do + it "works with padded hostname like strings" do + expected = ("host01".."host10").to_a + scope.function_range(["host01","host10"]).should eq expected + end + + it "coerces zero padded digits to integers" do + expected = (0..10).to_a + scope.function_range(["00", "10"]).should eq expected + end + end +end diff --git a/modules/stdlib/spec/functions/reject_spec.rb b/modules/stdlib/spec/functions/reject_spec.rb new file mode 100755 index 0000000..f2cb741 --- /dev/null +++ b/modules/stdlib/spec/functions/reject_spec.rb @@ -0,0 +1,20 @@ +#!/usr/bin/env ruby + +require 'spec_helper' + +describe "the reject function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("reject").should == "function_reject" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_reject([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should reject contents from an array" do + result = scope.function_reject([["1111", "aaabbb","bbbccc","dddeee"], "bbb"]) + result.should(eq(["1111", "dddeee"])) + end +end diff --git a/modules/stdlib/spec/functions/reverse_spec.rb b/modules/stdlib/spec/functions/reverse_spec.rb new file mode 100755 index 0000000..1b59206 --- /dev/null +++ b/modules/stdlib/spec/functions/reverse_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the reverse function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("reverse").should == "function_reverse" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_reverse([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should reverse a string" do + result = scope.function_reverse(["asdfghijkl"]) + result.should(eq('lkjihgfdsa')) + end +end diff --git a/modules/stdlib/spec/functions/rstrip_spec.rb b/modules/stdlib/spec/functions/rstrip_spec.rb new file mode 100755 index 0000000..d90de1d --- /dev/null +++ b/modules/stdlib/spec/functions/rstrip_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the rstrip function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("rstrip").should == "function_rstrip" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_rstrip([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should rstrip a string" do + result = scope.function_rstrip(["asdf "]) + result.should(eq('asdf')) + end + + it "should rstrip each element in an array" do + result = scope.function_rstrip([["a ","b ", "c "]]) + result.should(eq(['a','b','c'])) + end +end diff --git a/modules/stdlib/spec/functions/shuffle_spec.rb b/modules/stdlib/spec/functions/shuffle_spec.rb new file mode 100755 index 0000000..93346d5 --- /dev/null +++ b/modules/stdlib/spec/functions/shuffle_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the shuffle function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("shuffle").should == "function_shuffle" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_shuffle([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should shuffle a string and the result should be the same size" do + result = scope.function_shuffle(["asdf"]) + result.size.should(eq(4)) + end + + it "should shuffle a string but the sorted contents should still be the same" do + result = scope.function_shuffle(["adfs"]) + result.split("").sort.join("").should(eq("adfs")) + end +end diff --git a/modules/stdlib/spec/functions/size_spec.rb b/modules/stdlib/spec/functions/size_spec.rb new file mode 100755 index 0000000..b1c435a --- /dev/null +++ b/modules/stdlib/spec/functions/size_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the size function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("size").should == "function_size" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_size([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return the size of a string" do + result = scope.function_size(["asdf"]) + result.should(eq(4)) + end + + it "should return the size of an array" do + result = scope.function_size([["a","b","c"]]) + result.should(eq(3)) + end +end diff --git a/modules/stdlib/spec/functions/sort_spec.rb b/modules/stdlib/spec/functions/sort_spec.rb new file mode 100755 index 0000000..3187a5a --- /dev/null +++ b/modules/stdlib/spec/functions/sort_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the sort function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("sort").should == "function_sort" + end + + it "should raise a ParseError if there is not 1 arguments" do + lambda { scope.function_sort(['','']) }.should( raise_error(Puppet::ParseError)) + end + + it "should sort an array" do + result = scope.function_sort([["a","c","b"]]) + result.should(eq(['a','b','c'])) + end + + it "should sort a string" do + result = scope.function_sort(["acb"]) + result.should(eq('abc')) + end +end diff --git a/modules/stdlib/spec/functions/squeeze_spec.rb b/modules/stdlib/spec/functions/squeeze_spec.rb new file mode 100755 index 0000000..60e5a30 --- /dev/null +++ b/modules/stdlib/spec/functions/squeeze_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the squeeze function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("squeeze").should == "function_squeeze" + end + + it "should raise a ParseError if there is less than 2 arguments" do + lambda { scope.function_squeeze([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should squeeze a string" do + result = scope.function_squeeze(["aaabbbbcccc"]) + result.should(eq('abc')) + end + + it "should squeeze all elements in an array" do + result = scope.function_squeeze([["aaabbbbcccc","dddfff"]]) + result.should(eq(['abc','df'])) + end +end diff --git a/modules/stdlib/spec/functions/str2bool_spec.rb b/modules/stdlib/spec/functions/str2bool_spec.rb new file mode 100755 index 0000000..73c09c7 --- /dev/null +++ b/modules/stdlib/spec/functions/str2bool_spec.rb @@ -0,0 +1,31 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the str2bool function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("str2bool").should == "function_str2bool" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_str2bool([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should convert string 'true' to true" do + result = scope.function_str2bool(["true"]) + result.should(eq(true)) + end + + it "should convert string 'undef' to false" do + result = scope.function_str2bool(["undef"]) + result.should(eq(false)) + end + + it "should return the boolean it was called with" do + result = scope.function_str2bool([true]) + result.should(eq(true)) + result = scope.function_str2bool([false]) + result.should(eq(false)) + end +end diff --git a/modules/stdlib/spec/functions/str2saltedsha512_spec.rb b/modules/stdlib/spec/functions/str2saltedsha512_spec.rb new file mode 100755 index 0000000..df8fb8e --- /dev/null +++ b/modules/stdlib/spec/functions/str2saltedsha512_spec.rb @@ -0,0 +1,45 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the str2saltedsha512 function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("str2saltedsha512").should == "function_str2saltedsha512" + end + + it "should raise a ParseError if there is less than 1 argument" do + expect { scope.function_str2saltedsha512([]) }.to( raise_error(Puppet::ParseError) ) + end + + it "should raise a ParseError if there is more than 1 argument" do + expect { scope.function_str2saltedsha512(['foo', 'bar', 'baz']) }.to( raise_error(Puppet::ParseError) ) + end + + it "should return a salted-sha512 password hash 136 characters in length" do + result = scope.function_str2saltedsha512(["password"]) + result.length.should(eq(136)) + end + + it "should raise an error if you pass a non-string password" do + expect { scope.function_str2saltedsha512([1234]) }.to( raise_error(Puppet::ParseError) ) + end + + it "should generate a valid password" do + # Allow the function to generate a password based on the string 'password' + password_hash = scope.function_str2saltedsha512(["password"]) + + # Separate the Salt and Password from the Password Hash + salt = password_hash[0..7] + password = password_hash[8..-1] + + # Convert the Salt and Password from Hex to Binary Data + str_salt = Array(salt.lines).pack('H*') + str_password = Array(password.lines).pack('H*') + + # Combine the Binary Salt with 'password' and compare the end result + saltedpass = Digest::SHA512.digest(str_salt + 'password') + result = (str_salt + saltedpass).unpack('H*')[0] + result.should == password_hash + end +end diff --git a/modules/stdlib/spec/functions/strftime_spec.rb b/modules/stdlib/spec/functions/strftime_spec.rb new file mode 100755 index 0000000..df42b6f --- /dev/null +++ b/modules/stdlib/spec/functions/strftime_spec.rb @@ -0,0 +1,29 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the strftime function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("strftime").should == "function_strftime" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_strftime([]) }.should( raise_error(Puppet::ParseError)) + end + + it "using %s should be higher then when I wrote this test" do + result = scope.function_strftime(["%s"]) + result.to_i.should(be > 1311953157) + end + + it "using %s should be lower then 1.5 trillion" do + result = scope.function_strftime(["%s"]) + result.to_i.should(be < 1500000000) + end + + it "should return a date when given %Y-%m-%d" do + result = scope.function_strftime(["%Y-%m-%d"]) + result.should =~ /^\d{4}-\d{2}-\d{2}$/ + end +end diff --git a/modules/stdlib/spec/functions/strip_spec.rb b/modules/stdlib/spec/functions/strip_spec.rb new file mode 100755 index 0000000..fccdd26 --- /dev/null +++ b/modules/stdlib/spec/functions/strip_spec.rb @@ -0,0 +1,18 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the strip function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + it "should exist" do + Puppet::Parser::Functions.function("strip").should == "function_strip" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_strip([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should strip a string" do + result = scope.function_strip([" ab cd "]) + result.should(eq('ab cd')) + end +end diff --git a/modules/stdlib/spec/functions/suffix_spec.rb b/modules/stdlib/spec/functions/suffix_spec.rb new file mode 100755 index 0000000..89ba3b8 --- /dev/null +++ b/modules/stdlib/spec/functions/suffix_spec.rb @@ -0,0 +1,27 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the suffix function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "raises a ParseError if there is less than 1 arguments" do + expect { scope.function_suffix([]) }.to raise_error(Puppet::ParseError, /number of arguments/) + end + + it "raises an error if the first argument is not an array" do + expect { + scope.function_suffix([Object.new]) + }.to raise_error(Puppet::ParseError, /expected first argument to be an Array/) + end + + it "raises an error if the second argument is not a string" do + expect { + scope.function_suffix([['first', 'second'], 42]) + }.to raise_error(Puppet::ParseError, /expected second argument to be a String/) + end + + it "returns a suffixed array" do + result = scope.function_suffix([['a','b','c'], 'p']) + result.should(eq(['ap','bp','cp'])) + end +end diff --git a/modules/stdlib/spec/functions/swapcase_spec.rb b/modules/stdlib/spec/functions/swapcase_spec.rb new file mode 100755 index 0000000..808b415 --- /dev/null +++ b/modules/stdlib/spec/functions/swapcase_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the swapcase function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("swapcase").should == "function_swapcase" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_swapcase([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should swapcase a string" do + result = scope.function_swapcase(["aaBBccDD"]) + result.should(eq('AAbbCCdd')) + end +end diff --git a/modules/stdlib/spec/functions/time_spec.rb b/modules/stdlib/spec/functions/time_spec.rb new file mode 100755 index 0000000..e9fb76e --- /dev/null +++ b/modules/stdlib/spec/functions/time_spec.rb @@ -0,0 +1,29 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the time function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("time").should == "function_time" + end + + it "should raise a ParseError if there is more than 2 arguments" do + lambda { scope.function_time(['','']) }.should( raise_error(Puppet::ParseError)) + end + + it "should return a number" do + result = scope.function_time([]) + result.should be_an(Integer) + end + + it "should be higher then when I wrote this test" do + result = scope.function_time([]) + result.should(be > 1311953157) + end + + it "should be lower then 1.5 trillion" do + result = scope.function_time([]) + result.should(be < 1500000000) + end +end diff --git a/modules/stdlib/spec/functions/to_bytes_spec.rb b/modules/stdlib/spec/functions/to_bytes_spec.rb new file mode 100755 index 0000000..d1ea4c8 --- /dev/null +++ b/modules/stdlib/spec/functions/to_bytes_spec.rb @@ -0,0 +1,58 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe "the to_bytes function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("to_bytes").should == "function_to_bytes" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_to_bytes([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should convert kB to B" do + result = scope.function_to_bytes(["4 kB"]) + result.should(eq(4096)) + end + + it "should work without B in unit" do + result = scope.function_to_bytes(["4 k"]) + result.should(eq(4096)) + end + + it "should work without a space before unit" do + result = scope.function_to_bytes(["4k"]) + result.should(eq(4096)) + end + + it "should work without a unit" do + result = scope.function_to_bytes(["5678"]) + result.should(eq(5678)) + end + + it "should convert fractions" do + result = scope.function_to_bytes(["1.5 kB"]) + result.should(eq(1536)) + end + + it "should convert scientific notation" do + result = scope.function_to_bytes(["1.5e2 B"]) + result.should(eq(150)) + end + + it "should do nothing with a positive number" do + result = scope.function_to_bytes([5678]) + result.should(eq(5678)) + end + + it "should should raise a ParseError if input isn't a number" do + lambda { scope.function_to_bytes(["foo"]) }.should( raise_error(Puppet::ParseError)) + end + + it "should should raise a ParseError if prefix is unknown" do + lambda { scope.function_to_bytes(["5 uB"]) }.should( raise_error(Puppet::ParseError)) + end +end diff --git a/modules/stdlib/spec/functions/type_spec.rb b/modules/stdlib/spec/functions/type_spec.rb new file mode 100755 index 0000000..8fec88f --- /dev/null +++ b/modules/stdlib/spec/functions/type_spec.rb @@ -0,0 +1,43 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the type function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + it "should exist" do + Puppet::Parser::Functions.function("type").should == "function_type" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_type([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return string when given a string" do + result = scope.function_type(["aaabbbbcccc"]) + result.should(eq('string')) + end + + it "should return array when given an array" do + result = scope.function_type([["aaabbbbcccc","asdf"]]) + result.should(eq('array')) + end + + it "should return hash when given a hash" do + result = scope.function_type([{"a"=>1,"b"=>2}]) + result.should(eq('hash')) + end + + it "should return integer when given an integer" do + result = scope.function_type(["1"]) + result.should(eq('integer')) + end + + it "should return float when given a float" do + result = scope.function_type(["1.34"]) + result.should(eq('float')) + end + + it "should return boolean when given a boolean" do + result = scope.function_type([true]) + result.should(eq('boolean')) + end +end diff --git a/modules/stdlib/spec/functions/union_spec.rb b/modules/stdlib/spec/functions/union_spec.rb new file mode 100755 index 0000000..0d282ca --- /dev/null +++ b/modules/stdlib/spec/functions/union_spec.rb @@ -0,0 +1,19 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the union function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("union").should == "function_union" + end + + it "should raise a ParseError if there are fewer than 2 arguments" do + lambda { scope.function_union([]) }.should( raise_error(Puppet::ParseError) ) + end + + it "should join two arrays together" do + result = scope.function_union([["a","b","c"],["b","c","d"]]) + result.should(eq(["a","b","c","d"])) + end +end diff --git a/modules/stdlib/spec/functions/unique_spec.rb b/modules/stdlib/spec/functions/unique_spec.rb new file mode 100755 index 0000000..5d48d49 --- /dev/null +++ b/modules/stdlib/spec/functions/unique_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the unique function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("unique").should == "function_unique" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_unique([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should remove duplicate elements in a string" do + result = scope.function_unique(["aabbc"]) + result.should(eq('abc')) + end + + it "should remove duplicate elements in an array" do + result = scope.function_unique([["a","a","b","b","c"]]) + result.should(eq(['a','b','c'])) + end +end diff --git a/modules/stdlib/spec/functions/upcase_spec.rb b/modules/stdlib/spec/functions/upcase_spec.rb new file mode 100755 index 0000000..5db5513 --- /dev/null +++ b/modules/stdlib/spec/functions/upcase_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the upcase function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("upcase").should == "function_upcase" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_upcase([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should upcase a string" do + result = scope.function_upcase(["abc"]) + result.should(eq('ABC')) + end + + it "should do nothing if a string is already upcase" do + result = scope.function_upcase(["ABC"]) + result.should(eq('ABC')) + end +end diff --git a/modules/stdlib/spec/functions/uriescape_spec.rb b/modules/stdlib/spec/functions/uriescape_spec.rb new file mode 100755 index 0000000..7211c88 --- /dev/null +++ b/modules/stdlib/spec/functions/uriescape_spec.rb @@ -0,0 +1,24 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the uriescape function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("uriescape").should == "function_uriescape" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_uriescape([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should uriescape a string" do + result = scope.function_uriescape([":/?#[]@!$&'()*+,;= \"{}"]) + result.should(eq(':/?%23[]@!$&\'()*+,;=%20%22%7B%7D')) + end + + it "should do nothing if a string is already safe" do + result = scope.function_uriescape(["ABCdef"]) + result.should(eq('ABCdef')) + end +end diff --git a/modules/stdlib/spec/functions/validate_absolute_path_spec.rb b/modules/stdlib/spec/functions/validate_absolute_path_spec.rb new file mode 100755 index 0000000..342ae84 --- /dev/null +++ b/modules/stdlib/spec/functions/validate_absolute_path_spec.rb @@ -0,0 +1,84 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:validate_absolute_path) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + # The subject of these examples is the method itself. + subject do + # This makes sure the function is loaded within each test + function_name = Puppet::Parser::Functions.function(:validate_absolute_path) + scope.method(function_name) + end + + describe "Valid Paths" do + def self.valid_paths + %w{ + C:/ + C:\\ + C:\\WINDOWS\\System32 + C:/windows/system32 + X:/foo/bar + X:\\foo\\bar + /var/tmp + /var/lib/puppet + /var/opt/../lib/puppet + } + end + + context "Without Puppet::Util.absolute_path? (e.g. Puppet <= 2.6)" do + before :each do + # The intent here is to mock Puppet to behave like Puppet 2.6 does. + # Puppet 2.6 does not have the absolute_path? method. This is only a + # convenience test, stdlib should be run with the Puppet 2.6.x in the + # $LOAD_PATH in addition to 2.7.x and master. + Puppet::Util.expects(:respond_to?).with(:absolute_path?).returns(false) + end + valid_paths.each do |path| + it "validate_absolute_path(#{path.inspect}) should not fail" do + expect { subject.call [path] }.not_to raise_error + end + end + end + + context "Puppet without mocking" do + valid_paths.each do |path| + it "validate_absolute_path(#{path.inspect}) should not fail" do + expect { subject.call [path] }.not_to raise_error + end + end + end + end + + describe 'Invalid paths' do + context 'Garbage inputs' do + [ + nil, + [ nil ], + { 'foo' => 'bar' }, + { }, + '', + ].each do |path| + it "validate_absolute_path(#{path.inspect}) should fail" do + expect { subject.call [path] }.to raise_error Puppet::ParseError + end + end + end + + context 'Relative paths' do + %w{ + relative1 + . + .. + ./foo + ../foo + etc/puppetlabs/puppet + opt/puppet/bin + }.each do |path| + it "validate_absolute_path(#{path.inspect}) should fail" do + expect { subject.call [path] }.to raise_error Puppet::ParseError + end + end + end + end +end diff --git a/modules/stdlib/spec/functions/validate_array_spec.rb b/modules/stdlib/spec/functions/validate_array_spec.rb new file mode 100755 index 0000000..4b31cfd --- /dev/null +++ b/modules/stdlib/spec/functions/validate_array_spec.rb @@ -0,0 +1,38 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:validate_array) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + describe 'when calling validate_array from puppet' do + + %w{ true false }.each do |the_string| + it "should not compile when #{the_string} is a string" do + Puppet[:code] = "validate_array('#{the_string}')" + expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not an Array/) + end + + it "should not compile when #{the_string} is a bare word" do + Puppet[:code] = "validate_array(#{the_string})" + expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not an Array/) + end + end + + it "should compile when multiple array arguments are passed" do + Puppet[:code] = <<-'ENDofPUPPETcode' + $foo = [ ] + $bar = [ 'one', 'two' ] + validate_array($foo, $bar) + ENDofPUPPETcode + scope.compiler.compile + end + + it "should not compile when an undef variable is passed" do + Puppet[:code] = <<-'ENDofPUPPETcode' + $foo = undef + validate_array($foo) + ENDofPUPPETcode + expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not an Array/) + end + end +end diff --git a/modules/stdlib/spec/functions/validate_augeas_spec.rb b/modules/stdlib/spec/functions/validate_augeas_spec.rb new file mode 100755 index 0000000..c695ba2 --- /dev/null +++ b/modules/stdlib/spec/functions/validate_augeas_spec.rb @@ -0,0 +1,103 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:validate_augeas), :if => Puppet.features.augeas? do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + # The subject of these examplres is the method itself. + subject do + # This makes sure the function is loaded within each test + function_name = Puppet::Parser::Functions.function(:validate_augeas) + scope.method(function_name) + end + + context 'Using Puppet::Parser::Scope.new' do + + describe 'Garbage inputs' do + inputs = [ + [ nil ], + [ [ nil ] ], + [ { 'foo' => 'bar' } ], + [ { } ], + [ '' ], + [ "one", "one", "MSG to User", "4th arg" ], + ] + + inputs.each do |input| + it "validate_augeas(#{input.inspect}) should fail" do + expect { subject.call [input] }.to raise_error Puppet::ParseError + end + end + end + + describe 'Valid inputs' do + inputs = [ + [ "root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns' ], + [ "proc /proc proc nodev,noexec,nosuid 0 0\n", 'Fstab.lns'], + ] + + inputs.each do |input| + it "validate_augeas(#{input.inspect}) should not fail" do + expect { subject.call input }.not_to raise_error + end + end + end + + describe "Valid inputs which should raise an exception without a message" do + # The intent here is to make sure valid inputs raise exceptions when they + # don't specify an error message to display. This is the behvior in + # 2.2.x and prior. + inputs = [ + [ "root:x:0:0:root\n", 'Passwd.lns' ], + [ "127.0.1.1\n", 'Hosts.lns' ], + ] + + inputs.each do |input| + it "validate_augeas(#{input.inspect}) should fail" do + expect { subject.call input }.to raise_error /validate_augeas.*?matched less than it should/ + end + end + end + + describe "Nicer Error Messages" do + # The intent here is to make sure the function returns the 3rd argument + # in the exception thrown + inputs = [ + [ "root:x:0:0:root\n", 'Passwd.lns', [], 'Failed to validate passwd content' ], + [ "127.0.1.1\n", 'Hosts.lns', [], 'Wrong hosts content' ], + ] + + inputs.each do |input| + it "validate_augeas(#{input.inspect}) should fail" do + expect { subject.call input }.to raise_error /#{input[2]}/ + end + end + end + + describe "Passing simple unit tests" do + inputs = [ + [ "root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']], + [ "root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']], + ] + + inputs.each do |input| + it "validate_augeas(#{input.inspect}) should fail" do + expect { subject.call input }.not_to raise_error + end + end + end + + describe "Failing simple unit tests" do + inputs = [ + [ "foobar:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']], + [ "root:x:0:0:root:/root:/bin/sh\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']], + ] + + inputs.each do |input| + it "validate_augeas(#{input.inspect}) should fail" do + expect { subject.call input }.to raise_error /testing path/ + end + end + end + end +end diff --git a/modules/stdlib/spec/functions/validate_bool_spec.rb b/modules/stdlib/spec/functions/validate_bool_spec.rb new file mode 100755 index 0000000..a352d3b --- /dev/null +++ b/modules/stdlib/spec/functions/validate_bool_spec.rb @@ -0,0 +1,51 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:validate_bool) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + describe 'when calling validate_bool from puppet' do + + %w{ true false }.each do |the_string| + + it "should not compile when #{the_string} is a string" do + Puppet[:code] = "validate_bool('#{the_string}')" + expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a boolean/) + end + + it "should compile when #{the_string} is a bare word" do + Puppet[:code] = "validate_bool(#{the_string})" + scope.compiler.compile + end + + end + + it "should not compile when an arbitrary string is passed" do + Puppet[:code] = 'validate_bool("jeff and dan are awesome")' + expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a boolean/) + end + + it "should not compile when no arguments are passed" do + Puppet[:code] = 'validate_bool()' + expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /wrong number of arguments/) + end + + it "should compile when multiple boolean arguments are passed" do + Puppet[:code] = <<-'ENDofPUPPETcode' + $foo = true + $bar = false + validate_bool($foo, $bar, true, false) + ENDofPUPPETcode + scope.compiler.compile + end + + it "should compile when multiple boolean arguments are passed" do + Puppet[:code] = <<-'ENDofPUPPETcode' + $foo = true + $bar = false + validate_bool($foo, $bar, true, false, 'jeff') + ENDofPUPPETcode + expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a boolean/) + end + end +end diff --git a/modules/stdlib/spec/functions/validate_cmd_spec.rb b/modules/stdlib/spec/functions/validate_cmd_spec.rb new file mode 100755 index 0000000..a6e68df --- /dev/null +++ b/modules/stdlib/spec/functions/validate_cmd_spec.rb @@ -0,0 +1,48 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +TESTEXE = File.exists?('/usr/bin/test') ? '/usr/bin/test' : '/bin/test' +TOUCHEXE = File.exists?('/usr/bin/touch') ? '/usr/bin/touch' : '/bin/touch' + +describe Puppet::Parser::Functions.function(:validate_cmd) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + subject do + function_name = Puppet::Parser::Functions.function(:validate_cmd) + scope.method(function_name) + end + + describe "with an explicit failure message" do + it "prints the failure message on error" do + expect { + subject.call ['', '/bin/false', 'failure message!'] + }.to raise_error Puppet::ParseError, /failure message!/ + end + end + + describe "on validation failure" do + it "includes the command error output" do + expect { + subject.call ['', "#{TOUCHEXE} /cant/touch/this"] + }.to raise_error Puppet::ParseError, /(cannot touch|o such file or)/ + end + + it "includes the command return value" do + expect { + subject.call ['', '/cant/run/this'] + }.to raise_error Puppet::ParseError, /returned 1\b/ + end + end + + describe "when performing actual validation" do + it "can positively validate file content" do + expect { subject.call ["non-empty", "#{TESTEXE} -s"] }.to_not raise_error + end + + it "can negatively validate file content" do + expect { + subject.call ["", "#{TESTEXE} -s"] + }.to raise_error Puppet::ParseError, /failed to validate.*test -s/ + end + end +end diff --git a/modules/stdlib/spec/functions/validate_hash_spec.rb b/modules/stdlib/spec/functions/validate_hash_spec.rb new file mode 100755 index 0000000..a0c35c2 --- /dev/null +++ b/modules/stdlib/spec/functions/validate_hash_spec.rb @@ -0,0 +1,43 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:validate_hash) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + describe 'when calling validate_hash from puppet' do + + %w{ true false }.each do |the_string| + + it "should not compile when #{the_string} is a string" do + Puppet[:code] = "validate_hash('#{the_string}')" + expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a Hash/) + end + + it "should not compile when #{the_string} is a bare word" do + Puppet[:code] = "validate_hash(#{the_string})" + expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a Hash/) + end + + end + + it "should compile when multiple hash arguments are passed" do + Puppet[:code] = <<-'ENDofPUPPETcode' + $foo = {} + $bar = { 'one' => 'two' } + validate_hash($foo, $bar) + ENDofPUPPETcode + scope.compiler.compile + end + + it "should not compile when an undef variable is passed" do + Puppet[:code] = <<-'ENDofPUPPETcode' + $foo = undef + validate_hash($foo) + ENDofPUPPETcode + expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a Hash/) + end + + end + +end diff --git a/modules/stdlib/spec/functions/validate_ipv4_address_spec.rb b/modules/stdlib/spec/functions/validate_ipv4_address_spec.rb new file mode 100755 index 0000000..45401a4 --- /dev/null +++ b/modules/stdlib/spec/functions/validate_ipv4_address_spec.rb @@ -0,0 +1,64 @@ +#! /usr/bin/env ruby -S rspec + +require "spec_helper" + +describe Puppet::Parser::Functions.function(:validate_ipv4_address) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + describe "when calling validate_ipv4_address from puppet" do + describe "when given IPv4 address strings" do + it "should compile with one argument" do + Puppet[:code] = "validate_ipv4_address('1.2.3.4')" + scope.compiler.compile + end + + it "should compile with multiple arguments" do + Puppet[:code] = "validate_ipv4_address('1.2.3.4', '5.6.7.8')" + scope.compiler.compile + end + end + + describe "when given an IPv6 address" do + it "should not compile" do + Puppet[:code] = "validate_ipv4_address('3ffe:505')" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /not a valid IPv4 address/) + end + end + + describe "when given other strings" do + it "should not compile" do + Puppet[:code] = "validate_ipv4_address('hello', 'world')" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /not a valid IPv4 address/) + end + end + + describe "when given numbers" do + it "should not compile" do + Puppet[:code] = "validate_ipv4_address(1, 2)" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /is not a valid IPv4 address/) + end + end + + describe "when given booleans" do + it "should not compile" do + Puppet[:code] = "validate_ipv4_address(true, false)" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /is not a string/) + end + end + + it "should not compile when no arguments are passed" do + Puppet[:code] = "validate_ipv4_address()" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /wrong number of arguments/) + end + end +end diff --git a/modules/stdlib/spec/functions/validate_ipv6_address_spec.rb b/modules/stdlib/spec/functions/validate_ipv6_address_spec.rb new file mode 100755 index 0000000..a839d90 --- /dev/null +++ b/modules/stdlib/spec/functions/validate_ipv6_address_spec.rb @@ -0,0 +1,67 @@ +#! /usr/bin/env ruby -S rspec + +require "spec_helper" + +describe Puppet::Parser::Functions.function(:validate_ipv6_address) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + describe "when calling validate_ipv6_address from puppet" do + describe "when given IPv6 address strings" do + it "should compile with one argument" do + Puppet[:code] = "validate_ipv6_address('3ffe:0505:0002::')" + scope.compiler.compile + end + + it "should compile with multiple arguments" do + Puppet[:code] = "validate_ipv6_address('3ffe:0505:0002::', '3ffe:0505:0001::')" + scope.compiler.compile + end + end + + describe "when given an ipv4 address" do + it "should not compile" do + Puppet[:code] = "validate_ipv6_address('1.2.3.4')" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /not a valid IPv6 address/) + end + end + + describe "when given other strings" do + it "should not compile" do + Puppet[:code] = "validate_ipv6_address('hello', 'world')" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /not a valid IPv6 address/) + end + end + + # 1.8.7 is EOL'd and also absolutely insane about ipv6 + unless RUBY_VERSION == '1.8.7' + describe "when given numbers" do + it "should not compile" do + Puppet[:code] = "validate_ipv6_address(1, 2)" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /not a valid IPv6 address/) + end + end + end + + describe "when given booleans" do + it "should not compile" do + Puppet[:code] = "validate_ipv6_address(true, false)" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /is not a string/) + end + end + + it "should not compile when no arguments are passed" do + Puppet[:code] = "validate_ipv6_address()" + expect { + scope.compiler.compile + }.to raise_error(Puppet::ParseError, /wrong number of arguments/) + end + end +end diff --git a/modules/stdlib/spec/functions/validate_re_spec.rb b/modules/stdlib/spec/functions/validate_re_spec.rb new file mode 100755 index 0000000..d29988b --- /dev/null +++ b/modules/stdlib/spec/functions/validate_re_spec.rb @@ -0,0 +1,77 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:validate_re) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + # The subject of these examplres is the method itself. + subject do + # This makes sure the function is loaded within each test + function_name = Puppet::Parser::Functions.function(:validate_re) + scope.method(function_name) + end + + context 'Using Puppet::Parser::Scope.new' do + + describe 'Garbage inputs' do + inputs = [ + [ nil ], + [ [ nil ] ], + [ { 'foo' => 'bar' } ], + [ { } ], + [ '' ], + [ "one", "one", "MSG to User", "4th arg" ], + ] + + inputs.each do |input| + it "validate_re(#{input.inspect}) should fail" do + expect { subject.call [input] }.to raise_error Puppet::ParseError + end + end + end + + describe 'Valid inputs' do + inputs = [ + [ '/full/path/to/something', '^/full' ], + [ '/full/path/to/something', 'full' ], + [ '/full/path/to/something', ['full', 'absent'] ], + [ '/full/path/to/something', ['full', 'absent'], 'Message to the user' ], + ] + + inputs.each do |input| + it "validate_re(#{input.inspect}) should not fail" do + expect { subject.call input }.not_to raise_error + end + end + end + describe "Valid inputs which should raise an exception without a message" do + # The intent here is to make sure valid inputs raise exceptions when they + # don't specify an error message to display. This is the behvior in + # 2.2.x and prior. + inputs = [ + [ "hello", [ "bye", "later", "adios" ] ], + [ "greetings", "salutations" ], + ] + + inputs.each do |input| + it "validate_re(#{input.inspect}) should fail" do + expect { subject.call input }.to raise_error /validate_re.*?does not match/ + end + end + end + describe "Nicer Error Messages" do + # The intent here is to make sure the function returns the 3rd argument + # in the exception thrown + inputs = [ + [ "hello", [ "bye", "later", "adios" ], "MSG to User" ], + [ "greetings", "salutations", "Error, greetings does not match salutations" ], + ] + + inputs.each do |input| + it "validate_re(#{input.inspect}) should fail" do + expect { subject.call input }.to raise_error /#{input[2]}/ + end + end + end + end +end diff --git a/modules/stdlib/spec/functions/validate_slength_spec.rb b/modules/stdlib/spec/functions/validate_slength_spec.rb new file mode 100755 index 0000000..851835f --- /dev/null +++ b/modules/stdlib/spec/functions/validate_slength_spec.rb @@ -0,0 +1,67 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe "the validate_slength function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("validate_slength").should == "function_validate_slength" + end + + describe "validating the input argument types" do + it "raises an error if there are less than two arguments" do + expect { scope.function_validate_slength([]) }.to raise_error Puppet::ParseError, /Wrong number of arguments/ + end + + it "raises an error if there are more than three arguments" do + expect { scope.function_validate_slength(['input', 1, 2, 3]) }.to raise_error Puppet::ParseError, /Wrong number of arguments/ + end + + it "raises an error if the first argument is not a string" do + expect { scope.function_validate_slength([Object.new, 2, 1]) }.to raise_error Puppet::ParseError, /Expected first argument.*got .*Object/ + end + + it "raises an error if the second argument cannot be cast to an Integer" do + expect { scope.function_validate_slength(['input', Object.new]) }.to raise_error Puppet::ParseError, /Expected second argument.*got .*Object/ + end + + it "raises an error if the third argument cannot be cast to an Integer" do + expect { scope.function_validate_slength(['input', 1, Object.new]) }.to raise_error Puppet::ParseError, /Expected third argument.*got .*Object/ + end + + it "raises an error if the second argument is smaller than the third argument" do + expect { scope.function_validate_slength(['input', 1, 2]) }.to raise_error Puppet::ParseError, /Expected second argument to be larger than third argument/ + end + end + + describe "validating the input string length" do + describe "when the input is a string" do + it "fails validation if the string is larger than the max length" do + expect { scope.function_validate_slength(['input', 1]) }.to raise_error Puppet::ParseError, /Expected length .* between 0 and 1, was 5/ + end + + it "fails validation if the string is less than the min length" do + expect { scope.function_validate_slength(['input', 10, 6]) }.to raise_error Puppet::ParseError, /Expected length .* between 6 and 10, was 5/ + end + + it "doesn't raise an error if the string is under the max length" do + scope.function_validate_slength(['input', 10]) + end + + it "doesn't raise an error if the string is equal to the max length" do + scope.function_validate_slength(['input', 5]) + end + + it "doesn't raise an error if the string is equal to the min length" do + scope.function_validate_slength(['input', 10, 5]) + end + end + + describe "when the input is an array" do + it "fails validation if one of the array elements is not a string" do + expect { scope.function_validate_slength([["a", "b", Object.new], 2]) }.to raise_error Puppet::ParseError, /Expected element at array position 2 .*String, got .*Object/ + end + end + end +end diff --git a/modules/stdlib/spec/functions/validate_string_spec.rb b/modules/stdlib/spec/functions/validate_string_spec.rb new file mode 100755 index 0000000..3b4fb3e --- /dev/null +++ b/modules/stdlib/spec/functions/validate_string_spec.rb @@ -0,0 +1,60 @@ +#! /usr/bin/env ruby -S rspec + +require 'spec_helper' + +describe Puppet::Parser::Functions.function(:validate_string) do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + describe 'when calling validate_string from puppet' do + + %w{ foo bar baz }.each do |the_string| + + it "should compile when #{the_string} is a string" do + Puppet[:code] = "validate_string('#{the_string}')" + scope.compiler.compile + end + + it "should compile when #{the_string} is a bare word" do + Puppet[:code] = "validate_string(#{the_string})" + scope.compiler.compile + end + + end + + %w{ true false }.each do |the_string| + it "should compile when #{the_string} is a string" do + Puppet[:code] = "validate_string('#{the_string}')" + scope.compiler.compile + end + + it "should not compile when #{the_string} is a bare word" do + Puppet[:code] = "validate_string(#{the_string})" + expect { scope.compiler.compile }.to raise_error(Puppet::ParseError, /is not a string/) + end + end + + it "should compile when multiple string arguments are passed" do + Puppet[:code] = <<-'ENDofPUPPETcode' + $foo = '' + $bar = 'two' + validate_string($foo, $bar) + ENDofPUPPETcode + scope.compiler.compile + end + + it "should compile when an explicitly undef variable is passed (NOTE THIS MAY NOT BE DESIRABLE)" do + Puppet[:code] = <<-'ENDofPUPPETcode' + $foo = undef + validate_string($foo) + ENDofPUPPETcode + scope.compiler.compile + end + + it "should compile when an undefined variable is passed (NOTE THIS MAY NOT BE DESIRABLE)" do + Puppet[:code] = <<-'ENDofPUPPETcode' + validate_string($foobarbazishouldnotexist) + ENDofPUPPETcode + scope.compiler.compile + end + end +end diff --git a/modules/stdlib/spec/functions/values_at_spec.rb b/modules/stdlib/spec/functions/values_at_spec.rb new file mode 100755 index 0000000..08e95a5 --- /dev/null +++ b/modules/stdlib/spec/functions/values_at_spec.rb @@ -0,0 +1,38 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the values_at function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("values_at").should == "function_values_at" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_values_at([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should raise a ParseError if you try to use a range where stop is greater then start" do + lambda { scope.function_values_at([['a','b'],["3-1"]]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return a value at from an array" do + result = scope.function_values_at([['a','b','c'],"1"]) + result.should(eq(['b'])) + end + + it "should return a value at from an array when passed a range" do + result = scope.function_values_at([['a','b','c'],"0-1"]) + result.should(eq(['a','b'])) + end + + it "should return chosen values from an array when passed number of indexes" do + result = scope.function_values_at([['a','b','c'],["0","2"]]) + result.should(eq(['a','c'])) + end + + it "should return chosen values from an array when passed ranges and multiple indexes" do + result = scope.function_values_at([['a','b','c','d','e','f','g'],["0","2","4-5"]]) + result.should(eq(['a','c','e','f'])) + end +end diff --git a/modules/stdlib/spec/functions/values_spec.rb b/modules/stdlib/spec/functions/values_spec.rb new file mode 100755 index 0000000..14ae417 --- /dev/null +++ b/modules/stdlib/spec/functions/values_spec.rb @@ -0,0 +1,31 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the values function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("values").should == "function_values" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_values([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should return values from a hash" do + result = scope.function_values([{'a'=>'1','b'=>'2','c'=>'3'}]) + # =~ is the RSpec::Matchers::MatchArray matcher. + # A.K.A. "array with same elements" (multiset) matching + result.should =~ %w{ 1 2 3 } + end + + it "should return a multiset" do + result = scope.function_values([{'a'=>'1','b'=>'3','c'=>'3'}]) + result.should =~ %w{ 1 3 3 } + result.should_not =~ %w{ 1 3 } + end + + it "should raise a ParseError unless a Hash is provided" do + lambda { scope.function_values([['a','b','c']]) }.should( raise_error(Puppet::ParseError)) + end +end diff --git a/modules/stdlib/spec/functions/zip_spec.rb b/modules/stdlib/spec/functions/zip_spec.rb new file mode 100755 index 0000000..f45ab17 --- /dev/null +++ b/modules/stdlib/spec/functions/zip_spec.rb @@ -0,0 +1,15 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the zip function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_zip([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should be able to zip an array" do + result = scope.function_zip([['1','2','3'],['4','5','6']]) + result.should(eq([["1", "4"], ["2", "5"], ["3", "6"]])) + end +end diff --git a/modules/stdlib/spec/lib/puppet_spec/compiler.rb b/modules/stdlib/spec/lib/puppet_spec/compiler.rb new file mode 100755 index 0000000..2f0ae4d --- /dev/null +++ b/modules/stdlib/spec/lib/puppet_spec/compiler.rb @@ -0,0 +1,47 @@ +#! /usr/bin/env ruby -S rspec +module PuppetSpec::Compiler + def compile_to_catalog(string, node = Puppet::Node.new('foonode')) + Puppet[:code] = string + Puppet::Parser::Compiler.compile(node) + end + + def compile_to_ral(manifest) + catalog = compile_to_catalog(manifest) + ral = catalog.to_ral + ral.finalize + ral + end + + def compile_to_relationship_graph(manifest, prioritizer = Puppet::Graph::SequentialPrioritizer.new) + ral = compile_to_ral(manifest) + graph = Puppet::Graph::RelationshipGraph.new(prioritizer) + graph.populate_from(ral) + graph + end + + if Puppet.version.to_f >= 3.3 + def apply_compiled_manifest(manifest, prioritizer = Puppet::Graph::SequentialPrioritizer.new) + transaction = Puppet::Transaction.new(compile_to_ral(manifest), + Puppet::Transaction::Report.new("apply"), + prioritizer) + transaction.evaluate + transaction.report.finalize_report + + transaction + end + else + def apply_compiled_manifest(manifest) + transaction = Puppet::Transaction.new(compile_to_ral(manifest), Puppet::Transaction::Report.new("apply")) + transaction.evaluate + transaction.report.finalize_report + + transaction + end + end + + def order_resources_traversed_in(relationships) + order_seen = [] + relationships.traverse { |resource| order_seen << resource.ref } + order_seen + end +end diff --git a/modules/stdlib/spec/lib/puppet_spec/database.rb b/modules/stdlib/spec/lib/puppet_spec/database.rb new file mode 100755 index 0000000..f5c2341 --- /dev/null +++ b/modules/stdlib/spec/lib/puppet_spec/database.rb @@ -0,0 +1,30 @@ +#! /usr/bin/env ruby -S rspec +# This just makes some nice things available at global scope, and for setup of +# tests to use a real fake database, rather than a fake stubs-that-don't-work +# version of the same. Fun times. +def sqlite? + if $sqlite.nil? + begin + require 'sqlite3' + $sqlite = true + rescue LoadError + $sqlite = false + end + end + $sqlite +end + +def can_use_scratch_database? + sqlite? and Puppet.features.rails? +end + + +# This is expected to be called in your `before :each` block, and will get you +# ready to roll with a serious database and all. Cleanup is handled +# automatically for you. Nothing to do there. +def setup_scratch_database + Puppet[:dbadapter] = 'sqlite3' + Puppet[:dblocation] = ':memory:' + Puppet[:railslog] = PuppetSpec::Files.tmpfile('storeconfigs.log') + Puppet::Rails.init +end diff --git a/modules/stdlib/spec/lib/puppet_spec/files.rb b/modules/stdlib/spec/lib/puppet_spec/files.rb new file mode 100755 index 0000000..71b38ff --- /dev/null +++ b/modules/stdlib/spec/lib/puppet_spec/files.rb @@ -0,0 +1,61 @@ +#! /usr/bin/env ruby -S rspec +require 'fileutils' +require 'tempfile' +require 'tmpdir' +require 'pathname' + +# A support module for testing files. +module PuppetSpec::Files + def self.cleanup + $global_tempfiles ||= [] + while path = $global_tempfiles.pop do + begin + Dir.unstub(:entries) + FileUtils.rm_rf path, :secure => true + rescue Errno::ENOENT + # nothing to do + end + end + end + + def make_absolute(path) PuppetSpec::Files.make_absolute(path) end + def self.make_absolute(path) + path = File.expand_path(path) + path[0] = 'c' if Puppet.features.microsoft_windows? + path + end + + def tmpfile(name, dir = nil) PuppetSpec::Files.tmpfile(name, dir) end + def self.tmpfile(name, dir = nil) + # Generate a temporary file, just for the name... + source = dir ? Tempfile.new(name, dir) : Tempfile.new(name) + path = source.path + source.close! + + record_tmp(File.expand_path(path)) + + path + end + + def file_containing(name, contents) PuppetSpec::Files.file_containing(name, contents) end + def self.file_containing(name, contents) + file = tmpfile(name) + File.open(file, 'wb') { |f| f.write(contents) } + file + end + + def tmpdir(name) PuppetSpec::Files.tmpdir(name) end + def self.tmpdir(name) + dir = Dir.mktmpdir(name) + + record_tmp(dir) + + dir + end + + def self.record_tmp(tmp) + # ...record it for cleanup, + $global_tempfiles ||= [] + $global_tempfiles << tmp + end +end diff --git a/modules/stdlib/spec/lib/puppet_spec/fixtures.rb b/modules/stdlib/spec/lib/puppet_spec/fixtures.rb new file mode 100755 index 0000000..81e9775 --- /dev/null +++ b/modules/stdlib/spec/lib/puppet_spec/fixtures.rb @@ -0,0 +1,29 @@ +#! /usr/bin/env ruby -S rspec +module PuppetSpec::Fixtures + def fixtures(*rest) + File.join(PuppetSpec::FIXTURE_DIR, *rest) + end + def my_fixture_dir + callers = caller + while line = callers.shift do + next unless found = line.match(%r{/spec/(.*)_spec\.rb:}) + return fixtures(found[1]) + end + fail "sorry, I couldn't work out your path from the caller stack!" + end + def my_fixture(name) + file = File.join(my_fixture_dir, name) + unless File.readable? file then + fail Puppet::DevError, "fixture '#{name}' for #{my_fixture_dir} is not readable" + end + return file + end + def my_fixtures(glob = '*', flags = 0) + files = Dir.glob(File.join(my_fixture_dir, glob), flags) + unless files.length > 0 then + fail Puppet::DevError, "fixture '#{glob}' for #{my_fixture_dir} had no files!" + end + block_given? and files.each do |file| yield file end + files + end +end diff --git a/modules/stdlib/spec/lib/puppet_spec/matchers.rb b/modules/stdlib/spec/lib/puppet_spec/matchers.rb new file mode 100755 index 0000000..093d77c --- /dev/null +++ b/modules/stdlib/spec/lib/puppet_spec/matchers.rb @@ -0,0 +1,121 @@ +#! /usr/bin/env ruby -S rspec +require 'stringio' + +######################################################################## +# Backward compatibility for Jenkins outdated environment. +module RSpec + module Matchers + module BlockAliases + alias_method :to, :should unless method_defined? :to + alias_method :to_not, :should_not unless method_defined? :to_not + alias_method :not_to, :should_not unless method_defined? :not_to + end + end +end + + +######################################################################## +# Custom matchers... +RSpec::Matchers.define :have_matching_element do |expected| + match do |actual| + actual.any? { |item| item =~ expected } + end +end + + +RSpec::Matchers.define :exit_with do |expected| + actual = nil + match do |block| + begin + block.call + rescue SystemExit => e + actual = e.status + end + actual and actual == expected + end + failure_message_for_should do |block| + "expected exit with code #{expected} but " + + (actual.nil? ? " exit was not called" : "we exited with #{actual} instead") + end + failure_message_for_should_not do |block| + "expected that exit would not be called with #{expected}" + end + description do + "expect exit with #{expected}" + end +end + +class HavePrintedMatcher + attr_accessor :expected, :actual + + def initialize(expected) + case expected + when String, Regexp + @expected = expected + else + @expected = expected.to_s + end + end + + def matches?(block) + begin + $stderr = $stdout = StringIO.new + $stdout.set_encoding('UTF-8') if $stdout.respond_to?(:set_encoding) + block.call + $stdout.rewind + @actual = $stdout.read + ensure + $stdout = STDOUT + $stderr = STDERR + end + + if @actual then + case @expected + when String + @actual.include? @expected + when Regexp + @expected.match @actual + end + else + false + end + end + + def failure_message_for_should + if @actual.nil? then + "expected #{@expected.inspect}, but nothing was printed" + else + "expected #{@expected.inspect} to be printed; got:\n#{@actual}" + end + end + + def failure_message_for_should_not + "expected #{@expected.inspect} to not be printed; got:\n#{@actual}" + end + + def description + "expect #{@expected.inspect} to be printed" + end +end + +def have_printed(what) + HavePrintedMatcher.new(what) +end + +RSpec::Matchers.define :equal_attributes_of do |expected| + match do |actual| + actual.instance_variables.all? do |attr| + actual.instance_variable_get(attr) == expected.instance_variable_get(attr) + end + end +end + +RSpec::Matchers.define :be_one_of do |*expected| + match do |actual| + expected.include? actual + end + + failure_message_for_should do |actual| + "expected #{actual.inspect} to be one of #{expected.map(&:inspect).join(' or ')}" + end +end diff --git a/modules/stdlib/spec/lib/puppet_spec/modules.rb b/modules/stdlib/spec/lib/puppet_spec/modules.rb new file mode 100755 index 0000000..910c6d9 --- /dev/null +++ b/modules/stdlib/spec/lib/puppet_spec/modules.rb @@ -0,0 +1,27 @@ +#! /usr/bin/env ruby -S rspec +module PuppetSpec::Modules + class << self + def create(name, dir, options = {}) + module_dir = File.join(dir, name) + FileUtils.mkdir_p(module_dir) + + environment = options[:environment] + + if metadata = options[:metadata] + metadata[:source] ||= 'github' + metadata[:author] ||= 'puppetlabs' + metadata[:version] ||= '9.9.9' + metadata[:license] ||= 'to kill' + metadata[:dependencies] ||= [] + + metadata[:name] = "#{metadata[:author]}/#{name}" + + File.open(File.join(module_dir, 'metadata.json'), 'w') do |f| + f.write(metadata.to_pson) + end + end + + Puppet::Module.new(name, module_dir, environment) + end + end +end diff --git a/modules/stdlib/spec/lib/puppet_spec/pops.rb b/modules/stdlib/spec/lib/puppet_spec/pops.rb new file mode 100755 index 0000000..e056a52 --- /dev/null +++ b/modules/stdlib/spec/lib/puppet_spec/pops.rb @@ -0,0 +1,17 @@ +#! /usr/bin/env ruby -S rspec +module PuppetSpec::Pops + extend RSpec::Matchers::DSL + + # Checks if an Acceptor has a specific issue in its list of diagnostics + matcher :have_issue do |expected| + match do |actual| + actual.diagnostics.index { |i| i.issue == expected } != nil + end + failure_message_for_should do |actual| + "expected Acceptor[#{actual.diagnostics.collect { |i| i.issue.issue_code }.join(',')}] to contain issue #{expected.issue_code}" + end + failure_message_for_should_not do |actual| + "expected Acceptor[#{actual.diagnostics.collect { |i| i.issue.issue_code }.join(',')}] to not contain issue #{expected.issue_code}" + end + end +end diff --git a/modules/stdlib/spec/lib/puppet_spec/scope.rb b/modules/stdlib/spec/lib/puppet_spec/scope.rb new file mode 100755 index 0000000..3847ede --- /dev/null +++ b/modules/stdlib/spec/lib/puppet_spec/scope.rb @@ -0,0 +1,15 @@ +#! /usr/bin/env ruby -S rspec + +module PuppetSpec::Scope + # Initialize a new scope suitable for testing. + # + def create_test_scope_for_node(node_name) + node = Puppet::Node.new(node_name) + compiler = Puppet::Parser::Compiler.new(node) + scope = Puppet::Parser::Scope.new(compiler) + scope.source = Puppet::Resource::Type.new(:node, node_name) + scope.parent = compiler.topscope + scope + end + +end \ No newline at end of file diff --git a/modules/stdlib/spec/lib/puppet_spec/settings.rb b/modules/stdlib/spec/lib/puppet_spec/settings.rb new file mode 100755 index 0000000..8ddcb97 --- /dev/null +++ b/modules/stdlib/spec/lib/puppet_spec/settings.rb @@ -0,0 +1,16 @@ +#! /usr/bin/env ruby -S rspec +module PuppetSpec::Settings + + # It would probably be preferable to refactor defaults.rb such that the real definitions of + # these settings were available as a variable, which was then accessible for use during tests. + # However, I'm not doing that yet because I don't want to introduce any additional moving parts + # to this already very large changeset. + # Would be nice to clean this up later. --cprice 2012-03-20 + TEST_APP_DEFAULT_DEFINITIONS = { + :name => { :default => "test", :desc => "name" }, + :logdir => { :type => :directory, :default => "test", :desc => "logdir" }, + :confdir => { :type => :directory, :default => "test", :desc => "confdir" }, + :vardir => { :type => :directory, :default => "test", :desc => "vardir" }, + :rundir => { :type => :directory, :default => "test", :desc => "rundir" }, + } +end diff --git a/modules/stdlib/spec/lib/puppet_spec/verbose.rb b/modules/stdlib/spec/lib/puppet_spec/verbose.rb new file mode 100755 index 0000000..b2683df --- /dev/null +++ b/modules/stdlib/spec/lib/puppet_spec/verbose.rb @@ -0,0 +1,10 @@ +#! /usr/bin/env ruby -S rspec +# Support code for running stuff with warnings disabled. +module Kernel + def with_verbose_disabled + verbose, $VERBOSE = $VERBOSE, nil + result = yield + $VERBOSE = verbose + return result + end +end diff --git a/modules/stdlib/spec/monkey_patches/alias_should_to_must.rb b/modules/stdlib/spec/monkey_patches/alias_should_to_must.rb new file mode 100755 index 0000000..505e240 --- /dev/null +++ b/modules/stdlib/spec/monkey_patches/alias_should_to_must.rb @@ -0,0 +1,9 @@ +#! /usr/bin/env ruby -S rspec +require 'rspec' + +class Object + # This is necessary because the RAL has a 'should' + # method. + alias :must :should + alias :must_not :should_not +end diff --git a/modules/stdlib/spec/monkey_patches/publicize_methods.rb b/modules/stdlib/spec/monkey_patches/publicize_methods.rb new file mode 100755 index 0000000..3ae59f9 --- /dev/null +++ b/modules/stdlib/spec/monkey_patches/publicize_methods.rb @@ -0,0 +1,11 @@ +#! /usr/bin/env ruby -S rspec +# Some monkey-patching to allow us to test private methods. +class Class + def publicize_methods(*methods) + saved_private_instance_methods = methods.empty? ? self.private_instance_methods : methods + + self.class_eval { public(*saved_private_instance_methods) } + yield + self.class_eval { private(*saved_private_instance_methods) } + end +end diff --git a/modules/stdlib/spec/spec.opts b/modules/stdlib/spec/spec.opts new file mode 100644 index 0000000..91cd642 --- /dev/null +++ b/modules/stdlib/spec/spec.opts @@ -0,0 +1,6 @@ +--format +s +--colour +--loadby +mtime +--backtrace diff --git a/modules/stdlib/spec/spec_helper.rb b/modules/stdlib/spec/spec_helper.rb new file mode 100755 index 0000000..78925fd --- /dev/null +++ b/modules/stdlib/spec/spec_helper.rb @@ -0,0 +1,39 @@ +#! /usr/bin/env ruby -S rspec +dir = File.expand_path(File.dirname(__FILE__)) +$LOAD_PATH.unshift File.join(dir, 'lib') + +# So everyone else doesn't have to include this base constant. +module PuppetSpec + FIXTURE_DIR = File.join(dir = File.expand_path(File.dirname(__FILE__)), "fixtures") unless defined?(FIXTURE_DIR) +end + +require 'puppet' +require 'rspec-puppet' +require 'simplecov' +require 'puppetlabs_spec_helper/module_spec_helper' +require 'puppet_spec/verbose' +require 'puppet_spec/files' +require 'puppet_spec/settings' +require 'puppet_spec/fixtures' +require 'puppet_spec/matchers' +require 'puppet_spec/database' +require 'monkey_patches/alias_should_to_must' +require 'mocha/setup' + + +SimpleCov.start do + add_filter "/spec/" +end + + +RSpec.configure do |config| + config.before :each do + # Ensure that we don't accidentally cache facts and environment between + # test cases. This requires each example group to explicitly load the + # facts being exercised with something like + # Facter.collection.loader.load(:ipaddress) + Facter::Util::Loader.any_instance.stubs(:load_all) + Facter.clear + Facter.clear_messages + end +end diff --git a/modules/stdlib/spec/spec_helper_acceptance.rb b/modules/stdlib/spec/spec_helper_acceptance.rb new file mode 100755 index 0000000..8e56daa --- /dev/null +++ b/modules/stdlib/spec/spec_helper_acceptance.rb @@ -0,0 +1,31 @@ +#! /usr/bin/env ruby -S rspec +require 'beaker-rspec' + +UNSUPPORTED_PLATFORMS = [] + +unless ENV['RS_PROVISION'] == 'no' or ENV['BEAKER_provision'] == 'no' + if hosts.first.is_pe? + install_pe + on hosts, 'mkdir -p /etc/puppetlabs/facter/facts.d' + else + install_puppet + on hosts, 'mkdir -p /etc/facter/facts.d' + on hosts, '/bin/touch /etc/puppet/hiera.yaml' + end + hosts.each do |host| + on host, "mkdir -p #{host['distmoduledir']}" + end +end + +RSpec.configure do |c| + # Project root + proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) + + # Readable test descriptions + c.formatter = :documentation + + # Configure all nodes in nodeset + c.before :suite do + puppet_module_install(:source => proj_root, :module_name => 'stdlib') + end +end diff --git a/modules/stdlib/spec/unit/facter/facter_dot_d_spec.rb b/modules/stdlib/spec/unit/facter/facter_dot_d_spec.rb new file mode 100755 index 0000000..2fb72b2 --- /dev/null +++ b/modules/stdlib/spec/unit/facter/facter_dot_d_spec.rb @@ -0,0 +1,32 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' +require 'facter/facter_dot_d' + +describe Facter::Util::DotD do + + context 'returns a simple fact' do + before :each do + Facter.stubs(:version).returns('1.6.1') + subject.stubs(:entries).returns(['/etc/facter/facts.d/fake_fact.txt']) + File.stubs(:readlines).with('/etc/facter/facts.d/fake_fact.txt').returns(['fake_fact=fake fact']) + subject.create + end + + it 'should return successfully' do + Facter.fact(:fake_fact).value.should == 'fake fact' + end + end + + context 'returns a fact with equals signs' do + before :each do + Facter.stubs(:version).returns('1.6.1') + subject.stubs(:entries).returns(['/etc/facter/facts.d/foo.txt']) + File.stubs(:readlines).with('/etc/facter/facts.d/foo.txt').returns(['foo=1+1=2']) + subject.create + end + + it 'should return successfully' do + Facter.fact(:foo).value.should == '1+1=2' + end + end +end diff --git a/modules/stdlib/spec/unit/facter/pe_version_spec.rb b/modules/stdlib/spec/unit/facter/pe_version_spec.rb new file mode 100755 index 0000000..931c6d4 --- /dev/null +++ b/modules/stdlib/spec/unit/facter/pe_version_spec.rb @@ -0,0 +1,76 @@ +#!/usr/bin/env rspec + +require 'spec_helper' + +describe "PE Version specs" do + before :each do + # Explicitly load the pe_version.rb file which contains generated facts + # that cannot be automatically loaded. Puppet 2.x implements + # Facter.collection.load while Facter 1.x markes Facter.collection.load as + # a private method. + if Facter.collection.respond_to? :load + Facter.collection.load(:pe_version) + else + Facter.collection.loader.load(:pe_version) + end + end + + context "If PE is installed" do + %w{ 2.6.1 2.10.300 }.each do |version| + puppetversion = "2.7.19 (Puppet Enterprise #{version})" + context "puppetversion => #{puppetversion}" do + before :each do + Facter.fact(:puppetversion).stubs(:value).returns(puppetversion) + end + + (major,minor,patch) = version.split(".") + + it "Should return true" do + Facter.fact(:is_pe).value.should == true + end + + it "Should have a version of #{version}" do + Facter.fact(:pe_version).value.should == version + end + + it "Should have a major version of #{major}" do + Facter.fact(:pe_major_version).value.should == major + end + + it "Should have a minor version of #{minor}" do + Facter.fact(:pe_minor_version).value.should == minor + end + + it "Should have a patch version of #{patch}" do + Facter.fact(:pe_patch_version).value.should == patch + end + end + end + end + + context "When PE is not installed" do + before :each do + Facter.fact(:puppetversion).stubs(:value).returns("2.7.19") + end + + it "is_pe is false" do + Facter.fact(:is_pe).value.should == false + end + + it "pe_version is nil" do + Facter.fact(:pe_version).value.should be_nil + end + + it "pe_major_version is nil" do + Facter.fact(:pe_major_version).value.should be_nil + end + + it "pe_minor_version is nil" do + Facter.fact(:pe_minor_version).value.should be_nil + end + + it "Should have a patch version" do + Facter.fact(:pe_patch_version).value.should be_nil + end + end +end diff --git a/modules/stdlib/spec/unit/facter/root_home_spec.rb b/modules/stdlib/spec/unit/facter/root_home_spec.rb new file mode 100755 index 0000000..73eb3ea --- /dev/null +++ b/modules/stdlib/spec/unit/facter/root_home_spec.rb @@ -0,0 +1,52 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' +require 'facter/root_home' + +describe Facter::Util::RootHome do + context "solaris" do + let(:root_ent) { "root:x:0:0:Super-User:/:/sbin/sh" } + let(:expected_root_home) { "/" } + + it "should return /" do + Facter::Util::Resolution.expects(:exec).with("getent passwd root").returns(root_ent) + Facter::Util::RootHome.get_root_home.should == expected_root_home + end + end + context "linux" do + let(:root_ent) { "root:x:0:0:root:/root:/bin/bash" } + let(:expected_root_home) { "/root" } + + it "should return /root" do + Facter::Util::Resolution.expects(:exec).with("getent passwd root").returns(root_ent) + Facter::Util::RootHome.get_root_home.should == expected_root_home + end + end + context "windows" do + before :each do + Facter::Util::Resolution.expects(:exec).with("getent passwd root").returns(nil) + end + it "should be nil on windows" do + Facter::Util::RootHome.get_root_home.should be_nil + end + end +end + +describe 'root_home', :type => :fact do + before { Facter.clear } + after { Facter.clear } + + context "macosx" do + before do + Facter.fact(:kernel).stubs(:value).returns("Darwin") + Facter.fact(:osfamily).stubs(:value).returns("Darwin") + end + let(:expected_root_home) { "/var/root" } + sample_dscacheutil = File.read(fixtures('dscacheutil','root')) + + it "should return /var/root" do + Facter::Util::Resolution.stubs(:exec).with("dscacheutil -q user -a name root").returns(sample_dscacheutil) + Facter.fact(:root_home).value.should == expected_root_home + end + end + +end diff --git a/modules/stdlib/spec/unit/facter/util/puppet_settings_spec.rb b/modules/stdlib/spec/unit/facter/util/puppet_settings_spec.rb new file mode 100755 index 0000000..e77779b --- /dev/null +++ b/modules/stdlib/spec/unit/facter/util/puppet_settings_spec.rb @@ -0,0 +1,36 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' +require 'facter/util/puppet_settings' + +describe Facter::Util::PuppetSettings do + + describe "#with_puppet" do + context "Without Puppet loaded" do + before(:each) do + Module.expects(:const_get).with("Puppet").raises(NameError) + end + + it 'should be nil' do + subject.with_puppet { Puppet[:vardir] }.should be_nil + end + it 'should not yield to the block' do + Puppet.expects(:[]).never + subject.with_puppet { Puppet[:vardir] }.should be_nil + end + end + context "With Puppet loaded" do + module Puppet; end + let(:vardir) { "/var/lib/puppet" } + + before :each do + Puppet.expects(:[]).with(:vardir).returns vardir + end + it 'should yield to the block' do + subject.with_puppet { Puppet[:vardir] } + end + it 'should return the nodes vardir' do + subject.with_puppet { Puppet[:vardir] }.should eq vardir + end + end + end +end diff --git a/modules/stdlib/spec/unit/puppet/provider/file_line/ruby_spec.rb b/modules/stdlib/spec/unit/puppet/provider/file_line/ruby_spec.rb new file mode 100755 index 0000000..a016b68 --- /dev/null +++ b/modules/stdlib/spec/unit/puppet/provider/file_line/ruby_spec.rb @@ -0,0 +1,225 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' +require 'tempfile' +provider_class = Puppet::Type.type(:file_line).provider(:ruby) +describe provider_class do + context "when adding" do + let :tmpfile do + tmp = Tempfile.new('tmp') + path = tmp.path + tmp.close! + path + end + let :resource do + Puppet::Type::File_line.new( + {:name => 'foo', :path => tmpfile, :line => 'foo'} + ) + end + let :provider do + provider_class.new(resource) + end + + it 'should detect if the line exists in the file' do + File.open(tmpfile, 'w') do |fh| + fh.write('foo') + end + provider.exists?.should be_true + end + it 'should detect if the line does not exist in the file' do + File.open(tmpfile, 'w') do |fh| + fh.write('foo1') + end + provider.exists?.should be_nil + end + it 'should append to an existing file when creating' do + provider.create + File.read(tmpfile).chomp.should == 'foo' + end + end + + context "when matching" do + before :each do + # TODO: these should be ported over to use the PuppetLabs spec_helper + # file fixtures once the following pull request has been merged: + # https://github.com/puppetlabs/puppetlabs-stdlib/pull/73/files + tmp = Tempfile.new('tmp') + @tmpfile = tmp.path + tmp.close! + @resource = Puppet::Type::File_line.new( + { + :name => 'foo', + :path => @tmpfile, + :line => 'foo = bar', + :match => '^foo\s*=.*$', + } + ) + @provider = provider_class.new(@resource) + end + + describe 'using match' do + it 'should raise an error if more than one line matches, and should not have modified the file' do + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") + end + @provider.exists?.should be_nil + expect { @provider.create }.to raise_error(Puppet::Error, /More than one line.*matches/) + File.read(@tmpfile).should eql("foo1\nfoo=blah\nfoo2\nfoo=baz") + end + + it 'should replace all lines that matches' do + @resource = Puppet::Type::File_line.new( + { + :name => 'foo', + :path => @tmpfile, + :line => 'foo = bar', + :match => '^foo\s*=.*$', + :multiple => true + } + ) + @provider = provider_class.new(@resource) + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") + end + @provider.exists?.should be_nil + @provider.create + File.read(@tmpfile).chomp.should eql("foo1\nfoo = bar\nfoo2\nfoo = bar") + end + + it 'should raise an error with invalid values' do + expect { + @resource = Puppet::Type::File_line.new( + { + :name => 'foo', + :path => @tmpfile, + :line => 'foo = bar', + :match => '^foo\s*=.*$', + :multiple => 'asgadga' + } + ) + }.to raise_error(Puppet::Error, /Invalid value "asgadga"\. Valid values are true, false\./) + end + + it 'should replace a line that matches' do + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo=blah\nfoo2") + end + @provider.exists?.should be_nil + @provider.create + File.read(@tmpfile).chomp.should eql("foo1\nfoo = bar\nfoo2") + end + it 'should add a new line if no lines match' do + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo2") + end + @provider.exists?.should be_nil + @provider.create + File.read(@tmpfile).should eql("foo1\nfoo2\nfoo = bar\n") + end + it 'should do nothing if the exact line already exists' do + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo = bar\nfoo2") + end + @provider.exists?.should be_true + @provider.create + File.read(@tmpfile).chomp.should eql("foo1\nfoo = bar\nfoo2") + end + end + + describe 'using after' do + let :resource do + Puppet::Type::File_line.new( + { + :name => 'foo', + :path => @tmpfile, + :line => 'inserted = line', + :after => '^foo1', + } + ) + end + + let :provider do + provider_class.new(resource) + end + + context 'with one line matching the after expression' do + before :each do + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") + end + end + + it 'inserts the specified line after the line matching the "after" expression' do + provider.create + File.read(@tmpfile).chomp.should eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo = baz") + end + end + + context 'with two lines matching the after expression' do + before :each do + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo = blah\nfoo2\nfoo1\nfoo = baz") + end + end + + it 'errors out stating "One or no line must match the pattern"' do + expect { provider.create }.to raise_error(Puppet::Error, /One or no line must match the pattern/) + end + end + + context 'with no lines matching the after expression' do + let :content do + "foo3\nfoo = blah\nfoo2\nfoo = baz\n" + end + + before :each do + File.open(@tmpfile, 'w') do |fh| + fh.write(content) + end + end + + it 'appends the specified line to the file' do + provider.create + File.read(@tmpfile).should eq(content << resource[:line] << "\n") + end + end + end + end + + context "when removing" do + before :each do + # TODO: these should be ported over to use the PuppetLabs spec_helper + # file fixtures once the following pull request has been merged: + # https://github.com/puppetlabs/puppetlabs-stdlib/pull/73/files + tmp = Tempfile.new('tmp') + @tmpfile = tmp.path + tmp.close! + @resource = Puppet::Type::File_line.new( + {:name => 'foo', :path => @tmpfile, :line => 'foo', :ensure => 'absent' } + ) + @provider = provider_class.new(@resource) + end + it 'should remove the line if it exists' do + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo\nfoo2") + end + @provider.destroy + File.read(@tmpfile).should eql("foo1\nfoo2") + end + + it 'should remove the line without touching the last new line' do + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo\nfoo2\n") + end + @provider.destroy + File.read(@tmpfile).should eql("foo1\nfoo2\n") + end + + it 'should remove any occurence of the line' do + File.open(@tmpfile, 'w') do |fh| + fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") + end + @provider.destroy + File.read(@tmpfile).should eql("foo1\nfoo2\n") + end + end +end diff --git a/modules/stdlib/spec/unit/puppet/type/anchor_spec.rb b/modules/stdlib/spec/unit/puppet/type/anchor_spec.rb new file mode 100755 index 0000000..f92065f --- /dev/null +++ b/modules/stdlib/spec/unit/puppet/type/anchor_spec.rb @@ -0,0 +1,11 @@ +#!/usr/bin/env ruby + +require 'spec_helper' + +anchor = Puppet::Type.type(:anchor).new(:name => "ntp::begin") + +describe anchor do + it "should stringify normally" do + anchor.to_s.should == "Anchor[ntp::begin]" + end +end diff --git a/modules/stdlib/spec/unit/puppet/type/file_line_spec.rb b/modules/stdlib/spec/unit/puppet/type/file_line_spec.rb new file mode 100755 index 0000000..ab5b81b --- /dev/null +++ b/modules/stdlib/spec/unit/puppet/type/file_line_spec.rb @@ -0,0 +1,70 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' +require 'tempfile' +describe Puppet::Type.type(:file_line) do + let :file_line do + Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'line', :path => '/tmp/path') + end + it 'should accept a line and path' do + file_line[:line] = 'my_line' + file_line[:line].should == 'my_line' + file_line[:path] = '/my/path' + file_line[:path].should == '/my/path' + end + it 'should accept a match regex' do + file_line[:match] = '^foo.*$' + file_line[:match].should == '^foo.*$' + end + it 'should not accept a match regex that does not match the specified line' do + expect { + Puppet::Type.type(:file_line).new( + :name => 'foo', + :path => '/my/path', + :line => 'foo=bar', + :match => '^bar=blah$' + )}.to raise_error(Puppet::Error, /the value must be a regex that matches/) + end + it 'should accept a match regex that does match the specified line' do + expect { + Puppet::Type.type(:file_line).new( + :name => 'foo', + :path => '/my/path', + :line => 'foo=bar', + :match => '^\s*foo=.*$' + )}.not_to raise_error + end + it 'should accept posix filenames' do + file_line[:path] = '/tmp/path' + file_line[:path].should == '/tmp/path' + end + it 'should not accept unqualified path' do + expect { file_line[:path] = 'file' }.to raise_error(Puppet::Error, /File paths must be fully qualified/) + end + it 'should require that a line is specified' do + expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => '/tmp/file') }.to raise_error(Puppet::Error, /Both line and path are required attributes/) + end + it 'should require that a file is specified' do + expect { Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'path') }.to raise_error(Puppet::Error, /Both line and path are required attributes/) + end + it 'should default to ensure => present' do + file_line[:ensure].should eq :present + end + + it "should autorequire the file it manages" do + catalog = Puppet::Resource::Catalog.new + file = Puppet::Type.type(:file).new(:name => "/tmp/path") + catalog.add_resource file + catalog.add_resource file_line + + relationship = file_line.autorequire.find do |rel| + (rel.source.to_s == "File[/tmp/path]") and (rel.target.to_s == file_line.to_s) + end + relationship.should be_a Puppet::Relationship + end + + it "should not autorequire the file it manages if it is not managed" do + catalog = Puppet::Resource::Catalog.new + catalog.add_resource file_line + file_line.autorequire.should be_empty + end +end diff --git a/modules/stdlib/tests/file_line.pp b/modules/stdlib/tests/file_line.pp new file mode 100644 index 0000000..eea693e --- /dev/null +++ b/modules/stdlib/tests/file_line.pp @@ -0,0 +1,9 @@ +# This is a simple smoke test +# of the file_line resource type. +file { '/tmp/dansfile': + ensure => present +}-> +file_line { 'dans_line': + line => 'dan is awesome', + path => '/tmp/dansfile', +} diff --git a/modules/stdlib/tests/has_interface_with.pp b/modules/stdlib/tests/has_interface_with.pp new file mode 100644 index 0000000..e1f1353 --- /dev/null +++ b/modules/stdlib/tests/has_interface_with.pp @@ -0,0 +1,10 @@ +include stdlib +info('has_interface_with(\'lo\'):', has_interface_with('lo')) +info('has_interface_with(\'loX\'):', has_interface_with('loX')) +info('has_interface_with(\'ipaddress\', \'127.0.0.1\'):', has_interface_with('ipaddress', '127.0.0.1')) +info('has_interface_with(\'ipaddress\', \'127.0.0.100\'):', has_interface_with('ipaddress', '127.0.0.100')) +info('has_interface_with(\'network\', \'127.0.0.0\'):', has_interface_with('network', '127.0.0.0')) +info('has_interface_with(\'network\', \'128.0.0.0\'):', has_interface_with('network', '128.0.0.0')) +info('has_interface_with(\'netmask\', \'255.0.0.0\'):', has_interface_with('netmask', '255.0.0.0')) +info('has_interface_with(\'netmask\', \'256.0.0.0\'):', has_interface_with('netmask', '256.0.0.0')) + diff --git a/modules/stdlib/tests/has_ip_address.pp b/modules/stdlib/tests/has_ip_address.pp new file mode 100644 index 0000000..8429a88 --- /dev/null +++ b/modules/stdlib/tests/has_ip_address.pp @@ -0,0 +1,3 @@ +include stdlib +info('has_ip_address(\'192.168.1.256\'):', has_ip_address('192.168.1.256')) +info('has_ip_address(\'127.0.0.1\'):', has_ip_address('127.0.0.1')) diff --git a/modules/stdlib/tests/has_ip_network.pp b/modules/stdlib/tests/has_ip_network.pp new file mode 100644 index 0000000..a15d8c0 --- /dev/null +++ b/modules/stdlib/tests/has_ip_network.pp @@ -0,0 +1,4 @@ +include stdlib +info('has_ip_network(\'127.0.0.0\'):', has_ip_network('127.0.0.0')) +info('has_ip_network(\'128.0.0.0\'):', has_ip_network('128.0.0.0')) + diff --git a/modules/stdlib/tests/init.pp b/modules/stdlib/tests/init.pp new file mode 100644 index 0000000..9675d83 --- /dev/null +++ b/modules/stdlib/tests/init.pp @@ -0,0 +1 @@ +include stdlib