diff options
211 files changed, 2008 insertions, 1230 deletions
diff --git a/.rubocop.yml b/.rubocop.yml index b587000ad4..0c874566be 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -30,3 +30,11 @@ Lint/IneffectiveAccessModifier: Enabled: false Lint/ShadowedException: Enabled: false + +# set additional paths +ChefRuby/UnlessDefinedRequire: + Include: + - 'lib/**/*' + - 'chef-bin/**/*' + - 'chef-config/lib/**/*' + - 'chef-utils/lib/**/*' diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b78eb8320..f00bec72fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,78 +1,106 @@ <!-- usage documentation: http://expeditor-docs.es.chef.io/configuration/changelog/ --> -<!-- latest_release 16.5.51 --> -## [v16.5.51](https://github.com/chef/chef/tree/v16.5.51) (2020-09-10) +<!-- latest_release --> +<!-- latest_release --> + +<!-- release_rollup --> +<!-- release_rollup --> + +<!-- latest_stable_release --> +## [v16.5.77](https://github.com/chef/chef/tree/v16.5.77) (2020-09-29) #### Merged Pull Requests -- Update sysctl resource description to match reality [#10416](https://github.com/chef/chef/pull/10416) ([tas50](https://github.com/tas50)) -<!-- latest_release --> +- Add missing requires to chef/policy_builder/dynamic [#10446](https://github.com/chef/chef/pull/10446) ([tas50](https://github.com/tas50)) +- Pull in the new tty-table to unlock new license-acceptance [#10450](https://github.com/chef/chef/pull/10450) ([tas50](https://github.com/tas50)) +- Check for full names in Homebrew package info [#10360](https://github.com/chef/chef/pull/10360) ([ed-brex](https://github.com/ed-brex)) +- Remove unused method [#10449](https://github.com/chef/chef/pull/10449) ([007lva](https://github.com/007lva)) +- Fix examples markdown in chef_handler resource. [#10459](https://github.com/chef/chef/pull/10459) ([phiggins](https://github.com/phiggins)) +- Simplify Hash transforms & minor code refactoring [#10447](https://github.com/chef/chef/pull/10447) ([vsingh-msys](https://github.com/vsingh-msys)) +- Update require gating to include chef-utils/chef-config & gate more [#10451](https://github.com/chef/chef/pull/10451) ([tas50](https://github.com/tas50)) +- Use ChefUtils::Dist::Infra::PRODUCT for locale warning instead of "Chef" [#10461](https://github.com/chef/chef/pull/10461) ([ramereth](https://github.com/ramereth)) +- Preparing 16.5 hotfix patch to fix Workstation build issue [#10462](https://github.com/chef/chef/pull/10462) ([tyler-ball](https://github.com/tyler-ball)) +- autoload addressable/uri on :URI inside addressable module [#10464](https://github.com/chef/chef/pull/10464) ([mwrock](https://github.com/mwrock)) +- Remove unnecessary require. [#10465](https://github.com/chef/chef/pull/10465) ([phiggins](https://github.com/phiggins)) +- Use Ruby 2.6 endless Range syntax [#10463](https://github.com/chef/chef/pull/10463) ([007lva](https://github.com/007lva)) +- Bump dependencies to latest + resolve Chefstyle warning [#10468](https://github.com/chef/chef/pull/10468) ([tas50](https://github.com/tas50)) +<!-- latest_stable_release --> -<!-- release_rollup since=16.4.41 --> -### Changes not yet released to stable +## [v16.5.64](https://github.com/chef/chef/tree/v16.5.64) (2020-09-17) #### Merged Pull Requests -- Update sysctl resource description to match reality [#10416](https://github.com/chef/chef/pull/10416) ([tas50](https://github.com/tas50)) <!-- 16.5.51 --> -- Add system_name property to rhsm_register resource [#10413](https://github.com/chef/chef/pull/10413) ([jasonwbarnett](https://github.com/jasonwbarnett)) <!-- 16.5.50 --> -- Remove debug puts from snap_package [#10409](https://github.com/chef/chef/pull/10409) ([tas50](https://github.com/tas50)) <!-- 16.5.49 --> -- Update the windows_firewall_profile resource to fix NoMethodError [#10412](https://github.com/chef/chef/pull/10412) ([chef-davin](https://github.com/chef-davin)) <!-- 16.5.48 --> -- Add an ohai timing test to find busted DNS on CI testers [#10371](https://github.com/chef/chef/pull/10371) ([lamont-granquist](https://github.com/lamont-granquist)) <!-- 16.5.47 --> -- Use __dir__ instead of getting the dir of __FILE__ [#10401](https://github.com/chef/chef/pull/10401) ([tas50](https://github.com/tas50)) <!-- 16.5.46 --> -- Allow cpu_quota values > 100 [#10408](https://github.com/chef/chef/pull/10408) ([tas50](https://github.com/tas50)) <!-- 16.5.45 --> -- Allow for license-acceptance 2.0 gem [#10406](https://github.com/chef/chef/pull/10406) ([tas50](https://github.com/tas50)) <!-- 16.5.44 --> -- Enable s390x RHEL8 and SLES15 platforms [#10376](https://github.com/chef/chef/pull/10376) ([jaymalasinha](https://github.com/jaymalasinha)) <!-- 16.5.43 --> -- autoload license_acceptance/acceptor in knife loading [#10405](https://github.com/chef/chef/pull/10405) ([mwrock](https://github.com/mwrock)) <!-- 16.5.42 --> -- Add Patents link to chef infra & solo client [#10400](https://github.com/chef/chef/pull/10400) ([vsingh-msys](https://github.com/vsingh-msys)) <!-- 16.5.41 --> -- Remove a redundant spec loop [#10370](https://github.com/chef/chef/pull/10370) ([tas50](https://github.com/tas50)) <!-- 16.5.40 --> -- Update openssl to 1.0.2w [#10402](https://github.com/chef/chef/pull/10402) ([tas50](https://github.com/tas50)) <!-- 16.5.40 --> -- Update Ohai to 16.5 [#10399](https://github.com/chef/chef/pull/10399) ([tas50](https://github.com/tas50)) <!-- 16.5.39 --> -- Mock File.expand_path to fix window C:/ dir appended in absolute path [#10398](https://github.com/chef/chef/pull/10398) ([vsingh-msys](https://github.com/vsingh-msys)) <!-- 16.5.38 --> -- Use include? to example strings when we don't need a regex [#10396](https://github.com/chef/chef/pull/10396) ([tas50](https://github.com/tas50)) <!-- 16.5.38 --> -- rhsm_register: Avoid potentially checking if we need to register twice [#10395](https://github.com/chef/chef/pull/10395) ([tas50](https://github.com/tas50)) <!-- 16.5.37 --> -- Improve cli boot performance by prefering autoload over requires [#10383](https://github.com/chef/chef/pull/10383) ([mwrock](https://github.com/mwrock)) <!-- 16.5.36 --> -- [data-collector] improved output_locations validation & bug fixes [#10393](https://github.com/chef/chef/pull/10393) ([vsingh-msys](https://github.com/vsingh-msys)) <!-- 16.5.35 --> -- Resolve RuboCop Style/RedundantInterpolation warnings [#10394](https://github.com/chef/chef/pull/10394) ([tas50](https://github.com/tas50)) <!-- 16.5.34 --> -- chef_client_launchd: create a launchd daemon to handle the client restart [#10390](https://github.com/chef/chef/pull/10390) ([tas50](https://github.com/tas50)) <!-- 16.5.33 --> -- Add --logfile to chef-apply command [#10389](https://github.com/chef/chef/pull/10389) ([tas50](https://github.com/tas50)) <!-- 16.5.32 --> -- Add a :reboot_delay property to the windows_ad_join resource [#10388](https://github.com/chef/chef/pull/10388) ([chef-davin](https://github.com/chef-davin)) <!-- 16.5.31 --> -- Fix nil deep_merging [#10382](https://github.com/chef/chef/pull/10382) ([lamont-granquist](https://github.com/lamont-granquist)) <!-- 16.5.30 --> -- Allow removing profiles in osx_profile on Big Sur [#10386](https://github.com/chef/chef/pull/10386) ([tas50](https://github.com/tas50)) <!-- 16.5.29 --> -- Update all deps to current [#10385](https://github.com/chef/chef/pull/10385) ([tas50](https://github.com/tas50)) <!-- 16.5.28 --> -- chef_client_systemd_timer: Add the ability to set CPUQuota on the chef-client unit [#10381](https://github.com/chef/chef/pull/10381) ([tas50](https://github.com/tas50)) <!-- 16.5.27 --> -- Remove duplicate requires in the Provider class [#10369](https://github.com/chef/chef/pull/10369) ([tas50](https://github.com/tas50)) <!-- 16.5.26 --> -- More updates to the chef_client_* resources [#10362](https://github.com/chef/chef/pull/10362) ([tas50](https://github.com/tas50)) <!-- 16.5.25 --> -- Fixed mount Resource for bind mounts is not idempotent. [#10171](https://github.com/chef/chef/pull/10171) ([antima-gupta](https://github.com/antima-gupta)) <!-- 16.5.24 --> -- Update InSpec to 4.22.22 [#10363](https://github.com/chef/chef/pull/10363) ([tas50](https://github.com/tas50)) <!-- 16.5.23 --> -- chef_client_launchd: reorder properties and fix log permissions [#10361](https://github.com/chef/chef/pull/10361) ([tas50](https://github.com/tas50)) <!-- 16.5.22 --> -- Improve input handling and validation in chef_client_launchd [#10357](https://github.com/chef/chef/pull/10357) ([tas50](https://github.com/tas50)) <!-- 16.5.21 --> -- Add back nice functionality to chef_client_cron [#10358](https://github.com/chef/chef/pull/10358) ([tas50](https://github.com/tas50)) <!-- 16.5.20 --> -- Validate nice values in the launchd resource [#10359](https://github.com/chef/chef/pull/10359) ([tas50](https://github.com/tas50)) <!-- 16.5.19 --> -- more config specs cleanup & remove deprecated from knife config list [#10351](https://github.com/chef/chef/pull/10351) ([vsingh-msys](https://github.com/vsingh-msys)) <!-- 16.5.18 --> -- Update Ohai to 16.4.13 [#10353](https://github.com/chef/chef/pull/10353) ([tas50](https://github.com/tas50)) <!-- 16.5.17 --> -- Fix habitat test script [#10350](https://github.com/chef/chef/pull/10350) ([phiggins](https://github.com/phiggins)) <!-- 16.5.16 --> -- Add initial take at chef_client_launchd [#10348](https://github.com/chef/chef/pull/10348) ([tas50](https://github.com/tas50)) <!-- 16.5.15 --> -- Bump deps and resolve new Chefstyle warnings [#10349](https://github.com/chef/chef/pull/10349) ([tas50](https://github.com/tas50)) <!-- 16.5.14 --> -- Fix some CI failures [#10347](https://github.com/chef/chef/pull/10347) ([phiggins](https://github.com/phiggins)) <!-- 16.5.13 --> -- Fix dll copying in Gemfile to remove Dir.pwd [#10325](https://github.com/chef/chef/pull/10325) ([lamont-granquist](https://github.com/lamont-granquist)) <!-- 16.5.12 --> -- knife config list-profiles UI with tty-table [#10341](https://github.com/chef/chef/pull/10341) ([vsingh-msys](https://github.com/vsingh-msys)) <!-- 16.5.11 --> -- make 'knife config' options shorter/easier [#10346](https://github.com/chef/chef/pull/10346) ([vsingh-msys](https://github.com/vsingh-msys)) <!-- 16.5.10 --> -- Add macOS 11.0 (Big Sur) packages [#10332](https://github.com/chef/chef/pull/10332) ([tas50](https://github.com/tas50)) <!-- 16.5.9 --> -- separate omnibus rspec path from options [#10343](https://github.com/chef/chef/pull/10343) ([mwrock](https://github.com/mwrock)) <!-- 16.5.8 --> -- Start building S390x packages again [#10338](https://github.com/chef/chef/pull/10338) ([btm](https://github.com/btm)) <!-- 16.5.7 --> -- Avoid knife ssh freeze on windows [#9482](https://github.com/chef/chef/pull/9482) ([dheerajd-msys](https://github.com/dheerajd-msys)) <!-- 16.5.6 --> -- fix chocolatey and x86 windows omnibus builds [#10339](https://github.com/chef/chef/pull/10339) ([mwrock](https://github.com/mwrock)) <!-- 16.5.5 --> -- Bump all deps to the latest for the require optimizations [#10337](https://github.com/chef/chef/pull/10337) ([tas50](https://github.com/tas50)) <!-- 16.5.4 --> -- New exit code to signal chef-client exits due to configuration errors [#10302](https://github.com/chef/chef/pull/10302) ([NaomiReeves](https://github.com/NaomiReeves)) <!-- 16.5.3 --> -- Simplify macos detection in specs to include big sur [#10335](https://github.com/chef/chef/pull/10335) ([tas50](https://github.com/tas50)) <!-- 16.5.2 --> -- Add new chef_client_trusted_certificate resource [#10331](https://github.com/chef/chef/pull/10331) ([tas50](https://github.com/tas50)) <!-- 16.5.0 --> -<!-- release_rollup --> +- Add new chef_client_trusted_certificate resource [#10331](https://github.com/chef/chef/pull/10331) ([tas50](https://github.com/tas50)) +- Simplify macos detection in specs to include big sur [#10335](https://github.com/chef/chef/pull/10335) ([tas50](https://github.com/tas50)) +- New exit code to signal chef-client exits due to configuration errors [#10302](https://github.com/chef/chef/pull/10302) ([NaomiReeves](https://github.com/NaomiReeves)) +- Bump all deps to the latest for the require optimizations [#10337](https://github.com/chef/chef/pull/10337) ([tas50](https://github.com/tas50)) +- fix chocolatey and x86 windows omnibus builds [#10339](https://github.com/chef/chef/pull/10339) ([mwrock](https://github.com/mwrock)) +- Avoid knife ssh freeze on windows [#9482](https://github.com/chef/chef/pull/9482) ([dheerajd-msys](https://github.com/dheerajd-msys)) +- Start building S390x packages again [#10338](https://github.com/chef/chef/pull/10338) ([btm](https://github.com/btm)) +- separate omnibus rspec path from options [#10343](https://github.com/chef/chef/pull/10343) ([mwrock](https://github.com/mwrock)) +- Add macOS 11.0 (Big Sur) packages [#10332](https://github.com/chef/chef/pull/10332) ([tas50](https://github.com/tas50)) +- make 'knife config' options shorter/easier [#10346](https://github.com/chef/chef/pull/10346) ([vsingh-msys](https://github.com/vsingh-msys)) +- knife config list-profiles UI with tty-table [#10341](https://github.com/chef/chef/pull/10341) ([vsingh-msys](https://github.com/vsingh-msys)) +- Fix dll copying in Gemfile to remove Dir.pwd [#10325](https://github.com/chef/chef/pull/10325) ([lamont-granquist](https://github.com/lamont-granquist)) +- Fix some CI failures [#10347](https://github.com/chef/chef/pull/10347) ([phiggins](https://github.com/phiggins)) +- Bump deps and resolve new Chefstyle warnings [#10349](https://github.com/chef/chef/pull/10349) ([tas50](https://github.com/tas50)) +- Add initial take at chef_client_launchd [#10348](https://github.com/chef/chef/pull/10348) ([tas50](https://github.com/tas50)) +- Fix habitat test script [#10350](https://github.com/chef/chef/pull/10350) ([phiggins](https://github.com/phiggins)) +- Update Ohai to 16.4.13 [#10353](https://github.com/chef/chef/pull/10353) ([tas50](https://github.com/tas50)) +- more config specs cleanup & remove deprecated from knife config list [#10351](https://github.com/chef/chef/pull/10351) ([vsingh-msys](https://github.com/vsingh-msys)) +- Validate nice values in the launchd resource [#10359](https://github.com/chef/chef/pull/10359) ([tas50](https://github.com/tas50)) +- Add back nice functionality to chef_client_cron [#10358](https://github.com/chef/chef/pull/10358) ([tas50](https://github.com/tas50)) +- Improve input handling and validation in chef_client_launchd [#10357](https://github.com/chef/chef/pull/10357) ([tas50](https://github.com/tas50)) +- chef_client_launchd: reorder properties and fix log permissions [#10361](https://github.com/chef/chef/pull/10361) ([tas50](https://github.com/tas50)) +- Update InSpec to 4.22.22 [#10363](https://github.com/chef/chef/pull/10363) ([tas50](https://github.com/tas50)) +- Fixed mount Resource for bind mounts is not idempotent. [#10171](https://github.com/chef/chef/pull/10171) ([antima-gupta](https://github.com/antima-gupta)) +- More updates to the chef_client_* resources [#10362](https://github.com/chef/chef/pull/10362) ([tas50](https://github.com/tas50)) +- Remove duplicate requires in the Provider class [#10369](https://github.com/chef/chef/pull/10369) ([tas50](https://github.com/tas50)) +- chef_client_systemd_timer: Add the ability to set CPUQuota on the chef-client unit [#10381](https://github.com/chef/chef/pull/10381) ([tas50](https://github.com/tas50)) +- Update all deps to current [#10385](https://github.com/chef/chef/pull/10385) ([tas50](https://github.com/tas50)) +- Allow removing profiles in osx_profile on Big Sur [#10386](https://github.com/chef/chef/pull/10386) ([tas50](https://github.com/tas50)) +- Fix nil deep_merging [#10382](https://github.com/chef/chef/pull/10382) ([lamont-granquist](https://github.com/lamont-granquist)) +- Add a :reboot_delay property to the windows_ad_join resource [#10388](https://github.com/chef/chef/pull/10388) ([chef-davin](https://github.com/chef-davin)) +- Add --logfile to chef-apply command [#10389](https://github.com/chef/chef/pull/10389) ([tas50](https://github.com/tas50)) +- chef_client_launchd: create a launchd daemon to handle the client restart [#10390](https://github.com/chef/chef/pull/10390) ([tas50](https://github.com/tas50)) +- Resolve RuboCop Style/RedundantInterpolation warnings [#10394](https://github.com/chef/chef/pull/10394) ([tas50](https://github.com/tas50)) +- [data-collector] improved output_locations validation & bug fixes [#10393](https://github.com/chef/chef/pull/10393) ([vsingh-msys](https://github.com/vsingh-msys)) +- Improve cli boot performance by prefering autoload over requires [#10383](https://github.com/chef/chef/pull/10383) ([mwrock](https://github.com/mwrock)) +- rhsm_register: Avoid potentially checking if we need to register twice [#10395](https://github.com/chef/chef/pull/10395) ([tas50](https://github.com/tas50)) +- Use include? to example strings when we don't need a regex [#10396](https://github.com/chef/chef/pull/10396) ([tas50](https://github.com/tas50)) +- Mock File.expand_path to fix window C:/ dir appended in absolute path [#10398](https://github.com/chef/chef/pull/10398) ([vsingh-msys](https://github.com/vsingh-msys)) +- Update Ohai to 16.5 [#10399](https://github.com/chef/chef/pull/10399) ([tas50](https://github.com/tas50)) +- Update openssl to 1.0.2w [#10402](https://github.com/chef/chef/pull/10402) ([tas50](https://github.com/tas50)) +- Remove a redundant spec loop [#10370](https://github.com/chef/chef/pull/10370) ([tas50](https://github.com/tas50)) +- Add Patents link to chef infra & solo client [#10400](https://github.com/chef/chef/pull/10400) ([vsingh-msys](https://github.com/vsingh-msys)) +- autoload license_acceptance/acceptor in knife loading [#10405](https://github.com/chef/chef/pull/10405) ([mwrock](https://github.com/mwrock)) +- Enable s390x RHEL8 and SLES15 platforms [#10376](https://github.com/chef/chef/pull/10376) ([jaymalasinha](https://github.com/jaymalasinha)) +- Allow for license-acceptance 2.0 gem [#10406](https://github.com/chef/chef/pull/10406) ([tas50](https://github.com/tas50)) +- Allow cpu_quota values > 100 [#10408](https://github.com/chef/chef/pull/10408) ([tas50](https://github.com/tas50)) +- Use __dir__ instead of getting the dir of __FILE__ [#10401](https://github.com/chef/chef/pull/10401) ([tas50](https://github.com/tas50)) +- Add an ohai timing test to find busted DNS on CI testers [#10371](https://github.com/chef/chef/pull/10371) ([lamont-granquist](https://github.com/lamont-granquist)) +- Update the windows_firewall_profile resource to fix NoMethodError [#10412](https://github.com/chef/chef/pull/10412) ([chef-davin](https://github.com/chef-davin)) +- Remove debug puts from snap_package [#10409](https://github.com/chef/chef/pull/10409) ([tas50](https://github.com/tas50)) +- Add system_name property to rhsm_register resource [#10413](https://github.com/chef/chef/pull/10413) ([jasonwbarnett](https://github.com/jasonwbarnett)) +- Update sysctl resource description to match reality [#10416](https://github.com/chef/chef/pull/10416) ([tas50](https://github.com/tas50)) +- allow the use of SIDs in windows securable resources [#10423](https://github.com/chef/chef/pull/10423) ([mwrock](https://github.com/mwrock)) +- Update the validation of the privilege property on the windows_user_privilege resource [#10422](https://github.com/chef/chef/pull/10422) ([tas50](https://github.com/tas50)) +- Remove the Ubuntu azure pipeline test [#10434](https://github.com/chef/chef/pull/10434) ([tas50](https://github.com/tas50)) +- Move dist implementation into chef-utils [#9834](https://github.com/chef/chef/pull/9834) ([bobchaos](https://github.com/bobchaos)) +- Add examples to the ohai resource [#10432](https://github.com/chef/chef/pull/10432) ([tas50](https://github.com/tas50)) +- Move TrainTransport to ChefConfig [#10436](https://github.com/chef/chef/pull/10436) ([lamont-granquist](https://github.com/lamont-granquist)) +- More resource documentation improvements [#10435](https://github.com/chef/chef/pull/10435) ([tas50](https://github.com/tas50)) +- Resolve Lint/RedundantRequireStatement & Style/RedundantCondition warnings [#10437](https://github.com/chef/chef/pull/10437) ([tas50](https://github.com/tas50)) +- Speed up a openssl helper specs [#10438](https://github.com/chef/chef/pull/10438) ([tas50](https://github.com/tas50)) +- Resolve Style/RedundantSort warnings [#10439](https://github.com/chef/chef/pull/10439) ([tas50](https://github.com/tas50)) +- Docs fixes from review [#10440](https://github.com/chef/chef/pull/10440) ([tas50](https://github.com/tas50)) +- Update InSpec to the latest [#10443](https://github.com/chef/chef/pull/10443) ([tas50](https://github.com/tas50)) +- Fix idempotency in the osx_profile resource and avoid writing data to disk [#10444](https://github.com/chef/chef/pull/10444) ([tas50](https://github.com/tas50)) +- Update to the latest license_scout gem [#10445](https://github.com/chef/chef/pull/10445) ([tas50](https://github.com/tas50)) -<!-- latest_stable_release --> ## [v16.4.41](https://github.com/chef/chef/tree/v16.4.41) (2020-08-19) #### Merged Pull Requests - Refactor the timezone resource to properly load the current timezone [#10323](https://github.com/chef/chef/pull/10323) ([tas50](https://github.com/tas50)) - Add missing requires for knife configure command [#10329](https://github.com/chef/chef/pull/10329) ([tas50](https://github.com/tas50)) - Update Ohai to 16.4.11 to resolve Windows IP detection [#10327](https://github.com/chef/chef/pull/10327) ([tas50](https://github.com/tas50)) -<!-- latest_stable_release --> ## [v16.4.38](https://github.com/chef/chef/tree/v16.4.38) (2020-08-18) diff --git a/Dockerfile b/Dockerfile index 86359f927e..70aed5aa58 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,7 +18,7 @@ FROM busybox LABEL maintainer="Chef Software, Inc. <docker@chef.io>" ARG CHANNEL=stable -ARG VERSION=16.4.41 +ARG VERSION=16.5.77 RUN wget "http://packages.chef.io/files/${CHANNEL}/chef/${VERSION}/el/6/chef-${VERSION}-1.el6.x86_64.rpm" -O /tmp/chef-client.rpm && \ rpm2cpio /tmp/chef-client.rpm | cpio -idmv && \ diff --git a/Gemfile.lock b/Gemfile.lock index 82bd8a9ad1..dd2e50c5b1 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,17 +1,17 @@ GIT remote: https://github.com/chef/chefstyle.git - revision: 60af74b74133400864b8f792cd2dae5724190a54 + revision: 7e828c793e50bb955389fc8064a2562727d82912 branch: master specs: - chefstyle (1.3.2) - rubocop (= 0.90) + chefstyle (1.4.2) + rubocop (= 0.92.0) GIT remote: https://github.com/chef/ohai.git - revision: 483240891921d72f172067d15a50a97d52761c4b + revision: e0d81b68c3b78712e0c34ce14ff60d7dcc662d25 branch: master specs: - ohai (16.5.0) + ohai (16.5.6) chef-config (>= 12.8, < 17) chef-utils (>= 16.0, < 17) ffi (~> 1.9) @@ -27,12 +27,12 @@ GIT PATH remote: . specs: - chef (16.5.51) + chef (16.5.77) addressable bcrypt_pbkdf (= 1.1.0.rc1) bundler (>= 1.10) - chef-config (= 16.5.51) - chef-utils (= 16.5.51) + chef-config (= 16.5.77) + chef-utils (= 16.5.77) chef-vault chef-zero (>= 14.0.11) diff-lcs (>= 1.2.4, < 1.4.0) @@ -61,14 +61,14 @@ PATH train-winrm (>= 0.2.5) tty-prompt (~> 0.21) tty-screen (~> 0.6) - tty-table (~> 0.11.0) + tty-table (~> 0.11) uuidtools (~> 2.1.5) - chef (16.5.51-universal-mingw32) + chef (16.5.77-universal-mingw32) addressable bcrypt_pbkdf (= 1.1.0.rc1) bundler (>= 1.10) - chef-config (= 16.5.51) - chef-utils (= 16.5.51) + chef-config (= 16.5.77) + chef-utils (= 16.5.77) chef-vault chef-zero (>= 14.0.11) diff-lcs (>= 1.2.4, < 1.4.0) @@ -98,7 +98,7 @@ PATH train-winrm (>= 0.2.5) tty-prompt (~> 0.21) tty-screen (~> 0.6) - tty-table (~> 0.11.0) + tty-table (~> 0.11) uuidtools (~> 2.1.5) win32-api (~> 1.5.3) win32-certstore (~> 0.3) @@ -114,15 +114,15 @@ PATH PATH remote: chef-bin specs: - chef-bin (16.5.51) - chef (= 16.5.51) + chef-bin (16.5.77) + chef (= 16.5.77) PATH remote: chef-config specs: - chef-config (16.5.51) + chef-config (16.5.77) addressable - chef-utils (= 16.5.51) + chef-utils (= 16.5.77) fuzzyurl mixlib-config (>= 2.2.12, < 4.0) mixlib-shellout (>= 2.0, < 4.0) @@ -131,7 +131,7 @@ PATH PATH remote: chef-utils specs: - chef-utils (16.5.51) + chef-utils (16.5.77) GEM remote: https://rubygems.org/ @@ -153,8 +153,8 @@ GEM chef-config concurrent-ruby (~> 1.0) ffi-yajl (~> 2.2) - chef-vault (4.0.11) - chef-zero (15.0.2) + chef-vault (4.0.12) + chef-zero (15.0.3) ffi-yajl (~> 2.2) hashie (>= 2.0, < 5.0) mixlib-log (>= 2.0, < 4.0) @@ -165,14 +165,12 @@ GEM net-ssh coderay (1.1.3) concurrent-ruby (1.1.7) - crack (0.4.3) - safe_yaml (~> 1.0.0) + crack (0.4.4) debug_inspector (0.0.3) diff-lcs (1.3) ecma-re-validator (0.2.1) regexp_parser (~> 1.2) ed25519 (1.2.4) - equatable (0.6.1) erubi (1.9.0) erubis (2.7.0) faraday (1.0.1) @@ -199,13 +197,13 @@ GEM highline (2.0.3) httpclient (2.8.3) iniparse (1.5.0) - inspec-core (4.22.22) + inspec-core (4.23.11) addressable (~> 2.4) chef-telemetry (~> 1.0) - faraday (>= 0.9.0) + faraday (>= 0.9.0, < 1.1) hashie (~> 3.4) json_schemer (>= 0.2.1, < 0.2.12) - license-acceptance (>= 0.2.13, < 2.0) + license-acceptance (>= 0.2.13, < 3.0) method_source (>= 0.8, < 2.0) mixlib-log (~> 3.0) multipart-post (~> 2.0) @@ -222,8 +220,8 @@ GEM train-core (~> 3.0) tty-prompt (~> 0.17) tty-table (~> 0.10) - inspec-core-bin (4.22.22) - inspec-core (= 4.22.22) + inspec-core-bin (4.23.11) + inspec-core (= 4.23.11) ipaddress (0.8.3) iso8601 (0.13.0) json (2.3.1) @@ -233,11 +231,11 @@ GEM regexp_parser (~> 1.5) uri_template (~> 0.7) libyajl2 (1.2.0) - license-acceptance (1.0.19) + license-acceptance (2.1.2) pastel (~> 0.7) tomlrb (~> 1.2) - tty-box (~> 0.3) - tty-prompt (~> 0.18) + tty-box (~> 0.6) + tty-prompt (~> 0.20) little-plugger (1.1.4) logging (2.3.0) little-plugger (~> 1.1) @@ -252,15 +250,14 @@ GEM mixlib-config (3.0.9) tomlrb mixlib-log (3.0.9) - mixlib-shellout (3.1.4) + mixlib-shellout (3.1.6) chef-utils - mixlib-shellout (3.1.4-universal-mingw32) + mixlib-shellout (3.1.6-universal-mingw32) chef-utils win32-process (~> 0.8.2) wmi-lite (~> 1.0) multi_json (1.15.0) multipart-post (2.1.1) - necromancer (0.5.1) net-scp (3.0.0) net-ssh (>= 2.6.5, < 7.0.0) net-sftp (3.0.0) @@ -273,11 +270,10 @@ GEM net-ssh-gateway (>= 1.2.0) nori (2.6.0) parallel (1.19.2) - parser (2.7.1.4) + parser (2.7.1.5) ast (~> 2.4.1) parslet (1.8.2) - pastel (0.7.4) - equatable (~> 0.6) + pastel (0.8.0) tty-color (~> 0.5) plist (3.5.0) proxifier (1.0.3) @@ -298,7 +294,7 @@ GEM rainbow (3.0.0) rake (13.0.1) rb-readline (0.5.5) - regexp_parser (1.7.1) + regexp_parser (1.8.1) rexml (3.2.4) rspec (3.9.0) rspec-core (~> 3.9.0) @@ -319,28 +315,27 @@ GEM rspec_junit_formatter (0.2.3) builder (< 4) rspec-core (>= 2, < 4, != 2.12.0) - rubocop (0.90.0) + rubocop (0.92.0) parallel (~> 1.10) - parser (>= 2.7.1.1) + parser (>= 2.7.1.5) rainbow (>= 2.2.2, < 4.0) regexp_parser (>= 1.7) rexml - rubocop-ast (>= 0.3.0, < 1.0) + rubocop-ast (>= 0.5.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 1.4.0, < 2.0) - rubocop-ast (0.3.0) - parser (>= 2.7.1.4) + rubocop-ast (0.7.1) + parser (>= 2.7.1.5) ruby-prof (1.2.0) ruby-progressbar (1.10.1) ruby-shadow (2.5.0) rubyntlm (0.6.2) rubyzip (1.3.0) - safe_yaml (1.0.5) semverse (3.0.0) slop (3.6.0) sslshake (1.3.1) - strings (0.1.8) - strings-ansi (~> 0.1) + strings (0.2.0) + strings-ansi (~> 0.2) unicode-display_width (~> 1.5) unicode_utils (~> 1.4) strings-ansi (0.2.0) @@ -348,7 +343,7 @@ GEM syslog-logger (1.6.8) thor (1.0.1) tomlrb (1.2.9) - train-core (3.3.16) + train-core (3.3.21) addressable (~> 2.5) ffi (!= 1.13.0) json (>= 1.8, < 3.0) @@ -358,32 +353,29 @@ GEM train-winrm (0.2.6) winrm (~> 2.0) winrm-fs (~> 1.0) - tty-box (0.5.0) - pastel (~> 0.7.2) - strings (~> 0.1.6) + tty-box (0.6.0) + pastel (~> 0.8) + strings (~> 0.2.0) tty-cursor (~> 0.7) tty-color (0.5.2) tty-cursor (0.7.1) - tty-prompt (0.21.0) - necromancer (~> 0.5.0) - pastel (~> 0.7.0) - tty-reader (~> 0.7.0) - tty-reader (0.7.0) + tty-prompt (0.22.0) + pastel (~> 0.8) + tty-reader (~> 0.8) + tty-reader (0.8.0) tty-cursor (~> 0.7) - tty-screen (~> 0.7) - wisper (~> 2.0.0) + tty-screen (~> 0.8) + wisper (~> 2.0) tty-screen (0.8.1) - tty-table (0.11.0) - equatable (~> 0.6) - necromancer (~> 0.5) - pastel (~> 0.7.2) - strings (~> 0.1.5) - tty-screen (~> 0.7) + tty-table (0.12.0) + pastel (~> 0.8) + strings (~> 0.2.0) + tty-screen (~> 0.8) unicode-display_width (1.7.0) unicode_utils (1.4.0) uri_template (0.7.0) uuidtools (2.1.5) - webmock (3.8.3) + webmock (3.9.1) addressable (>= 2.3.6) crack (>= 0.3.2) hashdiff (>= 0.4.0, < 2.0.0) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index e6a7b22798..bf5a0a7138 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,27 +1,141 @@ This file holds "in progress" release notes for the current release under development and is intended for consumption by the Chef Documentation team. Please see <https://docs.chef.io/release_notes/> for the official Chef release notes. -# UNRELEASED - - -To expand upon later: - -- Improved ohai information gathering on on-English systems -- Performance improvements (provide some benchmarks) -- Package data in ohai for macOS -- rhsm_register: reduced load on the Satellite server -- new chef_client_launchd resource -- osx_profile lets you remove profiles on macOS 11 -- chef_client_cron: Added nice property -- Improved output in knife config list-profiles and new shorter knife config commands -- New packages: macOS 11, s390x RHEL 7, s390x SLES 12 -- New chef_client_trusted_certificate -- New exit code 43 when the client config has errors. Thanks @NaomiReeves -- Mount: Improved idempotency on Linux hosts -- chef_client_systemd_timer: Add cpu_quote property -- Resolved knife ssh freezing on Windows nodes -- launched: Improved validation for the values allowed in the nice property -- windows_ad_join: added reboot_delay property -- openssl to 1.0.2w +# Whats New in 16.5.77 + +* Added missing requires to prevent errors when loading `chef/policy_builder/dynamic`. +* The `homebrew_package` resource will now check for the full and short package names. Both `homebrew_package 'homebrew/core/vim'` and `homebrew_package 'vim'` styles should now work correctly. +* Resolved errors that occurred in cookbooks requiring `addressable/uri`. +* Improved the license acceptance flow to give helpful information if the user passes an invalid value in the environment variable or command line argument. +* Updated Chef InSpec to 4.23.11 in order to resolve issues when running the new `junit2` reporter. +* Additional performance improvements to reduce the startup time of the `chef-client` and `knife` commands. +* `knife vault` commands now output proper JSON or YAML when using the `-f json` or `-f yaml` flags. + +# What's New in 16.5 + +## Performance Improvements + +We continue to reduce the size of the Chef Infra Client install and optimize the performance of the client. With Chef Infra Client 16.5 we've greatly reduced the startup time of the `chef-client` process. Startup times on macOS, Linux, and Windows hosts are now approximately 2x faster than the 16.4 release. + +## CLI Improvements + +- The client license acceptance logic has been improved to provide helpful error messages when an incorrect value is passed and to accept license values in any text case. +- A new `chef-client` process exit code of 43 has been added to signal that an invalid configuration was specified. Thanks [@NaomiReeves](https://github.com/NaomiReeves)! +- The `knife ssh` command no longer hangs when connecting to Windows nodes over SSH. +- The `knife config` commands have been renamed to make them shorter and table output has been improved: + - knife config get-profile -> knife config use + - knife config use-profile [NAME] -> knife config use [NAME] + - knife config list-profiles -> knife config list + - knife config get -> knife config show + +## Chef InSpec 4.23.4 + +Chef InSpec has been updated from 4.22.1 to 4.23.4. This new release includes the following improvements: + +- A new mechanism marks inputs as sensitive: true and replaces their values with "***". +- Use the --no-diff CLI option to suppress diff output for textual tests. +- Control the order of controls in output, but not execution order, with the --sort_results_by=none|control|file|random CLI option. +- Disable caching of inputs with a cache_inputs: true setting. + +## New Resources + +### chef_client_launchd + +The `chef_client_launchd` resource allows you to configure Chef Infra Client to run as a global launchd daemon on macOS hosts. This resource mirrors the configuration of other `chef_client_*` resources and allows for simple out-of-the-box configuration of the daemon, while also providing advanced tunables. If you've used the `chef-client` cookbook in the past, you'll notice a number of improvements in the new resource including configuration update handling, splay times support, nice level support, and an out-of-the-box configuration of low IO priority execution. In order to handle restarting the Chef Infra Client launchd daemon when configuration changes occur, the resource also installs a new `com.chef.restarter` daemon. This daemon watches for daemon configuration changes and gracefully handles the restart to ensure the client process continues to run. + +```ruby +chef_client_launchd 'Setup the Chef Infra Client to run every 30 minutes' do + interval 30 + action :enable +end +``` + +### chef_client_trusted_certificate + +The `chef_client_trusted_certificate` resource allows you to add a certificate to Chef Infra Client's trusted certificate directory. The resource handles platform-specific locations and creates the trusted certificates directory if it doesn't already exist. Once a certificate is added, it will be used by the client itself to communicate with the Chef Infra Server and by resources such as `remote_file`. + +```ruby +chef_client_trusted_certificate 'self-signed.badssl.com' do + certificate <<~CERT + -----BEGIN CERTIFICATE----- + MIIDeTCCAmGgAwIBAgIJAPziuikCTox4MA0GCSqGSIb3DQEBCwUAMGIxCzAJBgNV + BAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNp + c2NvMQ8wDQYDVQQKDAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTAeFw0x + OTEwMDkyMzQxNTJaFw0yMTEwMDgyMzQxNTJaMGIxCzAJBgNVBAYTAlVTMRMwEQYD + VQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQ8wDQYDVQQK + DAZCYWRTU0wxFTATBgNVBAMMDCouYmFkc3NsLmNvbTCCASIwDQYJKoZIhvcNAQEB + BQADggEPADCCAQoCggEBAMIE7PiM7gTCs9hQ1XBYzJMY61yoaEmwIrX5lZ6xKyx2 + PmzAS2BMTOqytMAPgLaw+XLJhgL5XEFdEyt/ccRLvOmULlA3pmccYYz2QULFRtMW + hyefdOsKnRFSJiFzbIRMeVXk0WvoBj1IFVKtsyjbqv9u/2CVSndrOfEk0TG23U3A + xPxTuW1CrbV8/q71FdIzSOciccfCFHpsKOo3St/qbLVytH5aohbcabFXRNsKEqve + ww9HdFxBIuGa+RuT5q0iBikusbpJHAwnnqP7i/dAcgCskgjZjFeEU4EFy+b+a1SY + QCeFxxC7c3DvaRhBB0VVfPlkPz0sw6l865MaTIbRyoUCAwEAAaMyMDAwCQYDVR0T + BAIwADAjBgNVHREEHDAaggwqLmJhZHNzbC5jb22CCmJhZHNzbC5jb20wDQYJKoZI + hvcNAQELBQADggEBAGlwCdbPxflZfYOaukZGCaxYK6gpincX4Lla4Ui2WdeQxE95 + w7fChXvP3YkE3UYUE7mupZ0eg4ZILr/A0e7JQDsgIu/SRTUE0domCKgPZ8v99k3A + vka4LpLK51jHJJK7EFgo3ca2nldd97GM0MU41xHFk8qaK1tWJkfrrfcGwDJ4GQPI + iLlm6i0yHq1Qg1RypAXJy5dTlRXlCLd8ufWhhiwW0W75Va5AEnJuqpQrKwl3KQVe + wGj67WWRgLfSr+4QG1mNvCZb2CkjZWmxkGPuoP40/y7Yu5OFqxP5tAjj4YixCYTW + EVA0pmzIzgBg+JIe3PdRy27T0asgQW/F4TY61Yk= + -----END CERTIFICATE----- + CERT +end +``` + +## Resource Updates + +### chef_client_cron + +The `chef_client_cron` resource has been updated with a new `nice` property that allows you to set the nice level for the `chef-client` process. Nice level changes only apply to the `chef-client` process and not any subprocesses like `ohai` or system utility calls. If you need to ensure that the `chef-client` process does not negatively impact system performance, we highly recommend instead using the `cpu_quota` property in the `chef_client_systemd_timer` resource which applies to all child processes. + +### chef_client_systemd_timer + +The `chef_client_systemd_timer` resource has been updated with a new `cpu_quota` property that allows you to control the systemd `CPUQuota` value for the `chef-client` process. This allows you to ensure `chef-client` execution doesn't adversely impact performance on your systems. + +### launchd + +The `launchd` resource has been updated to better validate inputs to the `nice` property so we can make sure these are acceptable nice values. + +### mount + +The `mount` resource on Linux has new improved idempotency in some scenarios by switching to `findmnt` to determine the current state of the system. Thanks for reporting this issue [@pollosp](https://github.com/pollosp)! + +### osx_profile + +The `osx_profile` resource will now allow you to remove profiles from macOS 11 (Big Sur) systems. Due to security changes in macOS 11, it is no longer possible to locally install profiles, but this will allow you to cleanup existing profiles left over after an upgrade from an earlier macOS release. The resource has been updated to resolve a regression introduced in Chef Infra Client 16.4 that caused the resource to attempt to update profiles on each converge. Thanks for reporting these issues [@chilcote](https://github.com/chilcote)! + +### rhsm_register + +The `rhsm_register` resource has been updated to reduce the load on the RedHat Satellite server when checking if a system is already registered. Thanks for reporting this issue [@donwlewis](https://github.com/donwlewis)! A new `system_name` property has also been added to allow you to register a name other than the system's hostname. Thanks for this improvement [@jasonwbarnett](https://github.com/jasonwbarnett/)! + +### windows_ad_join + +The `windows_ad_join` resource has been updated with a new `reboot_delay` property which allows you to control the delay time before restarting systems. + +### windows_firewall_profile + +The `windows_firewall_profile` resource was updated to prevent NilClass errors from loading the firewall state. + +### windows_user_privilege + +The `windows_user_privilege` resource has been updated to better validate the `privilege` property and to allow the `users` property to accept String values. Thanks for reporting this issue [@jeremyciak](https://github.com/jeremyciak)! + +### Windows securable resources + +All Windows securable resources now support using SID in addition to user or group name when specifying `owner`, `group`, or `rights` principal. These resources include the `template`, `file`, `remote_file`, `cookbook_file`, `directory`, and `remote_directory` resources. When using a SID, you may use either the standard string representation of a SID (S-R-I-S-S) or one of the [SDDL string constants](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-strings). + +## Ohai Improvements + +- Ohai now uses the same underlying code for shelling out to external commands as Chef Infra Client. This may resolve issues from determining the state on some non-English systems. +- The `Packages` plugin has been updated to gather package installation information on macOS hosts. + +## Platform Packages + +- We are once again building Chef Infra Client packages for RHEL 7 / SLES 12 on the S390x architecture. In addition to these packages, we've also added S390x packages for RHEL 8 / SLES 15. +- We now produce packages for Apple's upcoming macOS 11 Big Sur release. + +## Security + +OpenSSL has been updated to 1.0.2w which includes a fix for [CVE-2020-1968](https://cve.mitre.org/cgi-bin/cvename.cgi?name=2020-1968). # What's New in 16.4 @@ -468,7 +582,7 @@ depends 'windows', '>> 1.0' ### Logging Improvements May Cause Behavior Changes -We've made low level changes to how logging behaves in Chef Infra Client that resolves many complaints we've heard of the years. With these change you'll now see the same logging output when you run `chef-client` on the command line as you will in logs from a daemonized client run. This also corrects often confusing behavior where running `chef-client` on the command line would log to the console, but not to the log file location defined your `client.rb`. In that scenario you'll now see logs in your console and in your log file. We believe this is the expected behavior and will mean that your on-disk log files can always be the source of truth for changes that were made by Chef Infra Client. This may cause unexpected behavior changes for users that relied on using the command line flags to override the `client.rb` log location - in this case logging will be sent to *both* the locations in `client.rb` and on the command line. If you have daemons running that log using the command line options you want to make sure that `client.rb` log location either matches or isn't defined. +We've made low-level changes to how logging behaves in Chef Infra Client that resolves many complaints we've heard of the years. With these change you'll now see the same logging output when you run `chef-client` on the command line as you will in logs from a daemonized client run. This also corrects often confusing behavior where running `chef-client` on the command line would log to the console, but not to the log file location defined your `client.rb`. In that scenario you'll now see logs in your console and in your log file. We believe this is the expected behavior and will mean that your on-disk log files can always be the source of truth for changes that were made by Chef Infra Client. This may cause unexpected behavior changes for users that relied on using the command line flags to override the `client.rb` log location - in this case logging will be sent to *both* the locations in `client.rb` and on the command line. If you have daemons running that log using the command line options you want to make sure that `client.rb` log location either matches or isn't defined. ### Red Hat / CentOS 6 Systems Require C11 GCC for Some Gem Installations @@ -2916,11 +3030,11 @@ Use the `powershell_package_source` resource to register a PowerShell package re #### Properties - `source_name` - The name of the package source. -- `url` - The url to the package source. +- `url` - The URL to the package source. - `trusted` - Whether or not to trust packages from this source. - `provider_name` - The package management provider for the source. It supports the following providers: 'Programs', 'msi', 'NuGet', 'msu', 'PowerShellGet', 'psl' and 'chocolatey'. -- `publish_location` - The url where modules will be published to for this source. Only valid if the provider is 'PowerShellGet'. -- `script_source_location` - The url where scripts are located for this source. Only valid if the provider is 'PowerShellGet'. +- `publish_location` - The URL where modules will be published to for this source. Only valid if the provider is 'PowerShellGet'. +- `script_source_location` - The URL where scripts are located for this source. Only valid if the provider is 'PowerShellGet'. - `script_publish_location` - The location where scripts will be published to for this source. Only valid if the provider is 'PowerShellGet'. ### kernel_module @@ -4203,7 +4317,7 @@ Sample data now available under azure: ### Package Plugin Supports Arch Linux -The Package plugin has been updated to include package information on Arch Linux systems. +The Packages plugin has been updated to include package information on Arch Linux systems. # What's New in 13.3: @@ -26,7 +26,7 @@ begin require_relative "tasks/announce" require_relative "tasks/docs" require_relative "tasks/spellcheck" - require_relative "lib/chef/dist" + require_relative "chef-utils/lib/chef-utils/dist" unless defined?(ChefUtils::Dist) rescue LoadError => e puts "Skipping missing rake dep: #{e}" end @@ -1 +1 @@ -16.5.51
\ No newline at end of file +16.5.77
\ No newline at end of file diff --git a/azure-pipelines.yml b/azure-pipelines.yml index d5e77904f7..68ab19bc6d 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -16,8 +16,6 @@ jobs: - job: strategy: matrix: - ubuntu_kitchen_tests: - imageName: 'ubuntu-latest' mac_kitchen_tests: imageName: 'macos-latest' diff --git a/chef-bin/Rakefile b/chef-bin/Rakefile index 5e5c9bbf5f..7fe4f1e9d4 100644 --- a/chef-bin/Rakefile +++ b/chef-bin/Rakefile @@ -10,7 +10,7 @@ Bundler::GemHelper.install_tasks desc "force install the chef-bin gem" task "install:force" do sh "gem build -V chef-bin.gemspec" - built_gem_path = Dir["chef-bin-*.gem"].sort_by { |f| File.mtime(f) }.last + built_gem_path = Dir["chef-bin-*.gem"].max_by { |f| File.mtime(f) } FileUtils.mkdir_p("pkg") unless Dir.exist?("pkg") FileUtils.mv(built_gem_path, "pkg") sh "gem install -f pkg/#{built_gem_path}" diff --git a/chef-bin/bin/chef-service-manager b/chef-bin/bin/chef-service-manager index 2575e23dc0..dcaae80141 100755 --- a/chef-bin/bin/chef-service-manager +++ b/chef-bin/bin/chef-service-manager @@ -21,13 +21,13 @@ $:.unshift(File.join(__dir__, "..", "lib")) require "chef" require "chef/application/windows_service_manager" -require "chef/dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) if Chef::Platform.windows? chef_client_service = { - service_name: Chef::Dist::CLIENT, - service_display_name: "#{Chef::Dist::PRODUCT} Service", - service_description: "Runs #{Chef::Dist::PRODUCT} on regular, configurable intervals.", + service_name: ChefUtils::Dist::Infra::CLIENT, + service_display_name: "#{ChefUtils::Dist::Infra::PRODUCT} Service", + service_description: "Runs #{ChefUtils::Dist::Infra::PRODUCT} on regular, configurable intervals.", service_file_path: File.expand_path("../chef-windows-service", $PROGRAM_NAME), delayed_start: true, dependencies: ["Winmgmt"], diff --git a/chef-bin/lib/chef-bin/version.rb b/chef-bin/lib/chef-bin/version.rb index 97b5811786..38dc350613 100644 --- a/chef-bin/lib/chef-bin/version.rb +++ b/chef-bin/lib/chef-bin/version.rb @@ -21,7 +21,7 @@ module ChefBin CHEFBIN_ROOT = File.expand_path("..", __dir__) - VERSION = "16.5.51".freeze + VERSION = "16.5.77".freeze end # diff --git a/chef-config/lib/chef-config/config.rb b/chef-config/lib/chef-config/config.rb index 2c4323db82..2f261b45a7 100644 --- a/chef-config/lib/chef-config/config.rb +++ b/chef-config/lib/chef-config/config.rb @@ -33,10 +33,12 @@ module Mixlib autoload :ShellOut, "mixlib/shellout" end autoload :URI, "uri" -autoload :Addressable, "addressable/uri" +module Addressable + autoload :URI, "addressable/uri" +end autoload :OpenSSL, "openssl" autoload :YAML, "yaml" -require_relative "dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) module ChefConfig @@ -82,7 +84,7 @@ module ChefConfig # @return [String] the platform-specific path # def self.etc_chef_dir(windows: ChefUtils.windows?) - path = windows ? c_chef_dir : PathHelper.join("/etc", ChefConfig::Dist::DIR_SUFFIX, windows: windows) + path = windows ? c_chef_dir : PathHelper.join("/etc", ChefUtils::Dist::Infra::DIR_SUFFIX, windows: windows) PathHelper.cleanpath(path, windows: windows) end @@ -92,7 +94,7 @@ module ChefConfig # @return [String] the platform-specific path # def self.var_chef_dir(windows: ChefUtils.windows?) - path = windows ? c_chef_dir : PathHelper.join("/var", ChefConfig::Dist::DIR_SUFFIX, windows: windows) + path = windows ? c_chef_dir : PathHelper.join("/var", ChefUtils::Dist::Infra::DIR_SUFFIX, windows: windows) PathHelper.cleanpath(path, windows: windows) end @@ -114,7 +116,7 @@ module ChefConfig # def self.c_chef_dir(windows: ChefUtils.windows?) drive = windows_installation_drive || "C:" - PathHelper.join(drive, ChefConfig::Dist::DIR_SUFFIX, windows: windows) + PathHelper.join(drive, ChefUtils::Dist::Infra::DIR_SUFFIX, windows: windows) end # On windows, C:/opscode @@ -125,7 +127,7 @@ module ChefConfig # def self.c_opscode_dir(windows: ChefUtils.windows?) drive = windows_installation_drive || "C:" - PathHelper.join(drive, ChefConfig::Dist::LEGACY_CONF_DIR, ChefConfig::Dist::DIR_SUFFIX, windows: windows) + PathHelper.join(drive, ChefUtils::Dist::Org::LEGACY_CONF_DIR, ChefUtils::Dist::Infra::DIR_SUFFIX, windows: windows) end # the drive where Chef is installed on a windows host. This is determined @@ -190,7 +192,7 @@ module ChefConfig if config_file PathHelper.dirname(PathHelper.canonical_path(config_file, false)) else - PathHelper.join(PathHelper.cleanpath(user_home), ChefConfig::Dist::USER_CONF_DIR, "") + PathHelper.join(PathHelper.cleanpath(user_home), ChefUtils::Dist::Infra::USER_CONF_DIR, "") end end @@ -269,7 +271,7 @@ module ChefConfig end path = new_path end - ChefConfig.logger.info("Auto-discovered #{ChefConfig::Dist::SHORT} repository at #{path}") + ChefConfig.logger.info("Auto-discovered #{ChefUtils::Dist::Infra::SHORT} repository at #{path}") path end @@ -367,7 +369,7 @@ module ChefConfig # Otherwise, we'll create .chef under the user's home directory and use that as # the cache path. unless path_accessible?(primary_cache_path) || path_accessible?(primary_cache_root) - secondary_cache_path = PathHelper.join(user_home, ChefConfig::Dist::USER_CONF_DIR) + secondary_cache_path = PathHelper.join(user_home, ChefUtils::Dist::Infra::USER_CONF_DIR) secondary_cache_path = target_mode? ? PathHelper.join(secondary_cache_path, target_mode.host) : secondary_cache_path ChefConfig.logger.trace("Unable to access cache at #{primary_cache_path}. Switching cache to #{secondary_cache_path}") secondary_cache_path @@ -398,7 +400,7 @@ module ChefConfig # If your `file_cache_path` resides on a NFS (or non-flock()-supporting # fs), it's recommended to set this to something like # '/tmp/chef-client-running.pid' - default(:lockfile) { PathHelper.join(file_cache_path, "#{ChefConfig::Dist::CLIENT}-running.pid") } + default(:lockfile) { PathHelper.join(file_cache_path, "#{ChefUtils::Dist::Infra::CLIENT}-running.pid") } ## Daemonization Settings ## # What user should Chef run as? @@ -647,7 +649,7 @@ module ChefConfig # credentials toml files which doesn't allow ruby symbol values configurable(:ssl_verify_mode).writes_value do |value| if value.is_a?(String) && value[0] == ":" - value[1..-1].to_sym + value[1..].to_sym else value.to_sym end @@ -795,7 +797,7 @@ module ChefConfig if chef_server_url.to_s =~ %r{/organizations/(.*)$} "#{$1}-validator" else - "#{ChefConfig::Dist::SHORT}-validator" + "#{ChefUtils::Dist::Infra::SHORT}-validator" end end @@ -869,7 +871,7 @@ module ChefConfig default :profile, nil default :chef_guid_path do - PathHelper.join(config_dir, "#{ChefConfig::Dist::SHORT}_guid") + PathHelper.join(config_dir, "#{ChefUtils::Dist::Infra::SHORT}_guid") end default :chef_guid, nil @@ -1078,7 +1080,7 @@ module ChefConfig # generated by the DataCollector when Chef is run in Solo mode. This # allows users to associate their Solo nodes with faux organizations # without the nodes being connected to an actual Chef Server. - default :organization, "#{ChefConfig::Dist::SHORT}_solo" + default :organization, "#{ChefUtils::Dist::Infra::SHORT}_solo" end configurable(:http_proxy) @@ -1205,7 +1207,7 @@ module ChefConfig # Transform into the form en_ZZ.UTF-8 guessed_locale.gsub(/UTF-?8$/i, "UTF-8") else - ChefConfig.logger.warn "Please install an English UTF-8 locale for Chef to use, falling back to C locale and disabling UTF-8 support." + ChefConfig.logger.warn "Please install an English UTF-8 locale for #{ChefUtils::Dist::Infra::PRODUCT} to use, falling back to C locale and disabling UTF-8 support." "C" end end @@ -1258,9 +1260,9 @@ module ChefConfig # @api private def self.enable_fips_mode OpenSSL.fips_mode = true - require "digest" - require "digest/sha1" - require "digest/md5" + require "digest" unless defined?(Digest) + require "digest/sha1" unless defined?(Digest::SHA1) + require "digest/md5" unless defined?(Digest::MD5) # Remove pre-existing constants if they do exist to reduce the # amount of log spam and warnings. Digest.send(:remove_const, "SHA1") if Digest.const_defined?("SHA1") diff --git a/chef-config/lib/chef-config/dist.rb b/chef-config/lib/chef-config/dist.rb deleted file mode 100644 index 67d1063163..0000000000 --- a/chef-config/lib/chef-config/dist.rb +++ /dev/null @@ -1,33 +0,0 @@ -module ChefConfig - class Dist - # The chef executable name. - EXEC = "chef".freeze - - # The client's alias (chef-client) - CLIENT = "chef-client".freeze - - # A short name for the product - SHORT = "chef".freeze - - # The suffix for Chef's /etc/chef, /var/chef and C:\\Chef directories - # "cinc" => /etc/cinc, /var/cinc, C:\\cinc - DIR_SUFFIX = "chef".freeze - - # The user's configuration directory - USER_CONF_DIR = ".chef".freeze - - # The legacy conf folder: C:/opscode/chef. Specifically the "opscode" part - # DIR_SUFFIX is appended to it in code where relevant - LEGACY_CONF_DIR = "opscode".freeze - - # Enable forcing Chef EULA - ENFORCE_LICENSE = true - - # The servers's alias (chef-server) - SERVER = "chef-server".freeze - - # The server's configuration utility - SERVER_CTL = "chef-server-ctl".freeze - - end -end diff --git a/chef-config/lib/chef-config/mixin/credentials.rb b/chef-config/lib/chef-config/mixin/credentials.rb index de004a062f..a17d94b443 100644 --- a/chef-config/lib/chef-config/mixin/credentials.rb +++ b/chef-config/lib/chef-config/mixin/credentials.rb @@ -17,6 +17,7 @@ autoload :Tomlrb, "tomlrb" require_relative "../path_helper" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) module ChefConfig module Mixin @@ -36,7 +37,7 @@ module ChefConfig # normally set via a command-line option. # @return [String] def credentials_profile(profile = nil) - context_file = PathHelper.home(ChefConfig::Dist::USER_CONF_DIR, "context").freeze + context_file = PathHelper.home(ChefUtils::Dist::Infra::USER_CONF_DIR, "context").freeze if !profile.nil? profile elsif ENV.include?("CHEF_PROFILE") @@ -53,7 +54,7 @@ module ChefConfig # @since 14.4 # @return [String] def credentials_file_path - PathHelper.home(ChefConfig::Dist::USER_CONF_DIR, "credentials").freeze + PathHelper.home(ChefUtils::Dist::Infra::USER_CONF_DIR, "credentials").freeze end # Load and parse the credentials file. @@ -84,17 +85,17 @@ module ChefConfig # @return [void] def load_credentials(profile = nil) profile = credentials_profile(profile) - config = parse_credentials_file - return if config.nil? # No credentials, nothing to do here. + cred_config = parse_credentials_file + return if cred_config.nil? # No credentials, nothing to do here. - if config[profile].nil? + if cred_config[profile].nil? # Unknown profile name. For "default" just silently ignore, otherwise # raise an error. return if profile == "default" raise ChefConfig::ConfigurationError, "Profile #{profile} doesn't exist. Please add it to #{credentials_file_path}." end - apply_credentials(config[profile], profile) + apply_credentials(cred_config[profile], profile) end end end diff --git a/chef-config/lib/chef-config/mixin/train_transport.rb b/chef-config/lib/chef-config/mixin/train_transport.rb new file mode 100644 index 0000000000..942f0ab3b7 --- /dev/null +++ b/chef-config/lib/chef-config/mixin/train_transport.rb @@ -0,0 +1,141 @@ +# Author:: Bryan McLellan <btm@loftninjas.org> +# Copyright:: Copyright (c) Chef Software Inc. +# License:: Apache License, Version 2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +require_relative "credentials" +autoload :Train, "train" +require_relative "../config" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) + +module ChefConfig + module Mixin + module TrainTransport + include ChefConfig::Mixin::Credentials + + attr_accessor :logger + + def initialize(logger) + @logger = logger + end + + # + # Returns a RFC099 credentials profile as a hash + # + def load_credentials(profile) + # Tomlrb.load_file returns a hash with keys as strings + credentials = parse_credentials_file + if contains_split_fqdn?(credentials, profile) + logger.warn("Credentials file #{credentials_file_path} contains target '#{profile}' as a Hash, expected a string.") + logger.warn("Hostnames must be surrounded by single quotes, e.g. ['host.example.org']") + end + + # host names must be specified in credentials file as ['foo.example.org'] with quotes + if !credentials.nil? && !credentials[profile].nil? + credentials[profile].transform_keys(&:to_sym) # return symbolized keys to match Train.options() + else + nil + end + end + + # Toml creates hashes when a key is separated by periods, e.g. + # [host.example.org] => { host: { example: { org: {} } } } + # + # Returns true if the above example is true + # + # A hostname has to be specified as ['host.example.org'] + # This will be a common mistake so we should catch it + # + def contains_split_fqdn?(hash, fqdn) + fqdn.split(".").reduce(hash) do |h, k| + v = h[k] + if Hash === v + v + else + break false + end + end + end + + # ChefConfig::Mixin::Credentials.credentials_file_path is designed around knife, + # overriding it here. + # + # Credentials file preference: + # + # 1) target_mode.credentials_file + # 2) /etc/chef/TARGET_MODE_HOST/credentials + # 3) #credentials_file_path from parent ($HOME/.chef/credentials) + # + def credentials_file_path + tm_config = config.target_mode + profile = tm_config.host + + credentials_file = + if tm_config.credentials_file && File.exist?(tm_config.credentials_file) + tm_config.credentials_file + elsif File.exist?(config.platform_specific_path("#{ChefConfig::Config.etc_chef_dir}/#{profile}/credentials")) + config.platform_specific_path("#{ChefConfig::Config.etc_chef_dir}/#{profile}/credentials") + else + super + end + + raise ArgumentError, "No credentials file found for target '#{profile}'" unless credentials_file + raise ArgumentError, "Credentials file specified for target mode does not exist: '#{credentials_file}'" unless File.exist?(credentials_file) + + logger.debug("Loading credentials file '#{credentials_file}' for target '#{profile}'") + + credentials_file + end + + def build_transport + return nil unless config.target_mode? + + # TODO: Consider supporting parsing the protocol from a URI passed to `--target` + # + train_config = {} + + # Load the target_mode config context from config, and place any valid settings into the train configuration + tm_config = config.target_mode + protocol = tm_config.protocol + train_config = tm_config.to_hash.select { |k| Train.options(protocol).key?(k) } + logger.trace("Using target mode options from #{ChefUtils::Dist::Infra::PRODUCT} config file: #{train_config.keys.join(", ")}") if train_config + + # Load the credentials file, and place any valid settings into the train configuration + credentials = load_credentials(tm_config.host) + if credentials + valid_settings = credentials.select { |k| Train.options(protocol).key?(k) } + valid_settings[:enable_password] = credentials[:enable_password] if credentials.key?(:enable_password) + train_config.merge!(valid_settings) + logger.trace("Using target mode options from credentials file: #{valid_settings.keys.join(", ")}") if valid_settings + end + + train_config[:logger] = logger + + # Train handles connection retries for us + Train.create(protocol, train_config) + rescue SocketError => e # likely a dns failure, not caught by train + e.message.replace "Error connecting to #{train_config[:target]} - #{e.message}" + raise e + rescue Train::PluginLoadError + logger.error("Invalid target mode protocol: #{protocol}") + exit(1) + end + + def config + raise NotImplementedError + end + end + end +end diff --git a/chef-config/lib/chef-config/version.rb b/chef-config/lib/chef-config/version.rb index 3cb7f03b20..8a3572645a 100644 --- a/chef-config/lib/chef-config/version.rb +++ b/chef-config/lib/chef-config/version.rb @@ -15,5 +15,5 @@ module ChefConfig CHEFCONFIG_ROOT = File.expand_path("..", __dir__) - VERSION = "16.5.51".freeze + VERSION = "16.5.77".freeze end diff --git a/chef-config/lib/chef-config/workstation_config_loader.rb b/chef-config/lib/chef-config/workstation_config_loader.rb index 4e44a24fd7..bbec74911b 100644 --- a/chef-config/lib/chef-config/workstation_config_loader.rb +++ b/chef-config/lib/chef-config/workstation_config_loader.rb @@ -59,7 +59,7 @@ module ChefConfig @chef_config_dir = false full_path = working_directory.split(File::SEPARATOR) (full_path.length - 1).downto(0) do |i| - candidate_directory = File.join(full_path[0..i] + [ChefConfig::Dist::USER_CONF_DIR]) + candidate_directory = File.join(full_path[0..i] + [ChefUtils::Dist::Infra::USER_CONF_DIR]) if File.exist?(candidate_directory) && File.directory?(candidate_directory) @chef_config_dir = candidate_directory break @@ -129,7 +129,7 @@ module ChefConfig candidate_configs << File.join(chef_config_dir, "knife.rb") end # Look for $HOME/.chef/knife.rb - PathHelper.home(ChefConfig::Dist::USER_CONF_DIR) do |dot_chef_dir| + PathHelper.home(ChefUtils::Dist::Infra::USER_CONF_DIR) do |dot_chef_dir| candidate_configs << File.join(dot_chef_dir, "config.rb") candidate_configs << File.join(dot_chef_dir, "knife.rb") end @@ -166,7 +166,7 @@ module ChefConfig when "client_key" extract_key(value, :client_key, :client_key_contents) when "knife" - Config.knife.merge!(Hash[value.map { |k, v| [k.to_sym, v] }]) + Config.knife.merge!(value.transform_keys(&:to_sym)) else Config[key.to_sym] = value end @@ -184,7 +184,7 @@ module ChefConfig end def home_chef_dir - @home_chef_dir ||= PathHelper.home(ChefConfig::Dist::USER_CONF_DIR) + @home_chef_dir ||= PathHelper.home(ChefUtils::Dist::Infra::USER_CONF_DIR) end def apply_config(config_content, config_file_path) diff --git a/chef-config/spec/unit/config_spec.rb b/chef-config/spec/unit/config_spec.rb index 1cb83bb8d0..3d7365927d 100644 --- a/chef-config/spec/unit/config_spec.rb +++ b/chef-config/spec/unit/config_spec.rb @@ -225,7 +225,7 @@ RSpec.describe ChefConfig::Config do end describe "#var_chef_path" do - let (:dirname) { ChefConfig::Dist::DIR_SUFFIX } + let (:dirname) { ChefUtils::Dist::Infra::DIR_SUFFIX } context "on unix", :unix_only do it "var_chef_dir is /var/chef" do @@ -931,7 +931,7 @@ RSpec.describe ChefConfig::Config do shared_examples_for "a suitable locale" do it "returns an English UTF-8 locale" do - expect(ChefConfig.logger).to_not receive(:warn).with(/Please install an English UTF-8 locale for Chef to use/) + expect(ChefConfig.logger).to_not receive(:warn).with(/Please install an English UTF-8 locale for Chef Infra Client to use/) expect(ChefConfig.logger).to_not receive(:trace).with(/Defaulting to locale en_US.UTF-8 on Windows/) expect(ChefConfig.logger).to_not receive(:trace).with(/No usable locale -a command found/) expect(ChefConfig::Config.guess_internal_locale).to eq expected_locale @@ -984,7 +984,7 @@ RSpec.describe ChefConfig::Config do let(:locale_array) { ["af_ZA", "af_ZA.ISO8859-1", "af_ZA.ISO8859-15", "af_ZA.UTF-8"] } it "should fall back to C locale" do - expect(ChefConfig.logger).to receive(:warn).with("Please install an English UTF-8 locale for Chef to use, falling back to C locale and disabling UTF-8 support.") + expect(ChefConfig.logger).to receive(:warn).with("Please install an English UTF-8 locale for Chef Infra Client to use, falling back to C locale and disabling UTF-8 support.") expect(ChefConfig::Config.guess_internal_locale).to eq "C" end end diff --git a/chef-config/spec/unit/fips_spec.rb b/chef-config/spec/unit/fips_spec.rb index 5ee62b6c79..4be6f64a2d 100644 --- a/chef-config/spec/unit/fips_spec.rb +++ b/chef-config/spec/unit/fips_spec.rb @@ -20,7 +20,7 @@ require "chef-config/fips" require "spec_helper" begin - require "win32/registry" + require "win32/registry" unless defined?(Win32::Registry) rescue LoadError # not on unix end diff --git a/chef-config/spec/unit/workstation_config_loader_spec.rb b/chef-config/spec/unit/workstation_config_loader_spec.rb index c589b298ae..70b42ad961 100644 --- a/chef-config/spec/unit/workstation_config_loader_spec.rb +++ b/chef-config/spec/unit/workstation_config_loader_spec.rb @@ -17,7 +17,7 @@ # require "spec_helper" -require "tempfile" +require "tempfile" unless defined?(Tempfile) require "chef-config/exceptions" require "chef-utils" diff --git a/chef-utils/lib/chef-utils/dist.rb b/chef-utils/lib/chef-utils/dist.rb new file mode 100644 index 0000000000..2b554e541f --- /dev/null +++ b/chef-utils/lib/chef-utils/dist.rb @@ -0,0 +1,97 @@ +module ChefUtils + # This class is not fully implemented, depending on it is not recommended! + module Dist + class Apply + # The chef-apply product name + PRODUCT = "Chef Infra Apply".freeze + + # The chef-apply binary + EXEC = "chef-apply".freeze + end + + class Automate + # name of the automate product + PRODUCT = "Chef Automate".freeze + end + + class Infra + # When referencing a product directly, like Chef (Now Chef Infra) + PRODUCT = "Chef Infra Client".freeze + + # A short designation for the product, used in Windows event logs + # and some nomenclature. + SHORT = "chef".freeze + + # The client's alias (chef-client) + CLIENT = "chef-client".freeze + + # The chef executable, as in `chef gem install` or `chef generate cookbook` + EXEC = "chef".freeze + + # The chef-shell executable + SHELL = "chef-shell".freeze + + # Configuration related constants + # The chef-shell configuration file + SHELL_CONF = "chef_shell.rb".freeze + + # The user's configuration directory + USER_CONF_DIR = ".chef".freeze + + # The suffix for Chef's /etc/chef, /var/chef and C:\\Chef directories + # "chef" => /etc/cinc, /var/cinc, C:\\cinc + DIR_SUFFIX = "chef".freeze + end + + class Org + # product Website address + WEBSITE = "https://chef.io".freeze + + # The downloads site + DOWNLOADS_URL = "downloads.chef.io".freeze + + # The legacy conf folder: C:/opscode/chef. Specifically the "opscode" part + # DIR_SUFFIX is appended to it in code where relevant + LEGACY_CONF_DIR = "opscode".freeze + + # Enable forcing Chef EULA + ENFORCE_LICENSE = true + + # product patents page + PATENTS = "https://www.chef.io/patents".freeze + + # knife documentation page + KNIFE_DOCS = "https://docs.chef.io/workstation/knife/".freeze + end + + class Server + # The name of the server product + PRODUCT = "Chef Infra Server".freeze + + # The server's configuration directory + CONF_DIR = "/etc/chef-server".freeze + + # The servers's alias (chef-server) + SERVER = "chef-server".freeze + + # The server's configuration utility + SERVER_CTL = "chef-server-ctl".freeze + end + + class Solo + # Chef-Solo's product name + PRODUCT = "Chef Infra Solo".freeze + + # The chef-solo executable (legacy local mode) + EXEC = "chef-solo".freeze + end + + class Zero + # chef-zero executable + PRODUCT = "Chef Infra Zero".freeze + + # The chef-zero executable (local mode) + EXEC = "chef-zero".freeze + end + end +end diff --git a/chef-utils/lib/chef-utils/dsl/train_helpers.rb b/chef-utils/lib/chef-utils/dsl/train_helpers.rb index a821383eac..b4be878723 100644 --- a/chef-utils/lib/chef-utils/dsl/train_helpers.rb +++ b/chef-utils/lib/chef-utils/dsl/train_helpers.rb @@ -25,8 +25,13 @@ module ChefUtils # # FIXME: generally these helpers all use the pattern of checking for target_mode? # and then if it is we use train. That approach should likely be flipped so that - # even when we're running without target mode we still use inspec in its local - # mode. + # even when we're running without target mode we still use train in its local + # mode. A prerequisite for that will be better CI testing of train against + # chef-client though, and ensuring that the APIs are entirely compatible. This + # will be particularly problematic for shell_out APIs and eventual file-creating + # APIs which are unlikely to be as sophisticated as the exiting code in chef-client + # for locally shelling out and creating files, and just dropping inspec local mode + # into chef-client would break the world. # # Train wrapper around File.exist? to make it local mode aware. @@ -57,6 +62,24 @@ module ChefUtils end end + # Alias to easily convert IO.read / File.read to file_read + def file_read(path) + file_open(path).read + end + + def file_directory?(path) + if __transport_connection + __transport_connection.file(filename).directory? + else + File.directory?(path) + end + end + + # Alias to easily convert Dir.exist to dir_exist + def dir_exist?(path) + file_directory?(path) + end + extend self end end diff --git a/chef-utils/lib/chef-utils/version.rb b/chef-utils/lib/chef-utils/version.rb index 9ccec198b3..5ed24d3a7f 100644 --- a/chef-utils/lib/chef-utils/version.rb +++ b/chef-utils/lib/chef-utils/version.rb @@ -15,5 +15,5 @@ module ChefUtils CHEFUTILS_ROOT = File.expand_path("..", __dir__) - VERSION = "16.5.51".freeze + VERSION = "16.5.77".freeze end diff --git a/chef.gemspec b/chef.gemspec index 77140a6b15..965981fee7 100644 --- a/chef.gemspec +++ b/chef.gemspec @@ -38,7 +38,7 @@ Gem::Specification.new do |s| s.add_dependency "highline", ">= 1.6.9", "< 3" s.add_dependency "tty-prompt", "~> 0.21" # knife ui.ask prompt s.add_dependency "tty-screen", "~> 0.6" # knife list - s.add_dependency "tty-table", "~> 0.11.0" # knife render table output + s.add_dependency "tty-table", "~> 0.11" # knife render table output. s.add_dependency "pastel" # knife ui.color s.add_dependency "erubis", "~> 2.7" s.add_dependency "diff-lcs", ">= 1.2.4", "< 1.4.0" # 1.4 breaks output diff --git a/distro/templates/powershell/chef/chef.psm1.erb b/distro/templates/powershell/chef/chef.psm1.erb index f8b24dc54b..35344d907d 100644 --- a/distro/templates/powershell/chef/chef.psm1.erb +++ b/distro/templates/powershell/chef/chef.psm1.erb @@ -412,40 +412,40 @@ function Run-RubyCommand($command, $argList) { } -function <%= Chef::Dist::APPLY %> { - Run-RubyCommand '<%= Chef::Dist::APPLY %>' $args +function <%= ChefUtils::Dist::Apply::EXEC %> { + Run-RubyCommand '<%= ChefUtils::Dist::Apply::EXEC %>' $args } -function <%= Chef::Dist::CLIENT %> { - Run-RubyCommand '<%= Chef::Dist::CLIENT %>' $args +function <%= ChefUtils::Dist::Infra::CLIENT %> { + Run-RubyCommand '<%= ChefUtils::Dist::Infra::CLIENT %>' $args } -function <%= Chef::Dist::EXEC %>-service-manager { - Run-RubyCommand '<%= Chef::Dist::EXEC %>-service-manager' $args +function <%= ChefUtils::Dist::Infra::EXEC %>-service-manager { + Run-RubyCommand '<%= ChefUtils::Dist::Infra::EXEC %>-service-manager' $args } -function <%= Chef::Dist::SHELL %> { - Run-RubyCommand '<%= Chef::Dist::SHELL %>' $args +function <%= ChefUtils::Dist::Infra::SHELL %> { + Run-RubyCommand '<%= ChefUtils::Dist::Infra::SHELL %>' $args } -function <%= Chef::Dist::SOLOEXEC %> { - Run-RubyCommand '<%= Chef::Dist::SOLOEXEC %>' $args +function <%= ChefUtils::Dist::Solo::EXEC %> { + Run-RubyCommand '<%= ChefUtils::Dist::Solo::EXEC %>' $args } -function <%= Chef::Dist::EXEC %>-windows-service { - Run-RubyCommand '<%= Chef::Dist::EXEC %>-windows-service' $args +function <%= ChefUtils::Dist::Infra::EXEC %>-windows-service { + Run-RubyCommand '<%= ChefUtils::Dist::Infra::EXEC %>-windows-service' $args } function knife { Run-RubyCommand 'knife' $args } -Export-ModuleMember -function <%= Chef::Dist::APPLY %> -Export-ModuleMember -function <%= Chef::Dist::CLIENT %> -Export-ModuleMember -function <%= Chef::Dist::EXEC %>-service-manager -Export-ModuleMember -function <%= Chef::Dist::SHELL %> -Export-ModuleMember -function <%= Chef::Dist::SOLOEXEC %> -Export-ModuleMember -function <%= Chef::Dist::EXEC %>-windows-service +Export-ModuleMember -function <%= ChefUtils::Dist::Apply::EXEC %> +Export-ModuleMember -function <%= ChefUtils::Dist::Infra::CLIENT %> +Export-ModuleMember -function <%= ChefUtils::Dist::Infra::EXEC %>-service-manager +Export-ModuleMember -function <%= ChefUtils::Dist::Infra::SHELL %> +Export-ModuleMember -function <%= ChefUtils::Dist::Solo::EXEC %> +Export-ModuleMember -function <%= ChefUtils::Dist::Infra::EXEC %>-windows-service Export-ModuleMember -function knife # To debug this module, uncomment the line below diff --git a/ext/win32-eventlog/Rakefile b/ext/win32-eventlog/Rakefile index 2cf1a40896..6addd36091 100644 --- a/ext/win32-eventlog/Rakefile +++ b/ext/win32-eventlog/Rakefile @@ -2,7 +2,7 @@ require "rubygems" require "rake" require "mkmf" require "erb" -require_relative "../../lib/chef/dist" +require "chef-utils/dist" desc "Building event log dll" @@ -51,7 +51,7 @@ task register: EVT_SHARED_OBJECT do begin Win32::EventLog.add_event_source( source: "Application", - key_name: Chef::Dist::SHORT, + key_name: ChefUtils::Dist::Infra::SHORT, event_message_file: dll_file, category_message_file: dll_file ) diff --git a/ext/win32-eventlog/chef-log.man.erb b/ext/win32-eventlog/chef-log.man.erb index 2e767a8cfe..83be49b4d2 100644 --- a/ext/win32-eventlog/chef-log.man.erb +++ b/ext/win32-eventlog/chef-log.man.erb @@ -1,25 +1,25 @@ MessageId=10000 SymbolicName=RUN_START Language=English -Starting <%= Chef::Dist::PRODUCT %> run v%1 +Starting <%= ChefUtils::Dist::Infra::PRODUCT %> run v%1 . MessageId=10001 SymbolicName=RUN_STARTED Language=English -Started <%= Chef::Dist::PRODUCT %> run %1 +Started <%= ChefUtils::Dist::Infra::PRODUCT %> run %1 . MessageId=10002 SymbolicName=RUN_COMPLETED Language=English -Completed <%= Chef::Dist::PRODUCT %> run %1 in %2 seconds +Completed <%= ChefUtils::Dist::Infra::PRODUCT %> run %1 in %2 seconds . MessageId=10003 SymbolicName=RUN_FAILED Language=English -Failed <%= Chef::Dist::PRODUCT %> run %1 in %2 seconds.%n +Failed <%= ChefUtils::Dist::Infra::PRODUCT %> run %1 in %2 seconds.%n Exception type: %3%n Exception message: %4%n Exception backtrace: %5%n diff --git a/lib/chef/application.rb b/lib/chef/application.rb index be69e01f7f..117f498831 100644 --- a/lib/chef/application.rb +++ b/lib/chef/application.rb @@ -27,7 +27,7 @@ require "mixlib/cli" unless defined?(Mixlib::CLI) require "tmpdir" unless defined?(Dir.mktmpdir) require "rbconfig" unless defined?(RbConfig) require_relative "application/exit_code" -require_relative "dist" +require "chef-utils" unless defined?(ChefUtils::CANARY) module LicenseAcceptance autoload :Acceptor, "license_acceptance/acceptor" end @@ -41,9 +41,6 @@ class Chef @chef_client = nil @chef_client_json = nil - - # Always switch to a readable directory. Keeps subsequent Dir.chdir() {} - # from failing due to permissions when launched as a less privileged user. end # Configure mixlib-cli to always separate defaults from user-supplied CLI options @@ -175,7 +172,7 @@ class Chef def configure_logging configure_log_location logger.init(MonoLogger.new(chef_config[:log_location][0])) - chef_config[:log_location][1..-1].each do |log_location| + chef_config[:log_location][1..].each do |log_location| logger.loggers << MonoLogger.new(log_location) end logger.level = resolve_log_level @@ -310,7 +307,7 @@ class Chef end def fork_chef_client - logger.info "Forking #{Chef::Dist::PRODUCT} instance to converge..." + logger.info "Forking #{ChefUtils::Dist::Infra::PRODUCT} instance to converge..." pid = fork do # Want to allow forked processes to finish converging when # TERM singal is received (exit gracefully) @@ -319,7 +316,7 @@ class Chef " finishing converge to exit normally (send SIGINT to terminate immediately)") end - client_solo = chef_config[:solo] ? Chef::Dist::SOLOEXEC : Chef::Dist::CLIENT + client_solo = chef_config[:solo] ? ChefUtils::Dist::Solo::EXEC : ChefUtils::Dist::Infra::CLIENT $0 = "#{client_solo} worker: ppid=#{Process.ppid};start=#{Time.new.strftime("%R:%S")};" begin logger.trace "Forked instance now converging" @@ -331,7 +328,7 @@ class Chef exit 0 end end - logger.trace "Fork successful. Waiting for new #{Chef::Dist::CLIENT} pid: #{pid}" + logger.trace "Fork successful. Waiting for new #{ChefUtils::Dist::Infra::CLIENT} pid: #{pid}" result = Process.waitpid2(pid) handle_child_exit(result) logger.trace "Forked instance successfully reaped (pid: #{pid})" @@ -343,9 +340,9 @@ class Chef return true if status.success? message = if status.signaled? - "#{Chef::Dist::PRODUCT} run process terminated by signal #{status.termsig} (#{Signal.list.invert[status.termsig]})" + "#{ChefUtils::Dist::Infra::PRODUCT} run process terminated by signal #{status.termsig} (#{Signal.list.invert[status.termsig]})" else - "#{Chef::Dist::PRODUCT} run process exited unsuccessfully (exit code #{status.exitstatus})" + "#{ChefUtils::Dist::Infra::PRODUCT} run process exited unsuccessfully (exit code #{status.exitstatus})" end raise Exceptions::ChildConvergeError, message end @@ -378,8 +375,8 @@ class Chef chef_stacktrace_out = "Generated at #{Time.now}\n" chef_stacktrace_out += message - Chef::FileCache.store("#{Chef::Dist::SHORT}-stacktrace.out", chef_stacktrace_out) - logger.fatal("Stacktrace dumped to #{Chef::FileCache.load("#{Chef::Dist::SHORT}-stacktrace.out", false)}") + Chef::FileCache.store("#{ChefUtils::Dist::Infra::SHORT}-stacktrace.out", chef_stacktrace_out) + logger.fatal("Stacktrace dumped to #{Chef::FileCache.load("#{ChefUtils::Dist::Infra::SHORT}-stacktrace.out", false)}") logger.fatal("Please provide the contents of the stacktrace.out file if you file a bug report") if Chef::Config[:always_dump_stacktrace] logger.fatal(message) diff --git a/lib/chef/application/apply.rb b/lib/chef/application/apply.rb index 83e28880f9..3559f8e416 100644 --- a/lib/chef/application/apply.rb +++ b/lib/chef/application/apply.rb @@ -27,13 +27,13 @@ require "fileutils" unless defined?(FileUtils) require "tempfile" unless defined?(Tempfile) require_relative "../providers" require_relative "../resources" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) require "license_acceptance/cli_flags/mixlib_cli" class Chef::Application::Apply < Chef::Application include LicenseAcceptance::CLIFlags::MixlibCLI - banner "Usage: #{Chef::Dist::APPLY} [RECIPE_FILE | -e RECIPE_TEXT | -s] [OPTIONS]" + banner "Usage: #{ChefUtils::Dist::Apply::EXEC} [RECIPE_FILE | -e RECIPE_TEXT | -s] [OPTIONS]" option :execute, short: "-e RECIPE_TEXT", @@ -100,9 +100,9 @@ class Chef::Application::Apply < Chef::Application option :version, short: "-v", long: "--version", - description: "Show #{Chef::Dist::PRODUCT} version.", + description: "Show #{ChefUtils::Dist::Infra::PRODUCT} version.", boolean: true, - proc: lambda { |v| puts "#{Chef::Dist::PRODUCT}: #{::Chef::VERSION}" }, + proc: lambda { |v| puts "#{ChefUtils::Dist::Infra::PRODUCT}: #{::Chef::VERSION}" }, exit: 0 option :why_run, @@ -119,7 +119,7 @@ class Chef::Application::Apply < Chef::Application option :profile_ruby, long: "--[no-]profile-ruby", - description: "Dump complete Ruby call graph stack of entire #{Chef::Dist::PRODUCT} run (expert only).", + description: "Dump complete Ruby call graph stack of entire #{ChefUtils::Dist::Infra::PRODUCT} run (expert only).", boolean: true, default: false @@ -131,7 +131,7 @@ class Chef::Application::Apply < Chef::Application option :minimal_ohai, long: "--minimal-ohai", - description: "Only run the bare minimum Ohai plugins #{Chef::Dist::PRODUCT} needs to function.", + description: "Only run the bare minimum Ohai plugins #{ChefUtils::Dist::Infra::PRODUCT} needs to function.", boolean: true attr_reader :json_attribs @@ -181,7 +181,7 @@ class Chef::Application::Apply < Chef::Application else Chef::RunContext.new(@chef_client.node, {}, @chef_client.events) end - recipe = Chef::Recipe.new("(#{Chef::Dist::APPLY} cookbook)", "(#{Chef::Dist::APPLY} recipe)", run_context) + recipe = Chef::Recipe.new("(#{ChefUtils::Dist::Apply::EXEC} cookbook)", "(#{ChefUtils::Dist::Apply::EXEC} recipe)", run_context) [recipe, run_context] end diff --git a/lib/chef/application/base.rb b/lib/chef/application/base.rb index 738788fa96..56e28baa79 100644 --- a/lib/chef/application/base.rb +++ b/lib/chef/application/base.rb @@ -20,7 +20,7 @@ require_relative "../log" require_relative "../config" require_relative "../mixin/shell_out" require_relative "../config_fetcher" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) require_relative "../daemon" require "chef-config/mixin/dot_d" require "license_acceptance/cli_flags/mixlib_cli" @@ -57,7 +57,7 @@ class Chef::Application::Base < Chef::Application option :once, long: "--once", - description: "Cancel any interval or splay options, run #{Chef::Dist::PRODUCT} once and exit.", + description: "Cancel any interval or splay options, run #{ChefUtils::Dist::Infra::PRODUCT} once and exit.", boolean: true option :formatter, @@ -80,7 +80,7 @@ class Chef::Application::Base < Chef::Application option :profile_ruby, long: "--[no-]profile-ruby", - description: "Dump complete Ruby call graph stack of entire #{Chef::Dist::PRODUCT} run (expert only).", + description: "Dump complete Ruby call graph stack of entire #{ChefUtils::Dist::Infra::PRODUCT} run (expert only).", boolean: true, default: false @@ -136,7 +136,7 @@ class Chef::Application::Base < Chef::Application option :interval, short: "-i SECONDS", long: "--interval SECONDS", - description: "Run #{Chef::Dist::PRODUCT} periodically, in seconds.", + description: "Run #{ChefUtils::Dist::Infra::PRODUCT} periodically, in seconds.", proc: lambda { |s| s.to_i } option :json_attribs, @@ -160,12 +160,12 @@ class Chef::Application::Base < Chef::Application option :environment, short: "-E ENVIRONMENT", long: "--environment ENVIRONMENT", - description: "Set the #{Chef::Dist::PRODUCT} environment on the node." + description: "Set the #{ChefUtils::Dist::Infra::PRODUCT} environment on the node." option :client_fork, short: "-f", long: "--[no-]fork", - description: "Fork #{Chef::Dist::PRODUCT} process." + description: "Fork #{ChefUtils::Dist::Infra::PRODUCT} process." option :why_run, short: "-W", @@ -192,14 +192,14 @@ class Chef::Application::Base < Chef::Application option :version, short: "-v", long: "--version", - description: "Show #{Chef::Dist::PRODUCT} version.", + description: "Show #{ChefUtils::Dist::Infra::PRODUCT} version.", boolean: true, - proc: lambda { |v| puts "#{Chef::Dist::PRODUCT}: #{::Chef::VERSION}" }, + proc: lambda { |v| puts "#{ChefUtils::Dist::Infra::PRODUCT}: #{::Chef::VERSION}" }, exit: 0 option :minimal_ohai, long: "--minimal-ohai", - description: "Only run the bare minimum Ohai plugins #{Chef::Dist::PRODUCT} needs to function.", + description: "Only run the bare minimum Ohai plugins #{ChefUtils::Dist::Infra::PRODUCT} needs to function.", boolean: true option :delete_entire_chef_repo, @@ -215,7 +215,7 @@ class Chef::Application::Base < Chef::Application option :target, short: "-t TARGET", long: "--target TARGET", - description: "Target #{Chef::Dist::PRODUCT} against a remote system or device", + description: "Target #{ChefUtils::Dist::Infra::PRODUCT} against a remote system or device", proc: lambda { |target| Chef::Log.warn "-- EXPERIMENTAL -- Target mode activated, resources and dsl may change without warning -- EXPERIMENTAL --" target @@ -230,7 +230,7 @@ class Chef::Application::Base < Chef::Application option :fatal_windows_admin_check, short: "-A", long: "--fatal-windows-admin-check", - description: "Fail the run when #{Chef::Dist::CLIENT} doesn't have administrator privileges on Windows.", + description: "Fail the run when #{ChefUtils::Dist::Infra::CLIENT} doesn't have administrator privileges on Windows.", boolean: true end @@ -247,7 +247,7 @@ class Chef::Application::Base < Chef::Application option :chef_server_url, short: "-S CHEFSERVERURL", long: "--server CHEFSERVERURL", - description: "The #{Chef::Dist::SERVER_PRODUCT} URL.", + description: "The #{ChefUtils::Dist::Server::PRODUCT} URL.", proc: nil option :validation_key, @@ -265,7 +265,7 @@ class Chef::Application::Base < Chef::Application option :enable_reporting, short: "-R", long: "--enable-reporting", - description: "(#{Chef::Dist::CLIENT} only) reporting data collection for runs.", + description: "(#{ChefUtils::Dist::Infra::CLIENT} only) reporting data collection for runs.", boolean: true option :local_mode, @@ -276,11 +276,11 @@ class Chef::Application::Base < Chef::Application option :chef_zero_host, long: "--chef-zero-host HOST", - description: "Host to start #{Chef::Dist::ZERO} on." + description: "Host to start #{ChefUtils::Dist::Zero::PRODUCT} on." option :chef_zero_port, long: "--chef-zero-port PORT", - description: "Port (or port range) to start #{Chef::Dist::ZERO} on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works." + description: "Port (or port range) to start #{ChefUtils::Dist::Zero::PRODUCT} on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works." option :listen, long: "--[no-]listen", @@ -289,7 +289,7 @@ class Chef::Application::Base < Chef::Application option :skip_cookbook_sync, long: "--[no-]skip-cookbook-sync", - description: "(#{Chef::Dist::CLIENT} only) Use cached cookbooks without overwriting local differences from the #{Chef::Dist::SERVER_PRODUCT}.", + description: "(#{ChefUtils::Dist::Infra::CLIENT} only) Use cached cookbooks without overwriting local differences from the #{ChefUtils::Dist::Server::PRODUCT}.", boolean: false option :named_run_list, @@ -328,7 +328,7 @@ class Chef::Application::Base < Chef::Application # Run the chef client, optionally daemonizing or looping at intervals. def run_application if Chef::Config[:version] - puts "#{Chef::Dist::PRODUCT} version: #{::Chef::VERSION}" + puts "#{ChefUtils::Dist::Infra::PRODUCT} version: #{::Chef::VERSION}" end if !Chef::Config[:client_fork] || Chef::Config[:once] @@ -348,17 +348,17 @@ class Chef::Application::Base < Chef::Application private def windows_interval_error_message - "Windows #{Chef::Dist::PRODUCT} interval runs are not supported in #{Chef::Dist::PRODUCT} 15 and later." + + "Windows #{ChefUtils::Dist::Infra::PRODUCT} interval runs are not supported in #{ChefUtils::Dist::Infra::PRODUCT} 15 and later." + "\nConfiguration settings:" + ("\n interval = #{Chef::Config[:interval]} seconds" if Chef::Config[:interval]).to_s + - "\nPlease manage #{Chef::Dist::PRODUCT} as a scheduled task instead." + "\nPlease manage #{ChefUtils::Dist::Infra::PRODUCT} as a scheduled task instead." end def unforked_interval_error_message - "Unforked #{Chef::Dist::PRODUCT} interval runs are disabled by default." + + "Unforked #{ChefUtils::Dist::Infra::PRODUCT} interval runs are disabled by default." + "\nConfiguration settings:" + ("\n interval = #{Chef::Config[:interval]} seconds" if Chef::Config[:interval]).to_s + - "\nEnable #{Chef::Dist::PRODUCT} interval runs by setting `:client_fork = true` in your config file or adding `--fork` to your command line options." + "\nEnable #{ChefUtils::Dist::Infra::PRODUCT} interval runs by setting `:client_fork = true` in your config file or adding `--fork` to your command line options." end def fetch_recipe_tarball(url, path) @@ -380,7 +380,7 @@ class Chef::Application::Base < Chef::Application def interval_run_chef_client if Chef::Config[:daemonize] - Chef::Daemon.daemonize(Chef::Dist::PRODUCT) + Chef::Daemon.daemonize(ChefUtils::Dist::Infra::PRODUCT) # Start first daemonized run after configured number of seconds if Chef::Config[:daemonize].is_a?(Integer) diff --git a/lib/chef/application/client.rb b/lib/chef/application/client.rb index 03ceff1727..4a749a7c39 100644 --- a/lib/chef/application/client.rb +++ b/lib/chef/application/client.rb @@ -21,6 +21,7 @@ require_relative "base" require_relative "../handler/error_report" require_relative "../workstation_config_loader" autoload :URI, "uri" +require "chef-utils" unless defined?(ChefUtils::CANARY) module Mixlib module Authentication autoload :Log, "mixlib/authentication" @@ -50,7 +51,7 @@ class Chef::Application::Client < Chef::Application::Base option :pid_file, short: "-P PID_FILE", long: "--pid PIDFILE", - description: "Set the PID file location, for the #{Chef::Dist::CLIENT} daemon process. Defaults to /tmp/chef-client.pid.", + description: "Set the PID file location, for the #{ChefUtils::Dist::Infra::CLIENT} daemon process. Defaults to /tmp/chef-client.pid.", proc: nil option :runlist, @@ -105,7 +106,7 @@ class Chef::Application::Client < Chef::Application::Base tarball_path = File.join(Chef::Config.chef_repo_path, "recipes.tgz") fetch_recipe_tarball(Chef::Config[:recipe_url], tarball_path) Mixlib::Archive.new(tarball_path).extract(Chef::Config.chef_repo_path, perms: false, ignore: /^\.$/) - config_path = File.join(Chef::Config.chef_repo_path, "#{Chef::Dist::USER_CONF_DIR}/config.rb") + config_path = File.join(Chef::Config.chef_repo_path, "#{ChefUtils::Dist::Infra::USER_CONF_DIR}/config.rb") Chef::Config.from_string(IO.read(config_path), config_path) if File.file?(config_path) end end @@ -152,7 +153,7 @@ class Chef::Application::Client < Chef::Application::Base if config[:local_mode] config[:config_file] = Chef::WorkstationConfigLoader.new(nil, Chef::Log).config_location else - config[:config_file] = Chef::Config.platform_specific_path("#{Chef::Dist::CONF_DIR}/client.rb") + config[:config_file] = Chef::Config.platform_specific_path("#{ChefConfig::Config.etc_chef_dir}/client.rb") end end diff --git a/lib/chef/application/exit_code.rb b/lib/chef/application/exit_code.rb index ee0621f5ce..26c181fa3d 100644 --- a/lib/chef/application/exit_code.rb +++ b/lib/chef/application/exit_code.rb @@ -22,7 +22,7 @@ class Chef # These are the exit codes defined in Chef RFC 062 # https://github.com/chef/chef-rfc/blob/master/rfc062-exit-status.md class ExitCode - require_relative "../dist" + require "chef-utils/dist" unless defined?(ChefUtils::Dist) # -1 is defined as DEPRECATED_FAILURE in RFC 062, so it is # not enumerated in an active constant. @@ -153,9 +153,9 @@ class Chef end def non_standard_exit_code_warning(exit_code) - "#{Chef::Dist::CLIENT} attempted to exit with a non-standard exit code of #{exit_code}." \ - " The #{Chef::Dist::PRODUCT} Exit Codes design document (https://github.com/chef/chef-rfc/blob/master/rfc062-exit-status.md)" \ - " defines the exit codes that should be used with #{Chef::Dist::CLIENT}. Chef::Application::ExitCode defines" \ + "#{ChefUtils::Dist::Infra::CLIENT} attempted to exit with a non-standard exit code of #{exit_code}." \ + " The #{ChefUtils::Dist::Infra::PRODUCT} Exit Codes design document (https://github.com/chef/chef-rfc/blob/master/rfc062-exit-status.md)" \ + " defines the exit codes that should be used with #{ChefUtils::Dist::Infra::CLIENT}. Chef::Application::ExitCode defines" \ " valid exit codes Non-standard exit codes are redefined as GENERIC_FAILURE." end diff --git a/lib/chef/application/knife.rb b/lib/chef/application/knife.rb index e8acb8ebcd..eb1c3279e1 100644 --- a/lib/chef/application/knife.rb +++ b/lib/chef/application/knife.rb @@ -22,7 +22,7 @@ require "ohai/config" module Net autoload :HTTP, File.expand_path("../monkey_patches/net_http", __dir__) end -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef::Application::Knife < Chef::Application @@ -61,7 +61,7 @@ class Chef::Application::Knife < Chef::Application option :environment, short: "-E ENVIRONMENT", long: "--environment ENVIRONMENT", - description: "Set the #{Chef::Dist::PRODUCT} environment (except for in searches, where this will be flagrantly ignored)." + description: "Set the #{ChefUtils::Dist::Infra::PRODUCT} environment (except for in searches, where this will be flagrantly ignored)." option :editor, short: "-e EDITOR", @@ -86,18 +86,18 @@ class Chef::Application::Knife < Chef::Application option :node_name, short: "-u USER", long: "--user USER", - description: "#{Chef::Dist::SERVER_PRODUCT} API client username." + description: "#{ChefUtils::Dist::Server::PRODUCT} API client username." option :client_key, short: "-k KEY", long: "--key KEY", - description: "#{Chef::Dist::SERVER_PRODUCT} API client key.", + description: "#{ChefUtils::Dist::Server::PRODUCT} API client key.", proc: lambda { |path| File.expand_path(path, Dir.pwd) } option :chef_server_url, short: "-s URL", long: "--server-url URL", - description: "#{Chef::Dist::SERVER_PRODUCT} URL." + description: "#{ChefUtils::Dist::Server::PRODUCT} URL." option :yes, short: "-y", @@ -122,16 +122,16 @@ class Chef::Application::Knife < Chef::Application option :local_mode, short: "-z", long: "--local-mode", - description: "Point knife commands at local repository instead of #{Chef::Dist::SERVER_PRODUCT}.", + description: "Point knife commands at local repository instead of #{ChefUtils::Dist::Server::PRODUCT}.", boolean: true option :chef_zero_host, long: "--chef-zero-host HOST", - description: "Host to start #{Chef::Dist::ZERO} on." + description: "Host to start #{ChefUtils::Dist::Zero::PRODUCT} on." option :chef_zero_port, long: "--chef-zero-port PORT", - description: "Port (or port range) to start #{Chef::Dist::ZERO} on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works." + description: "Port (or port range) to start #{ChefUtils::Dist::Zero::PRODUCT} on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works." option :listen, long: "--[no-]listen", @@ -141,9 +141,9 @@ class Chef::Application::Knife < Chef::Application option :version, short: "-v", long: "--version", - description: "Show #{Chef::Dist::PRODUCT} version.", + description: "Show #{ChefUtils::Dist::Infra::PRODUCT} version.", boolean: true, - proc: lambda { |v| puts "#{Chef::Dist::PRODUCT}: #{::Chef::VERSION}" }, + proc: lambda { |v| puts "#{ChefUtils::Dist::Infra::PRODUCT}: #{::Chef::VERSION}" }, exit: 0 option :fips, @@ -218,10 +218,10 @@ class Chef::Application::Knife < Chef::Application end if want_help? - puts "#{Chef::Dist::PRODUCT}: #{Chef::VERSION}" + puts "#{ChefUtils::Dist::Infra::PRODUCT}: #{Chef::VERSION}" puts - puts "Docs: #{Chef::Dist::KNIFE_DOCS}" - puts "Patents: #{Chef::Dist::PATENTS}" + puts "Docs: #{ChefUtils::Dist::Org::KNIFE_DOCS}" + puts "Patents: #{ChefUtils::Dist::Org::PATENTS}" puts end diff --git a/lib/chef/application/solo.rb b/lib/chef/application/solo.rb index 9953d298a2..8264393bb9 100644 --- a/lib/chef/application/solo.rb +++ b/lib/chef/application/solo.rb @@ -21,6 +21,7 @@ require_relative "../../chef" require_relative "client" require "fileutils" unless defined?(FileUtils) require "pathname" unless defined?(Pathname) +require "chef-utils" unless defined?(ChefUtils::CANARY) # DO NOT MAKE EDITS, see Chef::Application::Base # @@ -33,7 +34,7 @@ class Chef::Application::Solo < Chef::Application::Base option :config_file, short: "-c CONFIG", long: "--config CONFIG", - default: Chef::Config.platform_specific_path("#{Chef::Dist::CONF_DIR}/solo.rb"), + default: Chef::Config.platform_specific_path("#{ChefConfig::Config.etc_chef_dir}/solo.rb"), description: "The configuration file to use." unless ChefUtils.windows? diff --git a/lib/chef/application/windows_service.rb b/lib/chef/application/windows_service.rb index 770a5644ca..8975556f75 100644 --- a/lib/chef/application/windows_service.rb +++ b/lib/chef/application/windows_service.rb @@ -29,7 +29,7 @@ require "socket" unless defined?(Socket) require "uri" unless defined?(URI) require "win32/daemon" require_relative "../mixin/shell_out" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Application @@ -41,7 +41,7 @@ class Chef short: "-c CONFIG", long: "--config CONFIG", default: "#{Chef::Config.etc_chef_dir}/client.rb", - description: "The configuration file to use for #{Chef::Dist::PRODUCT} runs." + description: "The configuration file to use for #{ChefUtils::Dist::Infra::PRODUCT} runs." option :log_location, short: "-L LOGLOCATION", @@ -57,7 +57,7 @@ class Chef option :interval, short: "-i SECONDS", long: "--interval SECONDS", - description: "Set the number of seconds to wait between #{Chef::Dist::PRODUCT} runs.", + description: "Set the number of seconds to wait between #{ChefUtils::Dist::Infra::PRODUCT} runs.", proc: lambda { |s| s.to_i } DEFAULT_LOG_LOCATION ||= "#{Chef::Config.c_chef_dir}/client.log".freeze @@ -67,7 +67,7 @@ class Chef @service_signal = ConditionVariable.new reconfigure - Chef::Log.info("#{Chef::Dist::CLIENT} Service initialized") + Chef::Log.info("#{ChefUtils::Dist::Infra::CLIENT} Service initialized") end def service_main(*startup_parameters) @@ -79,7 +79,7 @@ class Chef # Grab the service_action_mutex to make a chef-client run @service_action_mutex.synchronize do - Chef::Log.info("Next #{Chef::Dist::CLIENT} run will happen in #{timeout} seconds") + Chef::Log.info("Next #{ChefUtils::Dist::Infra::CLIENT} run will happen in #{timeout} seconds") @service_signal.wait(@service_action_mutex, timeout) # Continue only if service is RUNNING @@ -96,7 +96,7 @@ class Chef # run chef-client only if service is in RUNNING state next if state != RUNNING - Chef::Log.info("#{Chef::Dist::CLIENT} service is starting a #{Chef::Dist::CLIENT} run...") + Chef::Log.info("#{ChefUtils::Dist::Infra::CLIENT} service is starting a #{ChefUtils::Dist::Infra::CLIENT} run...") run_chef_client rescue SystemExit => e # Do not raise any of the errors here in order to @@ -131,12 +131,12 @@ class Chef break else unless run_warning_displayed - Chef::Log.info("Currently a #{Chef::Dist::PRODUCT} run is happening on this system.") + Chef::Log.info("Currently a #{ChefUtils::Dist::Infra::PRODUCT} run is happening on this system.") Chef::Log.info("Service will stop when run is completed.") run_warning_displayed = true end - Chef::Log.trace("Waiting for #{Chef::Dist::PRODUCT} run...") + Chef::Log.trace("Waiting for #{ChefUtils::Dist::Infra::PRODUCT} run...") sleep 1 end end @@ -150,7 +150,7 @@ class Chef # since this is a PAUSE signal. if @service_action_mutex.locked? - Chef::Log.info("Currently a #{Chef::Dist::PRODUCT} run is happening.") + Chef::Log.info("Currently a #{ChefUtils::Dist::Infra::PRODUCT} run is happening.") Chef::Log.info("Service will pause once it's completed.") else Chef::Log.info("Service is pausing....") @@ -185,7 +185,7 @@ class Chef # The log_location and config_file of the parent process is passed to the new chef-client process. # We need to add the --no-fork, as by default it is set to fork=true. - Chef::Log.info "Starting #{Chef::Dist::CLIENT} in a new process" + Chef::Log.info "Starting #{ChefUtils::Dist::Infra::CLIENT} in a new process" # Pass config params to the new process config_params = " --no-fork" config_params += " -c #{Chef::Config[:config_file]}" unless Chef::Config[:config_file].nil? @@ -197,20 +197,20 @@ class Chef # Starts a new process and waits till the process exits result = shell_out( - "#{Chef::Dist::CLIENT}.bat #{config_params}", + "#{ChefUtils::Dist::Infra::CLIENT}.bat #{config_params}", timeout: Chef::Config[:windows_service][:watchdog_timeout], logger: Chef::Log ) Chef::Log.trace (result.stdout).to_s Chef::Log.trace (result.stderr).to_s rescue Mixlib::ShellOut::CommandTimeout => e - Chef::Log.error "#{Chef::Dist::CLIENT} timed out\n(#{e})" + Chef::Log.error "#{ChefUtils::Dist::Infra::CLIENT} timed out\n(#{e})" Chef::Log.error(<<-EOF) - Your #{Chef::Dist::CLIENT} run timed out. You can increase the time #{Chef::Dist::CLIENT} is given + Your #{ChefUtils::Dist::Infra::CLIENT} run timed out. You can increase the time #{ChefUtils::Dist::Infra::CLIENT} is given to complete by configuring windows_service.watchdog_timeout in your client.rb. EOF rescue Mixlib::ShellOut::ShellCommandFailed => e - Chef::Log.warn "Not able to start #{Chef::Dist::CLIENT} in new process (#{e})" + Chef::Log.warn "Not able to start #{ChefUtils::Dist::Infra::CLIENT} in new process (#{e})" rescue => e Chef::Log.error e ensure diff --git a/lib/chef/application/windows_service_manager.rb b/lib/chef/application/windows_service_manager.rb index 25ac72e014..4f0de26411 100644 --- a/lib/chef/application/windows_service_manager.rb +++ b/lib/chef/application/windows_service_manager.rb @@ -21,7 +21,7 @@ if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) end require_relative "../config" require "mixlib/cli" unless defined?(Mixlib::CLI) -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Application @@ -41,18 +41,18 @@ class Chef short: "-a ACTION", long: "--action ACTION", default: "status", - description: "Action to carry out on #{Chef::Dist::SHORT}-service (install, uninstall, status, start, stop, pause, or resume)." + description: "Action to carry out on #{ChefUtils::Dist::Infra::SHORT}-service (install, uninstall, status, start, stop, pause, or resume)." option :config_file, short: "-c CONFIG", long: "--config CONFIG", default: "#{ChefConfig::Config.c_chef_dir}/client.rb", - description: "The configuration file to use for #{Chef::Dist::PRODUCT} runs." + description: "The configuration file to use for #{ChefUtils::Dist::Infra::PRODUCT} runs." option :log_location, short: "-L LOGLOCATION", long: "--logfile LOGLOCATION", - description: "Set the log file location for #{Chef::Dist::SHORT}-service." + description: "Set the log file location for #{ChefUtils::Dist::Infra::SHORT}-service." option :help, short: "-h", @@ -66,9 +66,9 @@ class Chef option :version, short: "-v", long: "--version", - description: "Show #{Chef::Dist::PRODUCT} version.", + description: "Show #{ChefUtils::Dist::Infra::PRODUCT} version.", boolean: true, - proc: lambda { |v| puts "#{Chef::Dist::PRODUCT}: #{::Chef::VERSION}" }, + proc: lambda { |v| puts "#{ChefUtils::Dist::Infra::PRODUCT}: #{::Chef::VERSION}" }, exit: 0 def initialize(service_options) diff --git a/lib/chef/chef_fs/chef_fs_data_store.rb b/lib/chef/chef_fs/chef_fs_data_store.rb index d7541a592e..eeeb96e38b 100644 --- a/lib/chef/chef_fs/chef_fs_data_store.rb +++ b/lib/chef/chef_fs/chef_fs_data_store.rb @@ -265,7 +265,7 @@ class Chef @memory_store.get(path) elsif path[0] == "file_store" && path[1] == "repo" - entry = Chef::ChefFS::FileSystem.resolve_path(chef_fs, path[2..-1].join("/")) + entry = Chef::ChefFS::FileSystem.resolve_path(chef_fs, path[2..].join("/")) begin entry.read rescue Chef::ChefFS::FileSystem::NotFoundError => e diff --git a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_entry.rb b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_entry.rb index d01d24c360..d28bb65db6 100644 --- a/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_entry.rb +++ b/lib/chef/chef_fs/file_system/repository/chef_repository_file_system_cookbook_entry.rb @@ -64,7 +64,7 @@ class Chef if is_dir return recursive && name != "." && name != ".." elsif ruby_only - return false if name[-3..-1] != ".rb" + return false if name[-3..] != ".rb" end # Check chefignore diff --git a/lib/chef/chef_fs/knife.rb b/lib/chef/chef_fs/knife.rb index 1e5f786b1d..ba993beee4 100644 --- a/lib/chef/chef_fs/knife.rb +++ b/lib/chef/chef_fs/knife.rb @@ -18,7 +18,7 @@ require_relative "../knife" require "pathname" unless defined?(Pathname) -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef module ChefFS @@ -49,7 +49,7 @@ class Chef option :chef_repo_path, long: "--chef-repo-path PATH", - description: "Overrides the location of #{Chef::Dist::PRODUCT} repo. Default is specified by chef_repo_path in the config" + description: "Overrides the location of #{ChefUtils::Dist::Infra::PRODUCT} repo. Default is specified by chef_repo_path in the config" option :concurrency, long: "--concurrency THREADS", diff --git a/lib/chef/chef_fs/parallelizer.rb b/lib/chef/chef_fs/parallelizer.rb index be7d93c669..c4d17a842d 100644 --- a/lib/chef/chef_fs/parallelizer.rb +++ b/lib/chef/chef_fs/parallelizer.rb @@ -1,4 +1,3 @@ -require "thread" require_relative "parallelizer/parallel_enumerable" class Chef diff --git a/lib/chef/client.rb b/lib/chef/client.rb index 1a6da64c8f..04d907634b 100644 --- a/lib/chef/client.rb +++ b/lib/chef/client.rb @@ -55,7 +55,6 @@ require_relative "mixin/deprecation" require "chef-utils" unless defined?(ChefUtils::CANARY) require "ohai" unless defined?(Ohai::System) require "rbconfig" unless defined?(RbConfig) -require_relative "dist" require "forwardable" unless defined?(Forwardable) class Chef @@ -245,11 +244,11 @@ class Chef events.run_start(Chef::VERSION, run_status) - logger.info("*** #{Chef::Dist::PRODUCT} #{Chef::VERSION} ***") + logger.info("*** #{ChefUtils::Dist::Infra::PRODUCT} #{Chef::VERSION} ***") logger.info("Platform: #{RUBY_PLATFORM}") - logger.info "#{Chef::Dist::CLIENT.capitalize} pid: #{Process.pid}" + logger.info "#{ChefUtils::Dist::Infra::CLIENT.capitalize} pid: #{Process.pid}" logger.info "Targeting node: #{Chef::Config.target_mode.host}" if Chef::Config.target_mode? - logger.debug("#{Chef::Dist::CLIENT.capitalize} request_id: #{request_id}") + logger.debug("#{ChefUtils::Dist::Infra::CLIENT.capitalize} request_id: #{request_id}") ENV["PATH"] = ChefUtils::DSL::DefaultPaths.default_paths if Chef::Config[:enforce_default_paths] || Chef::Config[:enforce_path_sanity] if Chef::Config.target_mode? @@ -273,7 +272,7 @@ class Chef build_node run_status.start_clock - logger.info("Starting #{Chef::Dist::PRODUCT} Run for #{node.name}") + logger.info("Starting #{ChefUtils::Dist::Infra::PRODUCT} Run for #{node.name}") run_started do_windows_admin_check @@ -288,7 +287,7 @@ class Chef converge_and_save(run_context) run_status.stop_clock - logger.info("#{Chef::Dist::PRODUCT} Run complete in #{run_status.elapsed_time} seconds") + logger.info("#{ChefUtils::Dist::Infra::PRODUCT} Run complete in #{run_status.elapsed_time} seconds") run_completed_successfully events.run_completed(node, run_status) @@ -334,7 +333,7 @@ class Chef eol_year = 2006 + Gem::Version.new(Chef::VERSION).segments.first if Time.now > Time.new(eol_year, 5, 01) - logger.warn("This release of #{Chef::Dist::PRODUCT} became end of life (EOL) on May 1st #{eol_year}. Please update to a supported release to receive new features, bug fixes, and security updates.") + logger.warn("This release of #{ChefUtils::Dist::Infra::PRODUCT} became end of life (EOL) on May 1st #{eol_year}. Please update to a supported release to receive new features, bug fixes, and security updates.") end end @@ -763,7 +762,7 @@ class Chef logger.trace("Checking for administrator privileges....") if !has_admin_privileges? - message = "#{Chef::Dist::CLIENT} doesn't have administrator privileges on node #{node_name}." + message = "#{ChefUtils::Dist::Infra::CLIENT} doesn't have administrator privileges on node #{node_name}." if Chef::Config[:fatal_windows_admin_check] logger.fatal(message) logger.fatal("fatal_windows_admin_check is set to TRUE.") @@ -772,7 +771,7 @@ class Chef logger.warn("#{message} This might cause unexpected resource failures.") end else - logger.trace("#{Chef::Dist::CLIENT} has administrator privileges on node #{node_name}.") + logger.trace("#{ChefUtils::Dist::Infra::CLIENT} has administrator privileges on node #{node_name}.") end end end diff --git a/lib/chef/cookbook/gem_installer.rb b/lib/chef/cookbook/gem_installer.rb index b652e5dee0..d7c18627de 100644 --- a/lib/chef/cookbook/gem_installer.rb +++ b/lib/chef/cookbook/gem_installer.rb @@ -47,7 +47,7 @@ class Chef v2 end end - cookbook_gems[args.first] += args[1..-1] + cookbook_gems[args.first] += args[1..] end end diff --git a/lib/chef/cookbook/synchronizer.rb b/lib/chef/cookbook/synchronizer.rb index 4a2940fb1f..53e874d0e8 100644 --- a/lib/chef/cookbook/synchronizer.rb +++ b/lib/chef/cookbook/synchronizer.rb @@ -17,7 +17,7 @@ require_relative "../client" require_relative "../util/threaded_job_queue" require_relative "../server_api" require "singleton" unless defined?(Singleton) -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef @@ -65,7 +65,7 @@ class Chef # manifest. cache.find(File.join(%w{cookbooks ** {*,.*}})).each do |cache_filename| unless @valid_cache_entries[cache_filename] - Chef::Log.info("Removing #{cache_filename} from the cache; it is no longer needed by #{Chef::Dist::CLIENT}.") + Chef::Log.info("Removing #{cache_filename} from the cache; it is no longer needed by #{ChefUtils::Dist::Infra::CLIENT}.") cache.delete(cache_filename) end end diff --git a/lib/chef/cookbook_site_streaming_uploader.rb b/lib/chef/cookbook_site_streaming_uploader.rb index 7de89f9ad8..65b27fed1d 100644 --- a/lib/chef/cookbook_site_streaming_uploader.rb +++ b/lib/chef/cookbook_site_streaming_uploader.rb @@ -28,7 +28,7 @@ module Mixlib autoload :SignedHeaderAuth, "mixlib/authentication/signedheaderauth" end end -require_relative "dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef # == Chef::CookbookSiteStreamingUploader @@ -43,7 +43,7 @@ class Chef class << self def create_build_dir(cookbook) - tmp_cookbook_path = Tempfile.new("#{Chef::Dist::SHORT}-#{cookbook.name}-build") + tmp_cookbook_path = Tempfile.new("#{ChefUtils::Dist::Infra::SHORT}-#{cookbook.name}-build") tmp_cookbook_path.close tmp_cookbook_dir = tmp_cookbook_path.path File.unlink(tmp_cookbook_dir) @@ -231,11 +231,7 @@ class Chef @part_no += 1 @part_offset = 0 next_part = read(how_much_next_part) - result = current_part + if next_part - next_part - else - "" - end + result = current_part + (next_part || "") else @part_offset += how_much_current_part result = current_part diff --git a/lib/chef/data_collector.rb b/lib/chef/data_collector.rb index e1d7d9b97b..39e5196a10 100644 --- a/lib/chef/data_collector.rb +++ b/lib/chef/data_collector.rb @@ -26,7 +26,7 @@ require_relative "data_collector/run_end_message" require_relative "data_collector/run_start_message" require_relative "data_collector/config_validation" require_relative "data_collector/error_handlers" -require_relative "dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class DataCollector @@ -197,7 +197,7 @@ class Chef else if code == "404" # Make the message non-scary for folks who don't have automate: - msg << " (This is normal if you do not have #{Chef::Dist::AUTOMATE})" + msg << " (This is normal if you do not have #{ChefUtils::Dist::Automate::PRODUCT})" Chef::Log.debug(msg) else Chef::Log.warn(msg) diff --git a/lib/chef/data_collector/config_validation.rb b/lib/chef/data_collector/config_validation.rb index a58472a82b..1cdc400f48 100644 --- a/lib/chef/data_collector/config_validation.rb +++ b/lib/chef/data_collector/config_validation.rb @@ -16,6 +16,7 @@ # require "uri" unless defined?(URI) +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class DataCollector @@ -86,7 +87,7 @@ class Chef false when running_mode == :client && Chef::Config[:data_collector][:token] Chef::Log.warn("Data collector token authentication is not recommended for client-server mode. " \ - "Please upgrade #{Chef::Dist::SERVER_PRODUCT} to 12.11 or later and remove the token from your config file " \ + "Please upgrade #{ChefUtils::Dist::Server::PRODUCT} to 12.11 or later and remove the token from your config file " \ "to use key based authentication instead") true when Chef::Config[:data_collector][:output_locations] && !valid_hash_with_keys?(Chef::Config[:data_collector][:output_locations], :urls) @@ -99,7 +100,7 @@ class Chef true when running_mode == :solo && !Chef::Config[:data_collector][:token] # we are in solo mode and are not logging to a file, so must have a token - Chef::Log.trace("Data collector token must be configured to use #{Chef::Dist::AUTOMATE} data collector with #{Chef::Dist::SOLO}") + Chef::Log.trace("Data collector token must be configured to use #{ChefUtils::Dist::Automate::PRODUCT} data collector with #{ChefUtils::Dist::Solo::PRODUCT}") false else true diff --git a/lib/chef/deprecation/warnings.rb b/lib/chef/deprecation/warnings.rb index 201158114f..f83101ca3e 100644 --- a/lib/chef/deprecation/warnings.rb +++ b/lib/chef/deprecation/warnings.rb @@ -21,12 +21,12 @@ class Chef module Warnings require_relative "../version" - require_relative "../dist" + require "chef-utils/dist" unless defined?(ChefUtils::Dist) def add_deprecation_warnings_for(method_names) method_names.each do |name| define_method(name) do |*args| - message = "Method '#{name}' of '#{self.class}' is deprecated. It will be removed in #{Chef::Dist::PRODUCT} #{Chef::VERSION.to_i.next}." + message = "Method '#{name}' of '#{self.class}' is deprecated. It will be removed in #{ChefUtils::Dist::Infra::PRODUCT} #{Chef::VERSION.to_i.next}." message << " Please update your cookbooks accordingly." Chef.deprecated(:internal_api, message) super(*args) diff --git a/lib/chef/dist.rb b/lib/chef/dist.rb deleted file mode 100644 index b706f2d28f..0000000000 --- a/lib/chef/dist.rb +++ /dev/null @@ -1,74 +0,0 @@ -class Chef - class Dist - require "chef-config/dist" - require "chef-config/config" - - # This class is not fully implemented, depending on it is not recommended! - # When referencing a product directly, like Chef (Now Chef Infra) - PRODUCT = "Chef Infra Client".freeze - - # A short designation for the product, used in Windows event logs - # and some nomenclature. - SHORT = ChefConfig::Dist::SHORT.freeze - - # The name of the server product - SERVER_PRODUCT = "Chef Infra Server".freeze - - # The client's alias (chef-client) - CLIENT = ChefConfig::Dist::CLIENT.freeze - - # name of the automate product - AUTOMATE = "Chef Automate".freeze - - # The chef executable, as in `chef gem install` or `chef generate cookbook` - EXEC = ChefConfig::Dist::EXEC.freeze - - # product website address - WEBSITE = "https://chef.io".freeze - - # product patents page - PATENTS = "https://www.chef.io/patents".freeze - - # knife documentation page - KNIFE_DOCS = "https://docs.chef.io/workstation/knife/".freeze - - # Chef-Zero's product name - ZERO = "Chef Infra Zero".freeze - - # Chef-Solo's product name - SOLO = "Chef Infra Solo".freeze - - # The chef-zero executable (local mode) - ZEROEXEC = "chef-zero".freeze - - # The chef-solo executable (legacy local mode) - SOLOEXEC = "chef-solo".freeze - - # The chef-shell executable - SHELL = "chef-shell".freeze - - # The chef-apply executable - APPLY = "chef-apply".freeze - - # Configuration related constants - # The chef-shell configuration file - SHELL_CONF = "chef_shell.rb".freeze - - # The configuration directory - CONF_DIR = ChefConfig::Config.etc_chef_dir.freeze - - # The user's configuration directory - USER_CONF_DIR = ChefConfig::Dist::USER_CONF_DIR.freeze - - # The suffix for Chef's /etc/chef, /var/chef and C:\\Chef directories - # "cinc" => /etc/cinc, /var/cinc, C:\\cinc - DIR_SUFFIX = ChefConfig::Dist::DIR_SUFFIX.freeze - - # The legacy conf folder: C:/opscode/chef. Specifically the "opscode" part - # DIR_SUFFIX is appended to it in code where relevant - LEGACY_CONF_DIR = ChefConfig::Dist::LEGACY_CONF_DIR.freeze - - # The server's configuration directory - SERVER_CONF_DIR = "/etc/chef-server".freeze - end -end diff --git a/lib/chef/encrypted_data_bag_item.rb b/lib/chef/encrypted_data_bag_item.rb index c36c6923c5..9cf1a71db2 100644 --- a/lib/chef/encrypted_data_bag_item.rb +++ b/lib/chef/encrypted_data_bag_item.rb @@ -20,7 +20,6 @@ require_relative "config" Chef.autoload :DataBagItem, File.expand_path("data_bag_item", __dir__) require_relative "encrypted_data_bag_item/decryptor" require_relative "encrypted_data_bag_item/encryptor" -require_relative "dist" # An EncryptedDataBagItem represents a read-only data bag item where # all values, except for the value associated with the id key, have @@ -131,7 +130,7 @@ class Chef::EncryptedDataBagItem require "open-uri" unless defined?(OpenURI) path ||= Chef::Config[:encrypted_data_bag_secret] unless path - raise ArgumentError, "No secret specified and no secret found at #{Chef::Config.platform_specific_path(Chef::Dist::CONF_DIR + "/encrypted_data_bag_secret")}" + raise ArgumentError, "No secret specified and no secret found at #{Chef::Config.platform_specific_path(ChefConfig::Config.etc_chef_dir) + "/encrypted_data_bag_secret"}" end secret = case path diff --git a/lib/chef/environment.rb b/lib/chef/environment.rb index 4f0c365443..d6a2215423 100644 --- a/lib/chef/environment.rb +++ b/lib/chef/environment.rb @@ -25,7 +25,7 @@ require_relative "mixin/params_validate" require_relative "mixin/from_file" require_relative "version_constraint" require_relative "server_api" -require_relative "dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Environment @@ -308,7 +308,7 @@ class Chef def self.validate_cookbook_version(version) if Chef::Config[:solo_legacy_mode] raise Chef::Exceptions::IllegalVersionConstraint, - "Environment cookbook version constraints not allowed in #{Chef::Dist::SOLO}" + "Environment cookbook version constraints not allowed in #{ChefUtils::Dist::Solo::PRODUCT}" else Chef::VersionConstraint.new version true diff --git a/lib/chef/event_loggers/windows_eventlog.rb b/lib/chef/event_loggers/windows_eventlog.rb index 1b9037fdb3..6b290eb8a7 100644 --- a/lib/chef/event_loggers/windows_eventlog.rb +++ b/lib/chef/event_loggers/windows_eventlog.rb @@ -19,7 +19,7 @@ require_relative "base" require_relative "../platform/query_helpers" require_relative "../win32/eventlog" -require_relative "../dist" +require "chef-utils" unless defined?(ChefUtils::CANARY) class Chef module EventLoggers @@ -36,7 +36,7 @@ class Chef LOG_CATEGORY_ID = 11001 # Since we must install the event logger, this is not really configurable - SOURCE = Chef::Dist::SHORT.freeze + SOURCE = ChefUtils::Dist::Infra::SHORT.freeze def self.available? ChefUtils.windows? diff --git a/lib/chef/exceptions.rb b/lib/chef/exceptions.rb index 52a2cc8439..16134fe44b 100644 --- a/lib/chef/exceptions.rb +++ b/lib/chef/exceptions.rb @@ -18,7 +18,7 @@ # limitations under the License. require "chef-config/exceptions" -require_relative "dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) require_relative "constants" class Chef @@ -301,7 +301,7 @@ class Chef def client_run_failure(exception) set_backtrace(exception.backtrace) - @all_failures << [ "#{Chef::Dist::PRODUCT} run", exception ] + @all_failures << [ "#{ChefUtils::Dist::Infra::PRODUCT} run", exception ] end def notification_failure(exception) @@ -402,7 +402,7 @@ class Chef def initialize(response_length, content_length) super <<~EOF Response body length #{response_length} does not match HTTP Content-Length header #{content_length}. - This error is most often caused by network issues (proxies, etc) outside of #{Chef::Dist::CLIENT}. + This error is most often caused by network issues (proxies, etc) outside of #{ChefUtils::Dist::Infra::CLIENT}. EOF end end @@ -477,7 +477,7 @@ class Chef class CookbookChefVersionMismatch < RuntimeError def initialize(chef_version, cookbook_name, cookbook_version, *constraints) constraint_str = constraints.map { |c| c.requirement.as_list.to_s }.join(", ") - super "Cookbook '#{cookbook_name}' version '#{cookbook_version}' depends on #{Chef::Dist::PRODUCT} version #{constraint_str}, but the running #{Chef::Dist::PRODUCT} version is #{chef_version}" + super "Cookbook '#{cookbook_name}' version '#{cookbook_version}' depends on #{ChefUtils::Dist::Infra::PRODUCT} version #{constraint_str}, but the running #{ChefUtils::Dist::Infra::PRODUCT} version is #{chef_version}" end end diff --git a/lib/chef/file_access_control/windows.rb b/lib/chef/file_access_control/windows.rb index 118eae179c..9e5f07428c 100644 --- a/lib/chef/file_access_control/windows.rb +++ b/lib/chef/file_access_control/windows.rb @@ -112,7 +112,11 @@ class Chef def get_sid(value) if value.is_a?(String) - SID.from_account(value) + begin + Security.convert_string_sid_to_sid(value) + rescue Chef::Exceptions::Win32APIError + SID.from_account(value) + end elsif value.is_a?(SID) value else diff --git a/lib/chef/file_content_management/tempfile.rb b/lib/chef/file_content_management/tempfile.rb index 763648de33..27efe34191 100644 --- a/lib/chef/file_content_management/tempfile.rb +++ b/lib/chef/file_content_management/tempfile.rb @@ -76,7 +76,7 @@ class Chef # complexity here is due to supporting mangling non-UTF8 strings (e.g. latin-1 filenames with characters that are illegal in UTF-8) b = File.basename(@new_resource.path) i = b.index(".") - i.nil? ? "" : b[i..-1].scrub + i.nil? ? "" : b[i..].scrub end # Returns the possible directories for the tempfile to be created in. diff --git a/lib/chef/formatters/doc.rb b/lib/chef/formatters/doc.rb index 557f2b3682..513ac45471 100644 --- a/lib/chef/formatters/doc.rb +++ b/lib/chef/formatters/doc.rb @@ -1,6 +1,6 @@ require_relative "base" require_relative "../config" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef module Formatters @@ -41,8 +41,8 @@ class Chef end def run_start(version, run_status) - puts_line "Starting #{Chef::Dist::PRODUCT}, version #{version}" - puts_line "Patents: #{Chef::Dist::PATENTS}" + puts_line "Starting #{ChefUtils::Dist::Infra::PRODUCT}, version #{version}" + puts_line "Patents: #{ChefUtils::Dist::Org::PATENTS}" puts_line "Targeting node: #{Chef::Config.target_mode.host}" if Chef::Config.target_mode? puts_line "OpenSSL FIPS 140 mode enabled" if Chef::Config[:fips] end @@ -78,18 +78,18 @@ class Chef puts_line "" end if Chef::Config[:why_run] - puts_line "#{Chef::Dist::PRODUCT} finished, #{@updated_resources}/#{total_resources} resources would have been updated" + puts_line "#{ChefUtils::Dist::Infra::PRODUCT} finished, #{@updated_resources}/#{total_resources} resources would have been updated" else - puts_line "#{Chef::Dist::PRODUCT} finished, #{@updated_resources}/#{total_resources} resources updated in #{pretty_elapsed_time}" + puts_line "#{ChefUtils::Dist::Infra::PRODUCT} finished, #{@updated_resources}/#{total_resources} resources updated in #{pretty_elapsed_time}" end end def run_failed(exception) @end_time = Time.now if Chef::Config[:why_run] - puts_line "#{Chef::Dist::PRODUCT} failed. #{@updated_resources} resources would have been updated" + puts_line "#{ChefUtils::Dist::Infra::PRODUCT} failed. #{@updated_resources} resources would have been updated" else - puts_line "#{Chef::Dist::PRODUCT} failed. #{@updated_resources} resources updated in #{pretty_elapsed_time}" + puts_line "#{ChefUtils::Dist::Infra::PRODUCT} failed. #{@updated_resources} resources updated in #{pretty_elapsed_time}" end end diff --git a/lib/chef/formatters/error_inspectors/api_error_formatting.rb b/lib/chef/formatters/error_inspectors/api_error_formatting.rb index 47e8523323..ee4583c89b 100644 --- a/lib/chef/formatters/error_inspectors/api_error_formatting.rb +++ b/lib/chef/formatters/error_inspectors/api_error_formatting.rb @@ -17,7 +17,7 @@ # require_relative "../../http/authenticator" -require_relative "../../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) require "timeout" unless defined?(Timeout) class Chef @@ -41,7 +41,7 @@ class Chef def describe_eof_error(error_description) error_description.section("Authentication Error:", <<~E) Received an EOF on transport socket. This almost always indicates a network - error external to #{Chef::Dist::CLIENT}. Some causes include: + error external to #{ChefUtils::Dist::Infra::CLIENT}. Some causes include: - Blocking ICMP Dest Unreachable (breaking Path MTU Discovery) - IPsec or VPN tunnelling / TCP Encapsulation MTU issues @@ -115,8 +115,8 @@ class Chef error_description.section("Incompatible server API version:", <<~E) This version of the API that this request specified is not supported by the server you sent this request to. The server supports a min API version of #{min_server_version} and a max API version of #{max_server_version}. - #{Chef::Dist::PRODUCT} just made a request with an API version of #{client_api_version}. - Please either update your #{Chef::Dist::PRODUCT} or the server to be a compatible set. + #{ChefUtils::Dist::Infra::PRODUCT} just made a request with an API version of #{client_api_version}. + Please either update your #{ChefUtils::Dist::Infra::PRODUCT} or the server to be a compatible set. E else describe_http_error(error_description) @@ -131,7 +131,7 @@ class Chef end def describe_503_error(error_description) - error_description.section("Server Unavailable", "The #{Chef::Dist::SERVER_PRODUCT} is temporarily unavailable") + error_description.section("Server Unavailable", "The #{ChefUtils::Dist::Server::PRODUCT} is temporarily unavailable") error_description.section("Server Response:", format_rest_error) end diff --git a/lib/chef/formatters/error_inspectors/node_load_error_inspector.rb b/lib/chef/formatters/error_inspectors/node_load_error_inspector.rb index 3a3f602203..7e904c9ee2 100644 --- a/lib/chef/formatters/error_inspectors/node_load_error_inspector.rb +++ b/lib/chef/formatters/error_inspectors/node_load_error_inspector.rb @@ -17,7 +17,7 @@ # require_relative "api_error_formatting" -require_relative "../../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef module Formatters @@ -46,7 +46,7 @@ class Chef when Chef::Exceptions::PrivateKeyMissing error_description.section("Private Key Not Found:", <<~E) Your private key could not be loaded. If the key file exists, ensure that it is - readable by #{Chef::Dist::PRODUCT}. + readable by #{ChefUtils::Dist::Infra::PRODUCT}. E error_description.section("Relevant Config Settings:", <<~E) client_key "#{api_key}" @@ -99,7 +99,7 @@ class Chef # redirect. def describe_404_error(error_description) error_description.section("Resource Not Found:", <<~E) - The #{Chef::Dist::SERVER_PRODUCT} returned a HTTP 404. This usually indicates that your chef_server_url is incorrect. + The #{ChefUtils::Dist::Server::PRODUCT} returned a HTTP 404. This usually indicates that your chef_server_url is incorrect. E error_description.section("Relevant Config Settings:", <<~E) chef_server_url "#{server_url}" diff --git a/lib/chef/formatters/error_inspectors/registration_error_inspector.rb b/lib/chef/formatters/error_inspectors/registration_error_inspector.rb index 565ea217b8..4897ac6e1b 100644 --- a/lib/chef/formatters/error_inspectors/registration_error_inspector.rb +++ b/lib/chef/formatters/error_inspectors/registration_error_inspector.rb @@ -1,4 +1,4 @@ -require_relative "../../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef module Formatters @@ -28,7 +28,7 @@ class Chef humanize_http_exception(error_description) when Errno::ECONNREFUSED, Timeout::Error, Errno::ETIMEDOUT, SocketError error_description.section("Network Error:", <<~E) - There was a network error connecting to the #{Chef::Dist::SERVER_PRODUCT}: + There was a network error connecting to the #{ChefUtils::Dist::Server::PRODUCT}: #{exception.message} E error_description.section("Relevant Config Settings:", <<~E) @@ -39,14 +39,14 @@ class Chef when Chef::Exceptions::PrivateKeyMissing error_description.section("Private Key Not Found:", <<~E) Your private key could not be loaded. If the key file exists, ensure that it is - readable by #{Chef::Dist::PRODUCT}. + readable by #{ChefUtils::Dist::Infra::PRODUCT}. E error_description.section("Relevant Config Settings:", <<~E) validation_key "#{api_key}" E when Chef::Exceptions::InvalidRedirect error_description.section("Invalid Redirect:", <<~E) - Change your #{Chef::Dist::SERVER_PRODUCT} location in client.rb to the #{Chef::Dist::SERVER_PRODUCT}'s FQDN to avoid unwanted redirections. + Change your #{ChefUtils::Dist::Server::PRODUCT} location in client.rb to the #{ChefUtils::Dist::Server::PRODUCT}'s FQDN to avoid unwanted redirections. E when EOFError describe_eof_error(error_description) @@ -61,13 +61,13 @@ class Chef when Net::HTTPUnauthorized if clock_skew? error_description.section("Authentication Error:", <<~E) - Failed to authenticate to the #{Chef::Dist::SERVER_PRODUCT} (http 401). + Failed to authenticate to the #{ChefUtils::Dist::Server::PRODUCT} (http 401). The request failed because your clock has drifted by more than 15 minutes. Syncing your clock to an NTP Time source should resolve the issue. E else error_description.section("Authentication Error:", <<~E) - Failed to authenticate to the #{Chef::Dist::SERVER_PRODUCT} (http 401). + Failed to authenticate to the #{ChefUtils::Dist::Server::PRODUCT} (http 401). E error_description.section("Server Response:", format_rest_error) @@ -81,7 +81,7 @@ class Chef end when Net::HTTPForbidden error_description.section("Authorization Error:", <<~E) - Your validation client is not authorized to create the client for this node on the #{Chef::Dist::SERVER_PRODUCT} (HTTP 403). + Your validation client is not authorized to create the client for this node on the #{ChefUtils::Dist::Server::PRODUCT} (HTTP 403). E error_description.section("Possible Causes:", <<~E) * There may already be a client named "#{config[:node_name]}" @@ -94,7 +94,7 @@ class Chef error_description.section("Server Response:", format_rest_error) when Net::HTTPNotFound error_description.section("Resource Not Found:", <<~E) - The #{Chef::Dist::SERVER_PRODUCT} returned a HTTP 404. This usually indicates that your chef_server_url configuration is incorrect. + The #{ChefUtils::Dist::Server::PRODUCT} returned a HTTP 404. This usually indicates that your chef_server_url configuration is incorrect. E error_description.section("Relevant Config Settings:", <<~E) chef_server_url "#{server_url}" @@ -107,7 +107,7 @@ class Chef E error_description.section("Server Response:", format_rest_error) when Net::HTTPBadGateway, Net::HTTPServiceUnavailable - error_description.section("Server Unavailable", "The #{Chef::Dist::SERVER_PRODUCT} is temporarily unavailable") + error_description.section("Server Unavailable", "The #{ChefUtils::Dist::Server::PRODUCT} is temporarily unavailable") error_description.section("Server Response:", format_rest_error) else error_description.section("Unexpected API Request Failure:", format_rest_error) diff --git a/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb b/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb index fa7580d2c3..d858c756a4 100644 --- a/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb +++ b/lib/chef/formatters/error_inspectors/resource_failure_inspector.rb @@ -16,7 +16,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # -require_relative "../../dist" +require "chef-utils" unless defined?(ChefUtils::CANARY) class Chef module Formatters @@ -56,7 +56,7 @@ class Chef require_relative "../../win32/security" unless Chef::ReservedNames::Win32::Security.has_admin_privileges? - error_description.section("Missing Windows Admin Privileges", "#{Chef::Dist::CLIENT} doesn't have administrator privileges. This can be a possible reason for the resource failure.") + error_description.section("Missing Windows Admin Privileges", "#{ChefUtils::Dist::Infra::CLIENT} doesn't have administrator privileges. This can be a possible reason for the resource failure.") end end end diff --git a/lib/chef/formatters/error_inspectors/run_list_expansion_error_inspector.rb b/lib/chef/formatters/error_inspectors/run_list_expansion_error_inspector.rb index ca3dec138b..6e452c959b 100644 --- a/lib/chef/formatters/error_inspectors/run_list_expansion_error_inspector.rb +++ b/lib/chef/formatters/error_inspectors/run_list_expansion_error_inspector.rb @@ -18,7 +18,7 @@ # require_relative "api_error_formatting" -require_relative "../../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef module Formatters @@ -78,7 +78,7 @@ class Chef case response when Net::HTTPUnauthorized error_description.section("Authentication Error:", <<~E) - Failed to authenticate to the #{Chef::Dist::SERVER_PRODUCT} (http 401). + Failed to authenticate to the #{ChefUtils::Dist::Server::PRODUCT} (http 401). E error_description.section("Server Response:", format_rest_error) @@ -109,7 +109,7 @@ class Chef E error_description.section("Server Response:", format_rest_error) when Net::HTTPBadGateway, Net::HTTPServiceUnavailable - error_description.section("Server Unavailable", "The #{Chef::Dist::SERVER_PRODUCT} is temporarily unavailable") + error_description.section("Server Unavailable", "The #{ChefUtils::Dist::Server::PRODUCT} is temporarily unavailable") error_description.section("Server Response:", format_rest_error) else error_description.section("Unexpected API Request Failure:", format_rest_error) diff --git a/lib/chef/formatters/indentable_output_stream.rb b/lib/chef/formatters/indentable_output_stream.rb index d508a32eb0..4943041b37 100644 --- a/lib/chef/formatters/indentable_output_stream.rb +++ b/lib/chef/formatters/indentable_output_stream.rb @@ -20,7 +20,7 @@ class Chef # pastel.decorate is a lightweight replacement for highline.color def pastel @pastel ||= begin - require "pastel" + require "pastel" unless defined?(Pastel) Pastel.new end end @@ -126,7 +126,7 @@ class Chef indent_line(options) # Note that the next line will need to be started - if line[-1..-1] == "\n" + if line[-1..] == "\n" @line_started = false end diff --git a/lib/chef/formatters/minimal.rb b/lib/chef/formatters/minimal.rb index ba616798ab..6a067c4f86 100644 --- a/lib/chef/formatters/minimal.rb +++ b/lib/chef/formatters/minimal.rb @@ -1,5 +1,5 @@ require_relative "base" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef @@ -28,20 +28,20 @@ class Chef # Called at the very start of a Chef Run def run_start(version, run_status) - puts_line "Starting #{Chef::Dist::PRODUCT}, version #{version}" - puts_line "Patents: #{Chef::Dist::PATENTS}" + puts_line "Starting #{ChefUtils::Dist::Infra::PRODUCT}, version #{version}" + puts_line "Patents: #{ChefUtils::Dist::Org::PATENTS}" puts_line "Targeting node: #{Chef::Config.target_mode.host}" if Chef::Config.target_mode? puts_line "OpenSSL FIPS 140 mode enabled" if Chef::Config[:fips] end # Called at the end of the Chef run. def run_completed(node) - puts "#{Chef::Dist::PRODUCT} finished, #{@updated_resources.size} resources updated" + puts "#{ChefUtils::Dist::Infra::PRODUCT} finished, #{@updated_resources.size} resources updated" end # called at the end of a failed run def run_failed(exception) - puts "#{Chef::Dist::PRODUCT} failed. #{@updated_resources.size} resources updated" + puts "#{ChefUtils::Dist::Infra::PRODUCT} failed. #{@updated_resources.size} resources updated" end # Called right after ohai runs. diff --git a/lib/chef/http/http_request.rb b/lib/chef/http/http_request.rb index dbb1e0ce70..e6952aed9e 100644 --- a/lib/chef/http/http_request.rb +++ b/lib/chef/http/http_request.rb @@ -25,7 +25,7 @@ autoload :CGI, "cgi" module Net autoload :HTTP, File.expand_path("../monkey_patches/net_http", __dir__) end -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) # To load faster, we only want ohai's version string. # However, in ohai before 0.6.0, the version is defined @@ -44,7 +44,7 @@ class Chef engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : "ruby" - UA_COMMON = "/#{::Chef::VERSION} (#{engine}-#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}; ohai-#{Ohai::VERSION}; #{RUBY_PLATFORM}; +#{Chef::Dist::WEBSITE})".freeze + UA_COMMON = "/#{::Chef::VERSION} (#{engine}-#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}; ohai-#{Ohai::VERSION}; #{RUBY_PLATFORM}; +#{ChefUtils::Dist::Org::WEBSITE})".freeze DEFAULT_UA = "Chef Client" << UA_COMMON USER_AGENT = "User-Agent".freeze diff --git a/lib/chef/http/socketless_chef_zero_client.rb b/lib/chef/http/socketless_chef_zero_client.rb index feebba5a2c..9664f6feed 100644 --- a/lib/chef/http/socketless_chef_zero_client.rb +++ b/lib/chef/http/socketless_chef_zero_client.rb @@ -44,7 +44,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require "chef_zero/server" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) module Net autoload :HTTPResponse, File.expand_path("../monkey_patches/net_http", __dir__) end @@ -67,7 +67,7 @@ class Chef # or else streaming-style responses won't work. def read_body(dest = nil, &block) if dest - raise "responses from socketless #{Chef::Dist::ZERO} can't be written to specific destination" + raise "responses from socketless #{ChefUtils::Dist::Zero::PRODUCT} can't be written to specific destination" end if block_given? diff --git a/lib/chef/knife.rb b/lib/chef/knife.rb index e1f2d56aaf..ac7a68d0fc 100644 --- a/lib/chef/knife.rb +++ b/lib/chef/knife.rb @@ -21,6 +21,7 @@ require "forwardable" unless defined?(Forwardable) require_relative "version" require "mixlib/cli" unless defined?(Mixlib::CLI) require "chef-utils/dsl/default_paths" unless defined?(ChefUtils::DSL::DefaultPaths) +require "chef-utils/dist" unless defined?(ChefUtils::Dist) require_relative "workstation_config_loader" require_relative "mixin/convert_to_class_name" require_relative "mixin/default_paths" @@ -32,12 +33,11 @@ require_relative "http/authenticator" require_relative "http/http_request" require_relative "http" require "pp" unless defined?(PP) -require_relative "dist" class Chef class Knife - Chef::HTTP::HTTPRequest.user_agent = "#{Chef::Dist::PRODUCT} Knife#{Chef::HTTP::HTTPRequest::UA_COMMON}" + Chef::HTTP::HTTPRequest.user_agent = "#{ChefUtils::Dist::Infra::PRODUCT} Knife#{Chef::HTTP::HTTPRequest::UA_COMMON}" include Mixlib::CLI include ChefUtils::DSL::DefaultPaths @@ -282,7 +282,7 @@ class Chef elsif category_commands = guess_category(args) list_commands(category_commands) elsif OFFICIAL_PLUGINS.include?(args[0]) # command was an uninstalled official chef knife plugin - ui.info("Use `#{Chef::Dist::EXEC} gem install knife-#{args[0]}` to install the plugin into Chef Workstation") + ui.info("Use `#{ChefUtils::Dist::Infra::EXEC} gem install knife-#{args[0]}` to install the plugin into Chef Workstation") else list_commands end @@ -564,7 +564,7 @@ class Chef ui.error "The API version that Knife is using is not supported by the server you sent this request to." ui.info "The request that Knife sent was using API version #{client_api_version}." ui.info "The server you sent the request to supports a min API version of #{min_server_version} and a max API version of #{max_server_version}." - ui.info "Please either update your #{Chef::Dist::PRODUCT} or the server to be a compatible set." + ui.info "Please either update your #{ChefUtils::Dist::Infra::PRODUCT} or the server to be a compatible set." else ui.error response.message ui.info "Response: #{format_rest_error(response)}" diff --git a/lib/chef/knife/bootstrap.rb b/lib/chef/knife/bootstrap.rb index b78911e071..efd969210b 100644 --- a/lib/chef/knife/bootstrap.rb +++ b/lib/chef/knife/bootstrap.rb @@ -18,7 +18,7 @@ require_relative "../knife" require_relative "data_bag_secret_options" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) require "license_acceptance/cli_flags/mixlib_cli" module LicenseAcceptance autoload :Acceptor, "license_acceptance/acceptor" @@ -146,7 +146,7 @@ class Chef # client.rb content via chef-full/bootstrap_context option :bootstrap_version, long: "--bootstrap-version VERSION", - description: "The version of #{Chef::Dist::PRODUCT} to install." + description: "The version of #{ChefUtils::Dist::Infra::PRODUCT} to install." option :channel, long: "--channel CHANNEL", @@ -178,7 +178,7 @@ class Chef option :bootstrap_template, short: "-t TEMPLATE", long: "--bootstrap-template TEMPLATE", - description: "Bootstrap #{Chef::Dist::PRODUCT} using a built-in or custom template. Set to the full path of an erb template or use one of the built-in templates." + description: "Bootstrap #{ChefUtils::Dist::Infra::PRODUCT} using a built-in or custom template. Set to the full path of an erb template or use one of the built-in templates." # client.rb content via bootstrap_context option :node_ssl_verify_mode, @@ -196,7 +196,7 @@ class Chef # bootstrap_context - client.rb option :node_verify_api_cert, long: "--[no-]node-verify-api-cert", - description: "Verify the SSL cert for HTTPS requests to the #{Chef::Dist::SERVER_PRODUCT} API.", + description: "Verify the SSL cert for HTTPS requests to the #{ChefUtils::Dist::Server::PRODUCT} API.", boolean: true # runtime - sudo settings (train handles sudo) @@ -254,14 +254,14 @@ class Chef option :first_boot_attributes, short: "-j JSON_ATTRIBS", long: "--json-attributes", - description: "A JSON string to be added to the first run of #{Chef::Dist::CLIENT}.", + description: "A JSON string to be added to the first run of #{ChefUtils::Dist::Infra::CLIENT}.", proc: lambda { |o| Chef::JSONCompat.parse(o) }, default: nil # bootstrap template option :first_boot_attributes_from_file, long: "--json-attribute-file FILE", - description: "A JSON file to be used to the first run of #{Chef::Dist::CLIENT}.", + description: "A JSON file to be used to the first run of #{ChefUtils::Dist::Infra::CLIENT}.", proc: lambda { |o| Chef::JSONCompat.parse(File.read(o)) }, default: nil @@ -292,28 +292,28 @@ class Chef option :msi_url, # Windows target only short: "-m URL", long: "--msi-url URL", - description: "Location of the #{Chef::Dist::PRODUCT} MSI. The default templates will prefer to download from this location. The MSI will be downloaded from #{Chef::Dist::WEBSITE} if not provided (Windows).", + description: "Location of the #{ChefUtils::Dist::Infra::PRODUCT} MSI. The default templates will prefer to download from this location. The MSI will be downloaded from #{ChefUtils::Dist::Org::WEBSITE} if not provided (Windows).", default: "" # bootstrap override: Do this instead of our own setup.sh from omnitruck. Causes bootstrap_url to be ignored. option :bootstrap_install_command, long: "--bootstrap-install-command COMMANDS", - description: "Custom command to install #{Chef::Dist::PRODUCT}." + description: "Custom command to install #{ChefUtils::Dist::Infra::PRODUCT}." # bootstrap template: Run this command first in the bootstrap script option :bootstrap_preinstall_command, long: "--bootstrap-preinstall-command COMMANDS", - description: "Custom commands to run before installing #{Chef::Dist::PRODUCT}." + description: "Custom commands to run before installing #{ChefUtils::Dist::Infra::PRODUCT}." # bootstrap template option :bootstrap_wget_options, long: "--bootstrap-wget-options OPTIONS", - description: "Add options to wget when installing #{Chef::Dist::PRODUCT}." + description: "Add options to wget when installing #{ChefUtils::Dist::Infra::PRODUCT}." # bootstrap template option :bootstrap_curl_options, long: "--bootstrap-curl-options OPTIONS", - description: "Add options to curl when install #{Chef::Dist::PRODUCT}." + description: "Add options to curl when install #{ChefUtils::Dist::Infra::PRODUCT}." # chef_vault_handler option :bootstrap_vault_file, @@ -540,7 +540,7 @@ class Chef end def run - check_license if ChefConfig::Dist::ENFORCE_LICENSE + check_license if ChefUtils::Dist::Org::ENFORCE_LICENSE plugin_setup! validate_name_args! diff --git a/lib/chef/knife/bootstrap/chef_vault_handler.rb b/lib/chef/knife/bootstrap/chef_vault_handler.rb index b36c178d8e..20759d6fdf 100644 --- a/lib/chef/knife/bootstrap/chef_vault_handler.rb +++ b/lib/chef/knife/bootstrap/chef_vault_handler.rb @@ -112,7 +112,7 @@ class Chef if bootstrap_vault_item bootstrap_vault_item else - json = bootstrap_vault_json ? bootstrap_vault_json : File.read(bootstrap_vault_file) + json = bootstrap_vault_json || File.read(bootstrap_vault_file) Chef::JSONCompat.from_json(json) end end diff --git a/lib/chef/knife/bootstrap/templates/chef-full.erb b/lib/chef/knife/bootstrap/templates/chef-full.erb index 5006009617..2e0c80eaef 100644 --- a/lib/chef/knife/bootstrap/templates/chef-full.erb +++ b/lib/chef/knife/bootstrap/templates/chef-full.erb @@ -172,8 +172,8 @@ do_download() { <%= @config[:bootstrap_install_command] %> <% else %> install_sh="<%= @config[:bootstrap_url] ? @config[:bootstrap_url] : "https://omnitruck.chef.io/chef/install.sh" %>" - if test -f /usr/bin/<%= Chef::Dist::CLIENT %>; then - echo "-----> Existing <%= Chef::Dist::PRODUCT %> installation detected" + if test -f /usr/bin/<%= ChefUtils::Dist::Infra::CLIENT %>; then + echo "-----> Existing <%= ChefUtils::Dist::Infra::PRODUCT %> installation detected" else echo "-----> Installing Chef Omnibus (<%= @config[:channel] %>/<%= version_to_install %>)" do_download ${install_sh} $tmp_dir/install.sh @@ -237,6 +237,6 @@ mkdir -p /etc/chef/client.d <%= client_d %> <% end -%> -echo "Starting the first <%= Chef::Dist::PRODUCT %> Client run..." +echo "Starting the first <%= ChefUtils::Dist::Infra::PRODUCT %> Client run..." <%= start_chef %> diff --git a/lib/chef/knife/bootstrap/templates/windows-chef-client-msi.erb b/lib/chef/knife/bootstrap/templates/windows-chef-client-msi.erb index 9699c09b0e..9c8f5972d4 100644 --- a/lib/chef/knife/bootstrap/templates/windows-chef-client-msi.erb +++ b/lib/chef/knife/bootstrap/templates/windows-chef-client-msi.erb @@ -109,13 +109,13 @@ goto Version10.0 goto chef_installed :chef_installed -@echo Checking for existing <%= Chef::Dist::PRODUCT %> installation -WHERE <%= Chef::Dist::CLIENT %> >nul 2>nul +@echo Checking for existing <%= ChefUtils::Dist::Infra::PRODUCT %> installation +WHERE <%= ChefUtils::Dist::Infra::CLIENT %> >nul 2>nul If !ERRORLEVEL!==0 ( - @echo Existing <%= Chef::Dist::PRODUCT %> installation detected, skipping download + @echo Existing <%= ChefUtils::Dist::Infra::PRODUCT %> installation detected, skipping download goto key_create ) else ( - @echo No existing installation of <%= Chef::Dist::PRODUCT %> detected + @echo No existing installation of <%= ChefUtils::Dist::Infra::PRODUCT %> detected goto install ) @@ -127,7 +127,7 @@ If !ERRORLEVEL!==0 ( @rem Install Chef using the MSI installer @set "LOCAL_DESTINATION_MSI_PATH=<%= local_download_path %>" - @set "CHEF_CLIENT_MSI_LOG_PATH=%TEMP%\<%= Chef::Dist::CLIENT %>-msi%RANDOM%.log" + @set "CHEF_CLIENT_MSI_LOG_PATH=%TEMP%\<%= ChefUtils::Dist::Infra::CLIENT %>-msi%RANDOM%.log" @rem Clear any pre-existing downloads @echo Checking for existing downloaded package at "%LOCAL_DESTINATION_MSI_PATH%" @@ -197,7 +197,7 @@ If !ERRORLEVEL!==0 ( <%= install_chef %> @if ERRORLEVEL 1 ( - echo <%= Chef::Dist::CLIENT %> package failed to install with status code !ERRORLEVEL!. > "&2" + echo <%= ChefUtils::Dist::Infra::CLIENT %> package failed to install with status code !ERRORLEVEL!. > "&2" echo See installation log for additional detail: %CHEF_CLIENT_MSI_LOG_PATH%. > "&2" ) else ( @echo Installation completed successfully @@ -274,5 +274,5 @@ echo Validation key written. <%= client_d %> <% end -%> -@echo Starting <%= Chef::Dist::CLIENT %> to bootstrap the node... +@echo Starting <%= ChefUtils::Dist::Infra::CLIENT %> to bootstrap the node... <%= start_chef %> diff --git a/lib/chef/knife/client_create.rb b/lib/chef/knife/client_create.rb index 9e9975ec0d..d6e0eab63b 100644 --- a/lib/chef/knife/client_create.rb +++ b/lib/chef/knife/client_create.rb @@ -17,7 +17,7 @@ # require_relative "../knife" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Knife @@ -30,7 +30,7 @@ class Chef option :file, short: "-f FILE", long: "--file FILE", - description: "Write the private key to a file if the #{Chef::Dist::SERVER_PRODUCT} generated one." + description: "Write the private key to a file if the #{ChefUtils::Dist::Server::PRODUCT} generated one." option :validator, long: "--validator", @@ -45,7 +45,7 @@ class Chef option :prevent_keygen, short: "-k", long: "--prevent-keygen", - description: "Prevent #{Chef::Dist::SERVER_PRODUCT} from generating a default key pair for you. Cannot be passed with --public-key.", + description: "Prevent #{ChefUtils::Dist::Server::PRODUCT} from generating a default key pair for you. Cannot be passed with --public-key.", boolean: true banner "knife client create CLIENTNAME (options)" diff --git a/lib/chef/knife/configure.rb b/lib/chef/knife/configure.rb index dc19e40d47..2a27fd5d88 100644 --- a/lib/chef/knife/configure.rb +++ b/lib/chef/knife/configure.rb @@ -17,7 +17,7 @@ # require_relative "../knife" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Knife @@ -119,7 +119,7 @@ class Chef if config[:initial] @new_client_name = config[:node_name] || ask_question("Please enter a name for the new user: ", default: Etc.getlogin) @admin_client_name = config[:admin_client_name] || ask_question("Please enter the existing admin name: ", default: "admin") - @admin_client_key = config[:admin_client_key] || ask_question("Please enter the location of the existing admin's private key: ", default: "#{Chef::Dist::SERVER_CONF_DIR}/admin.pem") + @admin_client_key = config[:admin_client_key] || ask_question("Please enter the location of the existing admin's private key: ", default: "#{ChefUtils::Dist::Server::CONF_DIR}/admin.pem") @admin_client_key = File.expand_path(@admin_client_key) else @new_client_name = config[:node_name] || ask_question("Please enter an existing username or clientname for the API: ", default: Etc.getlogin) diff --git a/lib/chef/knife/core/bootstrap_context.rb b/lib/chef/knife/core/bootstrap_context.rb index 12923f149a..9aa81da82f 100644 --- a/lib/chef/knife/core/bootstrap_context.rb +++ b/lib/chef/knife/core/bootstrap_context.rb @@ -19,7 +19,7 @@ require_relative "../../run_list" require_relative "../../util/path_helper" require "pathname" unless defined?(Pathname) -require_relative "../../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Knife @@ -184,7 +184,7 @@ class Chef def start_chef # If the user doesn't have a client path configure, let bash use the PATH for what it was designed for - client_path = chef_config[:chef_client_path] || Chef::Dist::CLIENT + client_path = chef_config[:chef_client_path] || ChefUtils::Dist::Infra::CLIENT s = "#{client_path} -j /etc/chef/first-boot.json" if config[:verbosity] && config[:verbosity] >= 3 s << " -l trace" diff --git a/lib/chef/knife/core/ui.rb b/lib/chef/knife/core/ui.rb index 0d467b69c8..0a7bb2f69d 100644 --- a/lib/chef/knife/core/ui.rb +++ b/lib/chef/knife/core/ui.rb @@ -70,7 +70,7 @@ class Chef # pastel.decorate is a lightweight replacement for highline.color def pastel @pastel ||= begin - require "pastel" + require "pastel" unless defined?(Pastel) Pastel.new end end diff --git a/lib/chef/knife/core/windows_bootstrap_context.rb b/lib/chef/knife/core/windows_bootstrap_context.rb index 7b4d517237..ae8d3f37eb 100644 --- a/lib/chef/knife/core/windows_bootstrap_context.rb +++ b/lib/chef/knife/core/windows_bootstrap_context.rb @@ -18,7 +18,7 @@ require_relative "bootstrap_context" require_relative "../../util/path_helper" -require_relative "../../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Knife @@ -175,7 +175,7 @@ class Chef bootstrap_environment_option = bootstrap_environment.nil? ? "" : " -E #{bootstrap_environment}" start_chef = "SET \"PATH=%SYSTEM32%;%SystemRoot%;%SYSTEM32%\\Wbem;%SYSTEM32%\\WindowsPowerShell\\v1.0\\;C:\\ruby\\bin;#{c_opscode_dir}\\bin;#{c_opscode_dir}\\embedded\\bin\;%PATH%\"\n" - start_chef << "#{Chef::Dist::CLIENT} -c #{client_rb} -j #{first_boot}#{bootstrap_environment_option}\n" + start_chef << "#{ChefUtils::Dist::Infra::CLIENT} -c #{client_rb} -j #{first_boot}#{bootstrap_environment_option}\n" end def win_wget @@ -288,7 +288,7 @@ class Chef end def local_download_path - "%TEMP%\\#{Chef::Dist::CLIENT}-latest.msi" + "%TEMP%\\#{ChefUtils::Dist::Infra::CLIENT}-latest.msi" end # Build a URL to query www.chef.io that will redirect to the correct @@ -365,7 +365,7 @@ class Chef <<~EOH @set MSIERRORCODE=!ERRORLEVEL! @if ERRORLEVEL 1 ( - @echo WARNING: Failed to install #{Chef::Dist::PRODUCT} MSI package in remote context with status code !MSIERRORCODE!. + @echo WARNING: Failed to install #{ChefUtils::Dist::Infra::PRODUCT} MSI package in remote context with status code !MSIERRORCODE!. @echo WARNING: This may be due to a defect in operating system update KB2918614: http://support.microsoft.com/kb/2918614 @set OLDLOGLOCATION="%CHEF_CLIENT_MSI_LOG_PATH%-fail.log" @move "%CHEF_CLIENT_MSI_LOG_PATH%" "!OLDLOGLOCATION!" > NUL @@ -374,26 +374,26 @@ class Chef @schtasks /create /f /sc once /st 00:00:00 /tn chefclientbootstraptask /ru SYSTEM /rl HIGHEST /tr \"cmd /c #{command} & sleep 2 & waitfor /s %computername% /si chefclientinstalldone\" @if ERRORLEVEL 1 ( - @echo ERROR: Failed to create #{Chef::Dist::PRODUCT} installation scheduled task with status code !ERRORLEVEL! > "&2" + @echo ERROR: Failed to create #{ChefUtils::Dist::Infra::PRODUCT} installation scheduled task with status code !ERRORLEVEL! > "&2" ) else ( - @echo Successfully created scheduled task to install #{Chef::Dist::PRODUCT}. + @echo Successfully created scheduled task to install #{ChefUtils::Dist::Infra::PRODUCT}. @schtasks /run /tn chefclientbootstraptask @if ERRORLEVEL 1 ( - @echo ERROR: Failed to execute #{Chef::Dist::PRODUCT} installation scheduled task with status code !ERRORLEVEL!. > "&2" + @echo ERROR: Failed to execute #{ChefUtils::Dist::Infra::PRODUCT} installation scheduled task with status code !ERRORLEVEL!. > "&2" ) else ( - @echo Successfully started #{Chef::Dist::PRODUCT} installation scheduled task. + @echo Successfully started #{ChefUtils::Dist::Infra::PRODUCT} installation scheduled task. @echo Waiting for installation to complete -- this may take a few minutes... waitfor chefclientinstalldone /t 600 if ERRORLEVEL 1 ( - @echo ERROR: Timed out waiting for #{Chef::Dist::PRODUCT} package to install + @echo ERROR: Timed out waiting for #{ChefUtils::Dist::Infra::PRODUCT} package to install ) else ( - @echo Finished waiting for #{Chef::Dist::PRODUCT} package to install. + @echo Finished waiting for #{ChefUtils::Dist::Infra::PRODUCT} package to install. ) @schtasks /delete /f /tn chefclientbootstraptask > NUL ) ) ) else ( - @echo Successfully installed #{Chef::Dist::PRODUCT} package. + @echo Successfully installed #{ChefUtils::Dist::Infra::PRODUCT} package. ) EOH end diff --git a/lib/chef/knife/exec.rb b/lib/chef/knife/exec.rb index 9286a91022..d3ce2cee24 100644 --- a/lib/chef/knife/exec.rb +++ b/lib/chef/knife/exec.rb @@ -17,7 +17,7 @@ # require_relative "../knife" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef::Knife::Exec < Chef::Knife @@ -30,7 +30,7 @@ class Chef::Knife::Exec < Chef::Knife option :exec, short: "-E CODE", long: "--exec CODE", - description: "A string of #{Chef::Dist::PRODUCT} code to execute." + description: "A string of #{ChefUtils::Dist::Infra::PRODUCT} code to execute." option :script_path, short: "-p PATH:PATH", diff --git a/lib/chef/knife/node_policy_set.rb b/lib/chef/knife/node_policy_set.rb index cfbae1ff6f..d34ebd9478 100644 --- a/lib/chef/knife/node_policy_set.rb +++ b/lib/chef/knife/node_policy_set.rb @@ -45,7 +45,7 @@ class Chef # Set policy name and group to node def set_policy(node) - policy_group, policy_name = @name_args[1..-1] + policy_group, policy_name = @name_args[1..] node.policy_name = policy_name node.policy_group = policy_group end @@ -70,7 +70,7 @@ class Chef # True if one of policy_name or policy_group was given, but not both def incomplete_policyfile_options? - policy_group, policy_name = @name_args[1..-1] + policy_group, policy_name = @name_args[1..] (policy_group.nil? || policy_name.nil? || @name_args[1..-1].size > 2) end diff --git a/lib/chef/knife/node_run_list_add.rb b/lib/chef/knife/node_run_list_add.rb index ac5f09bae9..40476371eb 100644 --- a/lib/chef/knife/node_run_list_add.rb +++ b/lib/chef/knife/node_run_list_add.rb @@ -43,7 +43,7 @@ class Chef node = Chef::Node.load(@name_args[0]) if @name_args.size > 2 # Check for nested lists and create a single plain one - entries = @name_args[1..-1].map do |entry| + entries = @name_args[1..].map do |entry| entry.split(",").map(&:strip) end.flatten else diff --git a/lib/chef/knife/node_run_list_remove.rb b/lib/chef/knife/node_run_list_remove.rb index 08f4e5d382..484e575475 100644 --- a/lib/chef/knife/node_run_list_remove.rb +++ b/lib/chef/knife/node_run_list_remove.rb @@ -34,7 +34,7 @@ class Chef if @name_args.size > 2 # Check for nested lists and create a single plain one - entries = @name_args[1..-1].map do |entry| + entries = @name_args[1..].map do |entry| entry.split(",").map(&:strip) end.flatten else diff --git a/lib/chef/knife/node_run_list_set.rb b/lib/chef/knife/node_run_list_set.rb index eae05003ff..f356b39d95 100644 --- a/lib/chef/knife/node_run_list_set.rb +++ b/lib/chef/knife/node_run_list_set.rb @@ -36,7 +36,7 @@ class Chef exit 1 elsif @name_args.size > 2 # Check for nested lists and create a single plain one - entries = @name_args[1..-1].map do |entry| + entries = @name_args[1..].map do |entry| entry.split(",").map(&:strip) end.flatten else diff --git a/lib/chef/knife/node_show.rb b/lib/chef/knife/node_show.rb index 801f0bbba9..8ef06d8938 100644 --- a/lib/chef/knife/node_show.rb +++ b/lib/chef/knife/node_show.rb @@ -18,7 +18,7 @@ require_relative "../knife" require_relative "core/node_presenter" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Knife @@ -42,7 +42,7 @@ class Chef option :environment, short: "-E", long: "--environment", - description: "Show only the #{Chef::Dist::PRODUCT} environment." + description: "Show only the #{ChefUtils::Dist::Infra::PRODUCT} environment." def run ui.use_presenter Knife::Core::NodePresenter diff --git a/lib/chef/knife/role_env_run_list_add.rb b/lib/chef/knife/role_env_run_list_add.rb index 1fc8ef1e74..b5753b46fc 100644 --- a/lib/chef/knife/role_env_run_list_add.rb +++ b/lib/chef/knife/role_env_run_list_add.rb @@ -68,7 +68,7 @@ class Chef if @name_args.size > 2 # Check for nested lists and create a single plain one - entries = @name_args[2..-1].map do |entry| + entries = @name_args[2..].map do |entry| entry.split(",").map(&:strip) end.flatten else diff --git a/lib/chef/knife/role_env_run_list_set.rb b/lib/chef/knife/role_env_run_list_set.rb index d9294b9bc4..0f1ce62a5d 100644 --- a/lib/chef/knife/role_env_run_list_set.rb +++ b/lib/chef/knife/role_env_run_list_set.rb @@ -51,7 +51,7 @@ class Chef exit 1 elsif @name_args.size > 2 # Check for nested lists and create a single plain one - entries = @name_args[2..-1].map do |entry| + entries = @name_args[2..].map do |entry| entry.split(",").map(&:strip) end.flatten else diff --git a/lib/chef/knife/role_run_list_add.rb b/lib/chef/knife/role_run_list_add.rb index 5ed91d5d49..76633ff5f6 100644 --- a/lib/chef/knife/role_run_list_add.rb +++ b/lib/chef/knife/role_run_list_add.rb @@ -68,7 +68,7 @@ class Chef if @name_args.size > 1 # Check for nested lists and create a single plain one - entries = @name_args[1..-1].map do |entry| + entries = @name_args[1..].map do |entry| entry.split(",").map(&:strip) end.flatten else diff --git a/lib/chef/knife/role_run_list_set.rb b/lib/chef/knife/role_run_list_set.rb index 7302797c33..ad1a5e2923 100644 --- a/lib/chef/knife/role_run_list_set.rb +++ b/lib/chef/knife/role_run_list_set.rb @@ -50,7 +50,7 @@ class Chef exit 1 elsif @name_args.size > 1 # Check for nested lists and create a single plain one - entries = @name_args[1..-1].map do |entry| + entries = @name_args[1..].map do |entry| entry.split(",").map(&:strip) end.flatten else diff --git a/lib/chef/knife/search.rb b/lib/chef/knife/search.rb index 9297a89686..2feb8e6729 100644 --- a/lib/chef/knife/search.rb +++ b/lib/chef/knife/search.rb @@ -26,7 +26,6 @@ class Chef include Knife::Core::MultiAttributeReturnOption deps do - require "addressable/uri" unless defined?(Addressable::URI) require_relative "../node" require_relative "../environment" require_relative "../api_client" diff --git a/lib/chef/knife/serve.rb b/lib/chef/knife/serve.rb index cce2ff6576..d79e05aa85 100644 --- a/lib/chef/knife/serve.rb +++ b/lib/chef/knife/serve.rb @@ -16,7 +16,7 @@ require_relative "../knife" require_relative "../local_mode" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Knife @@ -30,11 +30,11 @@ class Chef option :chef_repo_path, long: "--chef-repo-path PATH", - description: "Overrides the location of #{Chef::Dist::PRODUCT} repo. Default is specified by chef_repo_path in the config." + description: "Overrides the location of #{ChefUtils::Dist::Infra::PRODUCT} repo. Default is specified by chef_repo_path in the config." option :chef_zero_host, long: "--chef-zero-host IP", - description: "Overrides the host upon which #{Chef::Dist::ZERO} listens. Default is 127.0.0.1." + description: "Overrides the host upon which #{ChefUtils::Dist::Zero::PRODUCT} listens. Default is 127.0.0.1." def configure_chef super diff --git a/lib/chef/knife/ssh.rb b/lib/chef/knife/ssh.rb index a6428d9726..a586bf37c2 100644 --- a/lib/chef/knife/ssh.rb +++ b/lib/chef/knife/ssh.rb @@ -489,7 +489,7 @@ class Chef new_window_cmds = lambda do if session.servers_for.size > 1 - [""] + session.servers_for[1..-1].map do |server| + [""] + session.servers_for[1..].map do |server| if config[:tmux_split] "split-window #{ssh_dest.call(server)}; tmux select-layout tiled" else @@ -625,7 +625,7 @@ class Chef when "cssh" cssh else - ssh_command(@name_args[1..-1].join(" ")) + ssh_command(@name_args[1..].join(" ")) end session.close diff --git a/lib/chef/knife/ssl_check.rb b/lib/chef/knife/ssl_check.rb index 65e8694497..0cc4141d42 100644 --- a/lib/chef/knife/ssl_check.rb +++ b/lib/chef/knife/ssl_check.rb @@ -17,7 +17,7 @@ # require_relative "../knife" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Knife @@ -190,7 +190,7 @@ class Chef #{ui.color("TO FIX THIS ERROR:", :bold)} If the server you are connecting to uses a self-signed certificate, you must - configure #{Chef::Dist::PRODUCT} to trust that server's certificate. + configure #{ChefUtils::Dist::Infra::PRODUCT} to trust that server's certificate. By default, the certificate is stored in the following location on the host where your chef-server runs: @@ -234,7 +234,7 @@ class Chef end def debug_chef_ssl_config - ui.err "#{Chef::Dist::PRODUCT} SSL Configuration:" + ui.err "#{ChefUtils::Dist::Infra::PRODUCT} SSL Configuration:" ui.err "* ssl_ca_path: #{configuration.ssl_ca_path.inspect}" ui.err "* ssl_ca_file: #{configuration.ssl_ca_file.inspect}" ui.err "* trusted_certs_dir: #{configuration.trusted_certs_dir.inspect}" diff --git a/lib/chef/knife/status.rb b/lib/chef/knife/status.rb index 530cf791f7..ea5dffdf6c 100644 --- a/lib/chef/knife/status.rb +++ b/lib/chef/knife/status.rb @@ -19,7 +19,7 @@ require_relative "../knife" require_relative "core/status_presenter" require_relative "core/node_presenter" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Knife @@ -44,7 +44,7 @@ class Chef option :hide_by_mins, long: "--hide-by-mins MINS", - description: "Hide nodes that have run #{Chef::Dist::CLIENT} in the last MINS minutes" + description: "Hide nodes that have run #{ChefUtils::Dist::Infra::CLIENT} in the last MINS minutes" def append_to_query(term) @query << " AND " unless @query.empty? diff --git a/lib/chef/knife/tag_create.rb b/lib/chef/knife/tag_create.rb index fe357981b7..2f0d302e74 100644 --- a/lib/chef/knife/tag_create.rb +++ b/lib/chef/knife/tag_create.rb @@ -32,7 +32,7 @@ class Chef def run name = @name_args[0] - tags = @name_args[1..-1] + tags = @name_args[1..] if name.nil? || tags.nil? || tags.empty? show_usage diff --git a/lib/chef/knife/tag_delete.rb b/lib/chef/knife/tag_delete.rb index 1c9f2185d7..85fa6a9e27 100644 --- a/lib/chef/knife/tag_delete.rb +++ b/lib/chef/knife/tag_delete.rb @@ -32,7 +32,7 @@ class Chef def run name = @name_args[0] - tags = @name_args[1..-1] + tags = @name_args[1..] if name.nil? || tags.nil? || tags.empty? show_usage diff --git a/lib/chef/knife/user_create.rb b/lib/chef/knife/user_create.rb index 785020f5e3..6d68f3ebbb 100644 --- a/lib/chef/knife/user_create.rb +++ b/lib/chef/knife/user_create.rb @@ -18,7 +18,7 @@ # require_relative "../knife" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Knife @@ -42,7 +42,7 @@ class Chef option :prevent_keygen, short: "-k", long: "--prevent-keygen", - description: "API V1 (#{Chef::Dist::SERVER_PRODUCT} 12.1+) only. Prevent server from generating a default key pair for you. Cannot be passed with --user-key.", + description: "API V1 (#{ChefUtils::Dist::Server::PRODUCT} 12.1+) only. Prevent server from generating a default key pair for you. Cannot be passed with --user-key.", boolean: true banner "knife user create USERNAME DISPLAY_NAME FIRST_NAME LAST_NAME EMAIL PASSWORD (options)" diff --git a/lib/chef/local_mode.rb b/lib/chef/local_mode.rb index b7816cdc89..e7346322d2 100644 --- a/lib/chef/local_mode.rb +++ b/lib/chef/local_mode.rb @@ -15,9 +15,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +require "chef-utils" unless defined?(ChefUtils::CANARY) require_relative "config" require_relative "monkey_patches/webrick-utils" if ChefUtils.windows? -require_relative "dist" class Chef module LocalMode @@ -79,7 +79,7 @@ class Chef local_mode_url = @chef_zero_server.local_mode_url - Chef::Log.info("Started #{Chef::Dist::ZERO} at #{local_mode_url} with #{@chef_fs.fs_description}") + Chef::Log.info("Started #{ChefUtils::Dist::Zero::PRODUCT} at #{local_mode_url} with #{@chef_fs.fs_description}") Chef::Config.chef_server_url = local_mode_url end end diff --git a/lib/chef/log/syslog.rb b/lib/chef/log/syslog.rb index 28c5bf8799..4e6a6dd0b5 100644 --- a/lib/chef/log/syslog.rb +++ b/lib/chef/log/syslog.rb @@ -19,7 +19,7 @@ require "logger" require "syslog-logger" require_relative "../mixin/unformatter" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Log @@ -33,7 +33,7 @@ class Chef attr_accessor :sync, :formatter - def initialize(program_name = Chef::Dist::CLIENT, facility = ::Syslog::LOG_DAEMON, logopts = nil) + def initialize(program_name = ChefUtils::Dist::Infra::CLIENT, facility = ::Syslog::LOG_DAEMON, logopts = nil) super return if defined? ::Logger::Syslog::SYSLOG diff --git a/lib/chef/log/winevt.rb b/lib/chef/log/winevt.rb index 6aff6cccec..f060ecfde6 100644 --- a/lib/chef/log/winevt.rb +++ b/lib/chef/log/winevt.rb @@ -19,7 +19,7 @@ require_relative "../event_loggers/base" require_relative "../platform/query_helpers" require_relative "../mixin/unformatter" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Log @@ -37,7 +37,7 @@ class Chef FATAL_EVENT_ID = 10104 # Since we must install the event logger, this is not really configurable - SOURCE = Chef::Dist::SHORT.freeze + SOURCE = ChefUtils::Dist::Infra::SHORT.freeze include Chef::Mixin::Unformatter diff --git a/lib/chef/mixin/template.rb b/lib/chef/mixin/template.rb index a369cae9e5..dcb728f964 100644 --- a/lib/chef/mixin/template.rb +++ b/lib/chef/mixin/template.rb @@ -204,7 +204,7 @@ class Chef all_ivars.delete(:@_extension_modules) all_ivars.inject({}) do |ivar_map, ivar_symbol_name| value = instance_variable_get(ivar_symbol_name) - name_without_at = ivar_symbol_name.to_s[1..-1].to_sym + name_without_at = ivar_symbol_name.to_s[1..].to_sym ivar_map[name_without_at] = value ivar_map end diff --git a/lib/chef/mixin/uris.rb b/lib/chef/mixin/uris.rb index 74c2af73d8..13c4ee29b3 100644 --- a/lib/chef/mixin/uris.rb +++ b/lib/chef/mixin/uris.rb @@ -17,7 +17,9 @@ # autoload :URI, "uri" -autoload :Addressable, "addressable/uri" +module Addressable + autoload :URI, "addressable/uri" +end class Chef module Mixin diff --git a/lib/chef/mixin/versioned_api.rb b/lib/chef/mixin/versioned_api.rb index eab2ea8228..b627e0210c 100644 --- a/lib/chef/mixin/versioned_api.rb +++ b/lib/chef/mixin/versioned_api.rb @@ -50,8 +50,7 @@ class Chef # in which case we'll just start with the highest version and see what happens ServerAPIVersions.instance.min_server_version.nil? || (version >= ServerAPIVersions.instance.min_server_version && version <= ServerAPIVersions.instance.send(type)) end - .sort { |a, b| a.send(:minimum_api_version) <=> b.send(:minimum_api_version) } - .last + .max_by { |a| a.send(:minimum_api_version) } end def def_versioned_delegator(method) diff --git a/lib/chef/node_map.rb b/lib/chef/node_map.rb index 30a0ed6c4e..0b85dbe9df 100644 --- a/lib/chef/node_map.rb +++ b/lib/chef/node_map.rb @@ -36,7 +36,7 @@ # XXX: confusingly, in the *_priority_map the :klass may be an array of Strings of class names # -require_relative "dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class NodeMap @@ -86,7 +86,7 @@ class Chef else klass.superclass.to_s end - Chef::Log.warn( COLLISION_WARNING % { type: type_of_thing, key: key, type_caps: type_of_thing.capitalize, client_name: Chef::Dist::PRODUCT } ) + Chef::Log.warn( COLLISION_WARNING % { type: type_of_thing, key: key, type_caps: type_of_thing.capitalize, client_name: ChefUtils::Dist::Infra::PRODUCT } ) end # The map is sorted in order of preference already; we just need to find @@ -225,13 +225,13 @@ class Chef if attribute == :platform_family # If any blocklist value matches, we don't match - return false if blocklist.any? { |v| v[1..-1] == value || platform_family_query_helper?(node, v[1..-1]) } + return false if blocklist.any? { |v| v[1..] == value || platform_family_query_helper?(node, v[1..]) } # If the allowlist is empty, or anything matches, we match. allowlist.empty? || allowlist.any? { |v| v == :all || v == value || platform_family_query_helper?(node, v) } else # If any blocklist value matches, we don't match - return false if blocklist.any? { |v| v[1..-1] == value } + return false if blocklist.any? { |v| v[1..] == value } # If the allowlist is empty, or anything matches, we match. allowlist.empty? || allowlist.any? { |v| v == :all || v == value } diff --git a/lib/chef/policy_builder/dynamic.rb b/lib/chef/policy_builder/dynamic.rb index 7971379d2c..3d9d4c0b7d 100644 --- a/lib/chef/policy_builder/dynamic.rb +++ b/lib/chef/policy_builder/dynamic.rb @@ -23,6 +23,8 @@ require_relative "../run_context" require_relative "../config" require_relative "../node" require_relative "../exceptions" +require_relative "expand_node_object" +require_relative "policyfile" class Chef module PolicyBuilder diff --git a/lib/chef/policy_builder/policyfile.rb b/lib/chef/policy_builder/policyfile.rb index 0055f9d4b6..bac015be42 100644 --- a/lib/chef/policy_builder/policyfile.rb +++ b/lib/chef/policy_builder/policyfile.rb @@ -24,7 +24,7 @@ require_relative "../run_context" require_relative "../config" require_relative "../node" require_relative "../server_api" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef module PolicyBuilder @@ -91,7 +91,7 @@ class Chef @node = nil if Chef::Config[:solo_legacy_mode] - raise UnsupportedFeature, "Policyfile does not support chef-solo. Use #{Chef::Dist::CLIENT} local mode instead." + raise UnsupportedFeature, "Policyfile does not support chef-solo. Use #{ChefUtils::Dist::Infra::CLIENT} local mode instead." end if override_runlist diff --git a/lib/chef/provider.rb b/lib/chef/provider.rb index 60b89a8094..4d5631397b 100644 --- a/lib/chef/provider.rb +++ b/lib/chef/provider.rb @@ -88,7 +88,7 @@ class Chef def self.use(partial) dirname = ::File.dirname(partial) basename = ::File.basename(partial, ".rb") - basename = basename[1..-1] if basename.start_with?("_") + basename = basename[1..] if basename.start_with?("_") class_eval IO.read(::File.expand_path("#{dirname}/_#{basename}.rb", ::File.dirname(caller_locations.first.absolute_path))) end diff --git a/lib/chef/provider/file.rb b/lib/chef/provider/file.rb index 0de620bba1..e2c07ad9f7 100644 --- a/lib/chef/provider/file.rb +++ b/lib/chef/provider/file.rb @@ -31,7 +31,7 @@ require_relative "../util/backup" require_relative "../util/diff" require_relative "../util/selinux" require_relative "../file_content_management/deploy" -require_relative "../dist" +require "chef-utils" unless defined?(ChefUtils::CANARY) # The Tao of File Providers: # - the content provider must always return a tempfile that we can delete/mv @@ -394,7 +394,7 @@ class Chef return if tempfile.nil? # but a tempfile that has no path or doesn't exist should not happen if tempfile.path.nil? || !::File.exists?(tempfile.path) - raise "#{Chef::Dist::CLIENT} is confused, trying to deploy a file that has no path or does not exist..." + raise "#{ChefUtils::Dist::Infra::CLIENT} is confused, trying to deploy a file that has no path or does not exist..." end # the file? on the next line suppresses the case in why-run when we have a not-file here that would have otherwise been removed diff --git a/lib/chef/provider/launchd.rb b/lib/chef/provider/launchd.rb index 37c73924f8..1045d4294f 100644 --- a/lib/chef/provider/launchd.rb +++ b/lib/chef/provider/launchd.rb @@ -209,7 +209,7 @@ class Chef # @api private def path - @path ||= new_resource.path ? new_resource.path : gen_path_from_type + @path ||= new_resource.path || gen_path_from_type end end end diff --git a/lib/chef/provider/link.rb b/lib/chef/provider/link.rb index 1615d3ad14..900d0516af 100644 --- a/lib/chef/provider/link.rb +++ b/lib/chef/provider/link.rb @@ -33,15 +33,6 @@ class Chef include Chef::Mixin::EnforceOwnershipAndPermissions include Chef::Mixin::FileClass - def negative_complement(big) - if big > 1073741823 # Fixnum max - big -= (2**32) # diminished radix wrap to negative - end - big - end - - private :negative_complement - def load_current_resource @current_resource = Chef::Resource::Link.new(new_resource.name) current_resource.target_file(new_resource.target_file) diff --git a/lib/chef/provider/package/dpkg.rb b/lib/chef/provider/package/dpkg.rb index 08829e9b26..b2d1678caa 100644 --- a/lib/chef/provider/package/dpkg.rb +++ b/lib/chef/provider/package/dpkg.rb @@ -164,10 +164,7 @@ class Chef # # @return [Hash] Mapping of package names to sources def name_sources - @name_sources = - begin - Hash[*package_name_array.zip(resolved_source_array).flatten] - end + @name_sources ||= Hash[*package_name_array.zip(resolved_source_array).flatten] end # Helper to construct Hash of names-to-package-information. @@ -186,17 +183,11 @@ class Chef end def name_candidate_version - @name_candidate_version ||= - begin - Hash[name_pkginfo.map { |k, v| [k, v ? v.split("\t")[1].strip : nil] }] - end + @name_candidate_version ||= name_pkginfo.transform_values { |v| v ? v.split("\t")[1]&.strip : nil } end def name_package_name - @name_package_name ||= - begin - Hash[name_pkginfo.map { |k, v| [k, v ? v.split("\t")[0] : nil] }] - end + @name_package_name ||= name_pkginfo.transform_values { |v| v ? v.split("\t")[0] : nil } end # Return candidate version array from pkg-deb -W against the source file(s). diff --git a/lib/chef/provider/package/homebrew.rb b/lib/chef/provider/package/homebrew.rb index d61a0314c0..2b60c0a1ec 100644 --- a/lib/chef/provider/package/homebrew.rb +++ b/lib/chef/provider/package/homebrew.rb @@ -127,7 +127,7 @@ class Chef # check each item in the hash to see if we were passed an alias brew_info.each_value do |p| - return p if p["aliases"].include?(package_name) + return p if p["full_name"] == package_name || p["aliases"].include?(package_name) end {} diff --git a/lib/chef/provider/package/rubygems.rb b/lib/chef/provider/package/rubygems.rb index f9e89ead02..8aba495c4c 100644 --- a/lib/chef/provider/package/rubygems.rb +++ b/lib/chef/provider/package/rubygems.rb @@ -22,7 +22,7 @@ require_relative "../package" require_relative "../../resource/package" require_relative "../../mixin/get_source_from_package" require_relative "../../mixin/which" -require_relative "../../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) # Class methods on Gem are defined in rubygems autoload :Gem, "rubygems" @@ -404,8 +404,8 @@ class Chef if new_resource.options && new_resource.options.is_a?(Hash) msg = [ "Gem options must be passed to gem_package as a string instead of a hash when", - "using this installation of #{Chef::Dist::PRODUCT} because it runs with its own packaged Ruby. A hash", - "may only be used when installing a gem to the same Ruby installation that #{Chef::Dist::PRODUCT} is", + "using this installation of #{ChefUtils::Dist::Infra::PRODUCT} because it runs with its own packaged Ruby. A hash", + "may only be used when installing a gem to the same Ruby installation that #{ChefUtils::Dist::Infra::PRODUCT} is", "running under. See https://docs.chef.io/resources/gem_package/ for more information.", "Error raised at #{new_resource} from #{new_resource.source_line}", ].join("\n") diff --git a/lib/chef/provider/package/zypper.rb b/lib/chef/provider/package/zypper.rb index 1096dcd044..da6bf0efbf 100644 --- a/lib/chef/provider/package/zypper.rb +++ b/lib/chef/provider/package/zypper.rb @@ -158,7 +158,7 @@ class Chef end def global_options - new_resource.global_options if new_resource.global_options + new_resource.global_options end end end diff --git a/lib/chef/provider/route.rb b/lib/chef/provider/route.rb index 3eac41aef0..8a304a7e45 100644 --- a/lib/chef/provider/route.rb +++ b/lib/chef/provider/route.rb @@ -169,11 +169,7 @@ class Chef next unless resource.is_a? Chef::Resource::Route # default to eth0 - dev = if resource.device - resource.device - else - "eth0" - end + dev = resource.device || "eth0" conf[dev] = "" if conf[dev].nil? case @action diff --git a/lib/chef/provider/service/macosx.rb b/lib/chef/provider/service/macosx.rb index ae04c7bfdd..2152789a6e 100644 --- a/lib/chef/provider/service/macosx.rb +++ b/lib/chef/provider/service/macosx.rb @@ -47,7 +47,7 @@ class Chef @current_resource = Chef::Resource::MacosxService.new(@new_resource.name) @current_resource.service_name(@new_resource.service_name) @plist_size = 0 - @plist = @new_resource.plist ? @new_resource.plist : find_service_plist + @plist = @new_resource.plist || find_service_plist @service_label = find_service_label # LaunchAgents should be loaded as the console user. @console_user = @plist ? @plist.include?("LaunchAgents") : false diff --git a/lib/chef/provider/service/redhat.rb b/lib/chef/provider/service/redhat.rb index 3ef7110002..14b55bef85 100644 --- a/lib/chef/provider/service/redhat.rb +++ b/lib/chef/provider/service/redhat.rb @@ -84,7 +84,7 @@ class Chef chkconfig = shell_out!("/sbin/chkconfig --list #{current_resource.service_name}", returns: [0, 1]) unless run_levels.nil? || run_levels.empty? all_levels_match = true - chkconfig.stdout.split(/\s+/)[1..-1].each do |level| + chkconfig.stdout.split(/\s+/)[1..].each do |level| index = level.split(":").first status = level.split(":").last if CHKCONFIG_ON.match?(level) diff --git a/lib/chef/provider/template_finder.rb b/lib/chef/provider/template_finder.rb index fdc5eaeda9..fa120a1624 100644 --- a/lib/chef/provider/template_finder.rb +++ b/lib/chef/provider/template_finder.rb @@ -43,19 +43,11 @@ class Chef protected def template_source_name(name, options) - if options[:source] - options[:source] - else - name - end + options[:source] || name end def find_cookbook_name(options) - if options[:cookbook] - options[:cookbook] - else - @cookbook_name - end + options[:cookbook] || @cookbook_name end end end diff --git a/lib/chef/provider/user/dscl.rb b/lib/chef/provider/user/dscl.rb index 2a7300c017..7b266b8d62 100644 --- a/lib/chef/provider/user/dscl.rb +++ b/lib/chef/provider/user/dscl.rb @@ -584,7 +584,7 @@ in 'password', with the associated 'salt' and 'iterations'.") # def run_dscl(*args) - result = shell_out("dscl", ".", "-#{args[0]}", args[1..-1]) + result = shell_out("dscl", ".", "-#{args[0]}", args[1..]) return "" if ( args.first =~ /^delete/ ) && ( result.exitstatus != 0 ) raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") unless result.exitstatus == 0 raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") if result.stdout.include?("No such key: ") @@ -593,7 +593,7 @@ in 'password', with the associated 'salt' and 'iterations'.") end def run_plutil(*args) - result = shell_out("plutil", "-#{args[0]}", args[1..-1]) + result = shell_out("plutil", "-#{args[0]}", args[1..]) raise(Chef::Exceptions::PlistUtilCommandFailed, "plutil error: #{result.inspect}") unless result.exitstatus == 0 if result.stdout.encoding == Encoding::ASCII_8BIT diff --git a/lib/chef/provider/user/mac.rb b/lib/chef/provider/user/mac.rb index a738fa4aa0..a3980aa12f 100644 --- a/lib/chef/provider/user/mac.rb +++ b/lib/chef/provider/user/mac.rb @@ -608,7 +608,7 @@ class Chef end def run_dscl(*args) - result = shell_out("dscl", "-plist", ".", "-#{args[0]}", args[1..-1]) + result = shell_out("dscl", "-plist", ".", "-#{args[0]}", args[1..]) return "" if ( args.first =~ /^delete/ ) && ( result.exitstatus != 0 ) raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") unless result.exitstatus == 0 raise(Chef::Exceptions::DsclCommandFailed, "dscl error: #{result.inspect}") if /No such key: /.match?(result.stdout) @@ -617,7 +617,7 @@ class Chef end def run_plutil(*args) - result = shell_out("plutil", "-#{args[0]}", args[1..-1]) + result = shell_out("plutil", "-#{args[0]}", args[1..]) raise(Chef::Exceptions::PlistUtilCommandFailed, "plutil error: #{result.inspect}") unless result.exitstatus == 0 result.stdout diff --git a/lib/chef/provider/zypper_repository.rb b/lib/chef/provider/zypper_repository.rb index 6427a27746..53dae74948 100644 --- a/lib/chef/provider/zypper_repository.rb +++ b/lib/chef/provider/zypper_repository.rb @@ -20,7 +20,7 @@ require_relative "../resource" require_relative "../dsl/declare_resource" require_relative "noop" require "shellwords" unless defined?(Shellwords) -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Provider @@ -110,7 +110,7 @@ class Chef logger.trace("Will use :cookbook_file resource to cache the gpg key locally") :cookbook_file else - raise Chef::Exceptions::FileNotFound, "Cannot determine location of gpgkey. Must start with 'http' or be a file managed by #{Chef::Dist::PRODUCT}." + raise Chef::Exceptions::FileNotFound, "Cannot determine location of gpgkey. Must start with 'http' or be a file managed by #{ChefUtils::Dist::Infra::PRODUCT}." end end diff --git a/lib/chef/provider_resolver.rb b/lib/chef/provider_resolver.rb index b0dd0d9376..94727a1043 100644 --- a/lib/chef/provider_resolver.rb +++ b/lib/chef/provider_resolver.rb @@ -113,7 +113,7 @@ class Chef # if resource.provider is set, just return one of those objects def maybe_explicit_provider(resource) - resource.provider if resource.provider + resource.provider end # try dynamically finding a provider based on querying the providers to see what they support diff --git a/lib/chef/recipe.rb b/lib/chef/recipe.rb index 4009677936..972edf9649 100644 --- a/lib/chef/recipe.rb +++ b/lib/chef/recipe.rb @@ -122,7 +122,7 @@ class Chef end def to_s - "cookbook: #{cookbook_name ? cookbook_name : "(none)"}, recipe: #{recipe_name ? recipe_name : "(none)"} " + "cookbook: #{cookbook_name || "(none)"}, recipe: #{recipe_name || "(none)"} " end def inspect diff --git a/lib/chef/resource.rb b/lib/chef/resource.rb index 2e5b17f277..e572f0667d 100644 --- a/lib/chef/resource.rb +++ b/lib/chef/resource.rb @@ -1480,7 +1480,7 @@ class Chef def self.use(partial) dirname = ::File.dirname(partial) basename = ::File.basename(partial, ".rb") - basename = basename[1..-1] if basename.start_with?("_") + basename = basename[1..] if basename.start_with?("_") class_eval IO.read(::File.expand_path("#{dirname}/_#{basename}.rb", ::File.dirname(caller_locations.first.absolute_path))) end diff --git a/lib/chef/resource/apt_repository.rb b/lib/chef/resource/apt_repository.rb index e4569561fc..68f416df4c 100644 --- a/lib/chef/resource/apt_repository.rb +++ b/lib/chef/resource/apt_repository.rb @@ -19,7 +19,9 @@ require_relative "../resource" require_relative "../http/simple" require "tmpdir" unless defined?(Dir.mktmpdir) -autoload :Addressable, "addressable" +module Addressable + autoload :URI, "addressable/uri" +end class Chef class Resource @@ -168,7 +170,7 @@ class Chef # is the provided ID a key ID from a keyserver. Looks at length and HEX only values # @param [String] id the key value passed by the user that *may* be an ID def is_key_id?(id) - id = id[2..-1] if id.start_with?("0x") + id = id[2..] if id.start_with?("0x") id =~ /^\h+$/ && [8, 16, 40].include?(id.length) end diff --git a/lib/chef/resource/bff_package.rb b/lib/chef/resource/bff_package.rb index d0b67d081b..ffe5dfac1b 100644 --- a/lib/chef/resource/bff_package.rb +++ b/lib/chef/resource/bff_package.rb @@ -17,6 +17,7 @@ # require_relative "package" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -27,6 +28,27 @@ class Chef description "Use the **bff_package** resource to manage packages for the AIX platform using the installp utility. When a package is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources." introduced "12.0" + examples <<~DOC + The **bff_package** resource is the default package provider on the AIX platform. The base **package** resource may be used, and then when the platform is AIX, #{ChefUtils::Dist::Infra::PRODUCT} will identify the correct package provider. The following examples show how to install part of the IBM XL C/C++ compiler. + + **Installing using the base package resource** + + ```ruby + package 'xlccmp.13.1.0' do + source '/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0' + action :install + end + ``` + + **Installing using the bff_package resource** + + ```ruby + bff_package 'xlccmp.13.1.0' do + source '/var/tmp/IBM_XL_C_13.1.0/usr/sys/inst.images/xlccmp.13.1.0' + action :install + end + ``` + DOC property :package_name, String, description: "An optional property to set the package name if it differs from the resource block's name.", diff --git a/lib/chef/resource/breakpoint.rb b/lib/chef/resource/breakpoint.rb index d1e6bbf179..d73a82a6e8 100644 --- a/lib/chef/resource/breakpoint.rb +++ b/lib/chef/resource/breakpoint.rb @@ -17,7 +17,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -26,8 +26,63 @@ class Chef provides :breakpoint, target_mode: true - description "Use the **breakpoint** resource to add breakpoints to recipes. Run the #{Chef::Dist::SHELL} in #{Chef::Dist::PRODUCT} mode, and then use those breakpoints to debug recipes. Breakpoints are ignored by the #{Chef::Dist::CLIENT} during an actual #{Chef::Dist::CLIENT} run. That said, breakpoints are typically used to debug recipes only when running them in a non-production environment, after which they are removed from those recipes before the parent cookbook is uploaded to the Chef server." + description "Use the **breakpoint** resource to add breakpoints to recipes. Run the #{ChefUtils::Dist::Infra::SHELL} in #{ChefUtils::Dist::Infra::PRODUCT} mode, and then use those breakpoints to debug recipes. Breakpoints are ignored by the #{ChefUtils::Dist::Infra::CLIENT} during an actual #{ChefUtils::Dist::Infra::CLIENT} run. That said, breakpoints are typically used to debug recipes only when running them in a non-production environment, after which they are removed from those recipes before the parent cookbook is uploaded to the Chef server." introduced "12.0" + examples <<~DOC + **A recipe without a breakpoint** + + ```ruby + yum_key node['yum']['elrepo']['key'] do + url node['yum']['elrepo']['key_url'] + action :add + end + + yum_repository 'elrepo' do + description 'ELRepo.org Community Enterprise Linux Extras Repository' + key node['yum']['elrepo']['key'] + mirrorlist node['yum']['elrepo']['url'] + includepkgs node['yum']['elrepo']['includepkgs'] + exclude node['yum']['elrepo']['exclude'] + action :create + end + ``` + + **The same recipe with breakpoints** + + ```ruby + breakpoint "before yum_key node['yum']['repo_name']['key']" do + action :break + end + + yum_key node['yum']['repo_name']['key'] do + url node['yum']['repo_name']['key_url'] + action :add + end + + breakpoint "after yum_key node['yum']['repo_name']['key']" do + action :break + end + + breakpoint "before yum_repository 'repo_name'" do + action :break + end + + yum_repository 'repo_name' do + description 'description' + key node['yum']['repo_name']['key'] + mirrorlist node['yum']['repo_name']['url'] + includepkgs node['yum']['repo_name']['includepkgs'] + exclude node['yum']['repo_name']['exclude'] + action :create + end + + breakpoint "after yum_repository 'repo_name'" do + action :break + end + ``` + + where the name of each breakpoint is an arbitrary string. In the previous examples, the names are used to indicate if the breakpoint is before or after a resource, and then also to specify which resource. + DOC default_action :break diff --git a/lib/chef/resource/cab_package.rb b/lib/chef/resource/cab_package.rb index 374eac56a4..904fe81701 100644 --- a/lib/chef/resource/cab_package.rb +++ b/lib/chef/resource/cab_package.rb @@ -29,6 +29,35 @@ class Chef description "Use the **cab_package** resource to install or remove Microsoft Windows cabinet (.cab) packages." introduced "12.15" + examples <<~'DOC' + **Using local path in source** + + ```ruby + cab_package 'Install .NET 3.5 sp1 via KB958488' do + source 'C:\Users\xyz\AppData\Local\Temp\Windows6.1-KB958488-x64.cab' + action :install + end + + cab_package 'Remove .NET 3.5 sp1 via KB958488' do + source 'C:\Users\xyz\AppData\Local\Temp\Windows6.1-KB958488-x64.cab' + action :remove + end + ``` + + **Using URL in source** + + ```ruby + cab_package 'Install .NET 3.5 sp1 via KB958488' do + source 'https://s3.amazonaws.com/my_bucket/Windows6.1-KB958488-x64.cab' + action :install + end + + cab_package 'Remove .NET 3.5 sp1 via KB958488' do + source 'https://s3.amazonaws.com/my_bucket/Temp\Windows6.1-KB958488-x64.cab' + action :remove + end + ``` + DOC allowed_actions :install, :remove diff --git a/lib/chef/resource/chef_client_cron.rb b/lib/chef/resource/chef_client_cron.rb index ab435c39f8..4dc1e1e5ad 100644 --- a/lib/chef/resource/chef_client_cron.rb +++ b/lib/chef/resource/chef_client_cron.rb @@ -15,7 +15,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) require_relative "helpers/cron_validations" require "digest/md5" unless defined?(Digest::MD5) @@ -26,25 +26,25 @@ class Chef provides :chef_client_cron - description "Use the **chef_client_cron** resource to setup the #{Chef::Dist::PRODUCT} to run as a cron job. This resource will also create the specified log directory if it doesn't already exist." + description "Use the **chef_client_cron** resource to setup the #{ChefUtils::Dist::Infra::PRODUCT} to run as a cron job. This resource will also create the specified log directory if it doesn't already exist." introduced "16.0" examples <<~DOC - **Setup #{Chef::Dist::PRODUCT} to run using the default 30 minute cadence**: + **Setup #{ChefUtils::Dist::Infra::PRODUCT} to run using the default 30 minute cadence**: ```ruby - chef_client_cron "Run #{Chef::Dist::PRODUCT} as a cron job" + chef_client_cron "Run #{ChefUtils::Dist::Infra::PRODUCT} as a cron job" ``` - **Run #{Chef::Dist::PRODUCT} twice a day**: + **Run #{ChefUtils::Dist::Infra::PRODUCT} twice a day**: ```ruby - chef_client_cron "Run #{Chef::Dist::PRODUCT} every 12 hours" do + chef_client_cron "Run #{ChefUtils::Dist::Infra::PRODUCT} every 12 hours" do minute 0 hour "0,12" end ``` - **Run #{Chef::Dist::PRODUCT} with extra options passed to the client**: + **Run #{ChefUtils::Dist::Infra::PRODUCT} with extra options passed to the client**: ```ruby chef_client_cron "Run an override recipe" do @@ -56,42 +56,42 @@ class Chef extend Chef::ResourceHelpers::CronValidations property :job_name, String, - default: Chef::Dist::CLIENT, + default: ChefUtils::Dist::Infra::CLIENT, description: "The name of the cron job to create." property :comment, String, description: "A comment to place in the cron.d file." property :user, String, - description: "The name of the user that #{Chef::Dist::PRODUCT} runs as.", + description: "The name of the user that #{ChefUtils::Dist::Infra::PRODUCT} runs as.", default: "root" property :minute, [Integer, String], - description: "The minute at which #{Chef::Dist::PRODUCT} is to run (0 - 59) or a cron pattern such as '0,30'.", + description: "The minute at which #{ChefUtils::Dist::Infra::PRODUCT} is to run (0 - 59) or a cron pattern such as '0,30'.", default: "0,30", callbacks: { "should be a valid minute spec" => method(:validate_minute), } property :hour, [Integer, String], - description: "The hour at which #{Chef::Dist::PRODUCT} is to run (0 - 23) or a cron pattern such as '0,12'.", + description: "The hour at which #{ChefUtils::Dist::Infra::PRODUCT} is to run (0 - 23) or a cron pattern such as '0,12'.", default: "*", callbacks: { "should be a valid hour spec" => method(:validate_hour), } property :day, [Integer, String], - description: "The day of month at which #{Chef::Dist::PRODUCT} is to run (1 - 31) or a cron pattern such as '1,7,14,21,28'.", + description: "The day of month at which #{ChefUtils::Dist::Infra::PRODUCT} is to run (1 - 31) or a cron pattern such as '1,7,14,21,28'.", default: "*", callbacks: { "should be a valid day spec" => method(:validate_day), } property :month, [Integer, String], - description: "The month in the year on which #{Chef::Dist::PRODUCT} is to run (1 - 12, jan-dec, or *).", + description: "The month in the year on which #{ChefUtils::Dist::Infra::PRODUCT} is to run (1 - 12, jan-dec, or *).", default: "*", callbacks: { "should be a valid month spec" => method(:validate_month), } property :weekday, [Integer, String], - description: "The day of the week on which #{Chef::Dist::PRODUCT} is to run (0-7, mon-sun, or *), where Sunday is both 0 and 7.", + description: "The day of the week on which #{ChefUtils::Dist::Infra::PRODUCT} is to run (0-7, mon-sun, or *), where Sunday is both 0 and 7.", default: "*", callbacks: { "should be a valid weekday spec" => method(:validate_dow), } @@ -100,7 +100,7 @@ class Chef default: 300, coerce: proc { |x| Integer(x) }, callbacks: { "should be a positive number" => proc { |v| v > 0 } }, - description: "A random number of seconds between 0 and X to add to interval so that all #{Chef::Dist::CLIENT} commands don't execute at the same time." + description: "A random number of seconds between 0 and X to add to interval so that all #{ChefUtils::Dist::Infra::CLIENT} commands don't execute at the same time." property :mailto, String, description: "The e-mail address to e-mail any cron task failures to." @@ -110,12 +110,12 @@ class Chef default: false property :config_directory, String, - default: Chef::Dist::CONF_DIR, + default: ChefConfig::Config.etc_chef_dir, description: "The path of the config directory." property :log_directory, String, - default: lazy { platform?("mac_os_x") ? "/Library/Logs/#{Chef::Dist::DIR_SUFFIX.capitalize}" : "/var/log/#{Chef::Dist::DIR_SUFFIX}" }, - default_description: "/Library/Logs/#{Chef::Dist::DIR_SUFFIX.capitalize} on macOS and /var/log/#{Chef::Dist::DIR_SUFFIX} otherwise", + default: lazy { platform?("mac_os_x") ? "/Library/Logs/#{ChefUtils::Dist::Infra::DIR_SUFFIX.capitalize}" : "/var/log/#{ChefUtils::Dist::Infra::DIR_SUFFIX}" }, + default_description: "/Library/Logs/#{ChefUtils::Dist::Infra::DIR_SUFFIX.capitalize} on macOS and /var/log/#{ChefUtils::Dist::Infra::DIR_SUFFIX} otherwise", description: "The path of the directory to create the log file in." property :log_file_name, String, @@ -127,19 +127,19 @@ class Chef description: "Append to the log file instead of overwriting the log file on each run." property :chef_binary_path, String, - default: "/opt/#{Chef::Dist::DIR_SUFFIX}/bin/#{Chef::Dist::CLIENT}", - description: "The path to the #{Chef::Dist::CLIENT} binary." + default: "/opt/#{ChefUtils::Dist::Infra::DIR_SUFFIX}/bin/#{ChefUtils::Dist::Infra::CLIENT}", + description: "The path to the #{ChefUtils::Dist::Infra::CLIENT} binary." property :daemon_options, Array, default: lazy { [] }, - description: "An array of options to pass to the #{Chef::Dist::CLIENT} command." + description: "An array of options to pass to the #{ChefUtils::Dist::Infra::CLIENT} command." property :environment, Hash, default: lazy { {} }, description: "A Hash containing additional arbitrary environment variables under which the cron job will be run in the form of `({'ENV_VARIABLE' => 'VALUE'})`." property :nice, [Integer, String], - description: "The process priority to run the #{Chef::Dist::CLIENT} process at. A value of -20 is the highest priority and 19 is the lowest priority.", + description: "The process priority to run the #{ChefUtils::Dist::Infra::CLIENT} process at. A value of -20 is the highest priority and 19 is the lowest priority.", introduced: "16.5", coerce: proc { |x| Integer(x) }, callbacks: { "should be an Integer between -20 and 19" => proc { |v| v >= -20 && v <= 19 } } @@ -202,7 +202,7 @@ class Chef cmd << "-c #{::File.join(new_resource.config_directory, "client.rb")} " cmd << "--chef-license accept " if new_resource.accept_chef_license cmd << log_command - cmd << " || echo \"#{Chef::Dist::PRODUCT} execution failed\"" if new_resource.mailto + cmd << " || echo \"#{ChefUtils::Dist::Infra::PRODUCT} execution failed\"" if new_resource.mailto cmd end diff --git a/lib/chef/resource/chef_client_launchd.rb b/lib/chef/resource/chef_client_launchd.rb index c33fa05876..0e173050d0 100644 --- a/lib/chef/resource/chef_client_launchd.rb +++ b/lib/chef/resource/chef_client_launchd.rb @@ -15,7 +15,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource class ChefClientLaunchd < Chef::Resource @@ -23,37 +23,37 @@ class Chef provides :chef_client_launchd - description "Use the **chef_client_launchd** resource to configure the #{Chef::Dist::PRODUCT} to run on a schedule." + description "Use the **chef_client_launchd** resource to configure the #{ChefUtils::Dist::Infra::PRODUCT} to run on a schedule." introduced "16.5" examples <<~DOC - **Set the #{Chef::Dist::PRODUCT} to run on a schedule**: + **Set the #{ChefUtils::Dist::Infra::PRODUCT} to run on a schedule**: ```ruby - chef_client_launchd 'Setup the #{Chef::Dist::PRODUCT} to run every 30 minutes' do + chef_client_launchd 'Setup the #{ChefUtils::Dist::Infra::PRODUCT} to run every 30 minutes' do interval 30 action :enable end ``` - **Disable the #{Chef::Dist::PRODUCT} running on a schedule**: + **Disable the #{ChefUtils::Dist::Infra::PRODUCT} running on a schedule**: ```ruby - chef_client_launchd 'Prevent the #{Chef::Dist::PRODUCT} from running on a schedule' do + chef_client_launchd 'Prevent the #{ChefUtils::Dist::Infra::PRODUCT} from running on a schedule' do action :disable end ``` DOC property :user, String, - description: "The name of the user that #{Chef::Dist::PRODUCT} runs as.", + description: "The name of the user that #{ChefUtils::Dist::Infra::PRODUCT} runs as.", default: "root" property :working_directory, String, - description: "The working directory to run the #{Chef::Dist::PRODUCT} from.", + description: "The working directory to run the #{ChefUtils::Dist::Infra::PRODUCT} from.", default: "/var/root" property :interval, [Integer, String], - description: "Time in minutes between #{Chef::Dist::PRODUCT} executions.", + description: "Time in minutes between #{ChefUtils::Dist::Infra::PRODUCT} executions.", coerce: proc { |x| Integer(x) }, callbacks: { "should be a positive number" => proc { |v| v > 0 } }, default: 30 @@ -62,7 +62,7 @@ class Chef default: 300, coerce: proc { |x| Integer(x) }, callbacks: { "should be a positive number" => proc { |v| v > 0 } }, - description: "A random number of seconds between 0 and X to add to interval so that all #{Chef::Dist::CLIENT} commands don't execute at the same time." + description: "A random number of seconds between 0 and X to add to interval so that all #{ChefUtils::Dist::Infra::CLIENT} commands don't execute at the same time." property :accept_chef_license, [true, false], description: "Accept the Chef Online Master License and Services Agreement. See <https://www.chef.io/online-master-agreement/>", @@ -70,7 +70,7 @@ class Chef property :config_directory, String, description: "The path of the config directory.", - default: Chef::Dist::CONF_DIR + default: ChefConfig::Config.etc_chef_dir property :log_directory, String, description: "The path of the directory to create the log file in.", @@ -81,11 +81,11 @@ class Chef default: "client.log" property :chef_binary_path, String, - description: "The path to the #{Chef::Dist::CLIENT} binary.", - default: "/opt/#{Chef::Dist::DIR_SUFFIX}/bin/#{Chef::Dist::CLIENT}" + description: "The path to the #{ChefUtils::Dist::Infra::CLIENT} binary.", + default: "/opt/#{ChefUtils::Dist::Infra::DIR_SUFFIX}/bin/#{ChefUtils::Dist::Infra::CLIENT}" property :daemon_options, Array, - description: "An array of options to pass to the #{Chef::Dist::CLIENT} command.", + description: "An array of options to pass to the #{ChefUtils::Dist::Infra::CLIENT} command.", default: lazy { [] } property :environment, Hash, @@ -93,12 +93,12 @@ class Chef default: lazy { {} } property :nice, [Integer, String], - description: "The process priority to run the #{Chef::Dist::CLIENT} process at. A value of -20 is the highest priority and 19 is the lowest priority.", + description: "The process priority to run the #{ChefUtils::Dist::Infra::CLIENT} process at. A value of -20 is the highest priority and 19 is the lowest priority.", coerce: proc { |x| Integer(x) }, callbacks: { "should be an Integer between -20 and 19" => proc { |v| v >= -20 && v <= 19 } } property :low_priority_io, [true, false], - description: "Run the #{Chef::Dist::CLIENT} process with low priority disk IO", + description: "Run the #{ChefUtils::Dist::Infra::CLIENT} process with low priority disk IO", default: true action :enable do @@ -110,7 +110,7 @@ class Chef end end - launchd "com.#{Chef::Dist::SHORT}.#{Chef::Dist::CLIENT}" do + launchd "com.#{ChefUtils::Dist::Infra::SHORT}.#{ChefUtils::Dist::Infra::CLIENT}" do username new_resource.user working_directory new_resource.working_directory start_interval new_resource.interval * 60 @@ -127,14 +127,14 @@ class Chef # to restart itself. If the chef-client process uses launchd or macosx_service resources to restart itself # we'll end up with a stopped service that will never get started back up. Instead we use this daemon # that triggers when the chef-client plist file is updated, and handles the restart outside the run. - launchd "com.#{Chef::Dist::SHORT}.restarter" do + launchd "com.#{ChefUtils::Dist::Infra::SHORT}.restarter" do username "root" - watch_paths ["/Library/LaunchDaemons/com.#{Chef::Dist::SHORT}.#{Chef::Dist::CLIENT}.plist"] + watch_paths ["/Library/LaunchDaemons/com.#{ChefUtils::Dist::Infra::SHORT}.#{ChefUtils::Dist::Infra::CLIENT}.plist"] standard_out_path ::File.join(new_resource.log_directory, new_resource.log_file_name) standard_error_path ::File.join(new_resource.log_directory, new_resource.log_file_name) program_arguments ["/bin/bash", "-c", - "echo; echo #{Chef::Dist::PRODUCT} launchd daemon config has been updated. Manually unloading and reloading the daemon; echo Now unloading the daemon; launchctl unload /Library/LaunchDaemons/com.#{Chef::Dist::SHORT}.#{Chef::Dist::CLIENT}.plist; sleep 2; echo Now loading the daemon; launchctl load /Library/LaunchDaemons/com.#{Chef::Dist::SHORT}.#{Chef::Dist::CLIENT}.plist"] + "echo; echo #{ChefUtils::Dist::Infra::PRODUCT} launchd daemon config has been updated. Manually unloading and reloading the daemon; echo Now unloading the daemon; launchctl unload /Library/LaunchDaemons/com.#{ChefUtils::Dist::Infra::SHORT}.#{ChefUtils::Dist::Infra::CLIENT}.plist; sleep 2; echo Now loading the daemon; launchctl load /Library/LaunchDaemons/com.#{ChefUtils::Dist::Infra::SHORT}.#{ChefUtils::Dist::Infra::CLIENT}.plist"] action :enable # enable creates the plist & triggers service restarts on change end @@ -149,12 +149,12 @@ class Chef end action :disable do - service Chef::Dist::PRODUCT do - service_name "com.#{Chef::Dist::SHORT}.#{Chef::Dist::CLIENT}" + service ChefUtils::Dist::Infra::PRODUCT do + service_name "com.#{ChefUtils::Dist::Infra::SHORT}.#{ChefUtils::Dist::Infra::CLIENT}" action :disable end - service "com.#{Chef::Dist::SHORT}.restarter" do + service "com.#{ChefUtils::Dist::Infra::SHORT}.restarter" do action :disable end end @@ -191,4 +191,4 @@ class Chef end end end -end
\ No newline at end of file +end diff --git a/lib/chef/resource/chef_client_scheduled_task.rb b/lib/chef/resource/chef_client_scheduled_task.rb index 7fde581763..617d452b1d 100644 --- a/lib/chef/resource/chef_client_scheduled_task.rb +++ b/lib/chef/resource/chef_client_scheduled_task.rb @@ -15,7 +15,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -24,24 +24,24 @@ class Chef provides :chef_client_scheduled_task - description "Use the **chef_client_scheduled_task** resource to setup the #{Chef::Dist::PRODUCT} to run as a Windows scheduled task. This resource will also create the specified log directory if it doesn't already exist." + description "Use the **chef_client_scheduled_task** resource to setup the #{ChefUtils::Dist::Infra::PRODUCT} to run as a Windows scheduled task. This resource will also create the specified log directory if it doesn't already exist." introduced "16.0" examples <<~DOC - **Setup #{Chef::Dist::PRODUCT} to run using the default 30 minute cadence**: + **Setup #{ChefUtils::Dist::Infra::PRODUCT} to run using the default 30 minute cadence**: ```ruby - chef_client_scheduled_task "Run #{Chef::Dist::PRODUCT} as a scheduled task" + chef_client_scheduled_task "Run #{ChefUtils::Dist::Infra::PRODUCT} as a scheduled task" ``` - **Run #{Chef::Dist::PRODUCT} on system start**: + **Run #{ChefUtils::Dist::Infra::PRODUCT} on system start**: ```ruby - chef_client_scheduled_task '#{Chef::Dist::PRODUCT} on start' do + chef_client_scheduled_task '#{ChefUtils::Dist::Infra::PRODUCT} on start' do frequency 'onstart' end ``` - **Run #{Chef::Dist::PRODUCT} with extra options passed to the client**: + **Run #{ChefUtils::Dist::Infra::PRODUCT} with extra options passed to the client**: ```ruby chef_client_scheduled_task "Run an override recipe" do @@ -49,7 +49,7 @@ class Chef end ``` - **Run #{Chef::Dist::PRODUCT} daily at 01:00 am, specifying a named run-list**: + **Run #{ChefUtils::Dist::Infra::PRODUCT} daily at 01:00 am, specifying a named run-list**: ```ruby chef_client_scheduled_task "Run chef-client named run-list daily" do @@ -64,14 +64,14 @@ class Chef property :task_name, String, description: "The name of the scheduled task to create.", - default: Chef::Dist::CLIENT + default: ChefUtils::Dist::Infra::CLIENT property :user, String, - description: "The name of the user that #{Chef::Dist::PRODUCT} runs as.", + description: "The name of the user that #{ChefUtils::Dist::Infra::PRODUCT} runs as.", default: "System", sensitive: true property :password, String, - description: "The password for the user that #{Chef::Dist::PRODUCT} runs as.", + description: "The password for the user that #{ChefUtils::Dist::Infra::PRODUCT} runs as.", sensitive: true property :frequency, String, @@ -101,16 +101,16 @@ class Chef property :splay, [Integer, String], coerce: proc { |x| Integer(x) }, callbacks: { "should be a positive number" => proc { |v| v > 0 } }, - description: "A random number of seconds between 0 and X to add to interval so that all #{Chef::Dist::CLIENT} commands don't execute at the same time.", + description: "A random number of seconds between 0 and X to add to interval so that all #{ChefUtils::Dist::Infra::CLIENT} commands don't execute at the same time.", default: 300 property :run_on_battery, [true, false], - description: "Run the #{Chef::Dist::PRODUCT} task when the system is on batteries.", + description: "Run the #{ChefUtils::Dist::Infra::PRODUCT} task when the system is on batteries.", default: true property :config_directory, String, description: "The path of the config directory.", - default: Chef::Dist::CONF_DIR + default: ChefConfig::Config.etc_chef_dir property :log_directory, String, description: "The path of the directory to create the log file in.", @@ -122,11 +122,11 @@ class Chef default: "client.log" property :chef_binary_path, String, - description: "The path to the #{Chef::Dist::CLIENT} binary.", - default: "C:/#{Chef::Dist::LEGACY_CONF_DIR}/#{Chef::Dist::DIR_SUFFIX}/bin/#{Chef::Dist::CLIENT}" + description: "The path to the #{ChefUtils::Dist::Infra::CLIENT} binary.", + default: "C:/#{ChefUtils::Dist::Org::LEGACY_CONF_DIR}/#{ChefUtils::Dist::Infra::DIR_SUFFIX}/bin/#{ChefUtils::Dist::Infra::CLIENT}" property :daemon_options, Array, - description: "An array of options to pass to the #{Chef::Dist::CLIENT} command.", + description: "An array of options to pass to the #{ChefUtils::Dist::Infra::CLIENT} command.", default: lazy { [] } action :add do diff --git a/lib/chef/resource/chef_client_systemd_timer.rb b/lib/chef/resource/chef_client_systemd_timer.rb index 71e05e9499..ce250ea68d 100644 --- a/lib/chef/resource/chef_client_systemd_timer.rb +++ b/lib/chef/resource/chef_client_systemd_timer.rb @@ -15,7 +15,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -24,24 +24,24 @@ class Chef provides :chef_client_systemd_timer - description "Use the **chef_client_systemd_timer** resource to setup the #{Chef::Dist::PRODUCT} to run as a systemd timer." + description "Use the **chef_client_systemd_timer** resource to setup the #{ChefUtils::Dist::Infra::PRODUCT} to run as a systemd timer." introduced "16.0" examples <<~DOC - **Setup #{Chef::Dist::PRODUCT} to run using the default 30 minute cadence**: + **Setup #{ChefUtils::Dist::Infra::PRODUCT} to run using the default 30 minute cadence**: ```ruby - chef_client_systemd_timer "Run #{Chef::Dist::PRODUCT} as a systemd timer" + chef_client_systemd_timer "Run #{ChefUtils::Dist::Infra::PRODUCT} as a systemd timer" ``` - **Run #{Chef::Dist::PRODUCT} every 1 hour**: + **Run #{ChefUtils::Dist::Infra::PRODUCT} every 1 hour**: ```ruby - chef_client_systemd_timer "Run #{Chef::Dist::PRODUCT} every 1 hour" do + chef_client_systemd_timer "Run #{ChefUtils::Dist::Infra::PRODUCT} every 1 hour" do interval "1hr" end ``` - **Run #{Chef::Dist::PRODUCT} with extra options passed to the client**: + **Run #{ChefUtils::Dist::Infra::PRODUCT} with extra options passed to the client**: ```ruby chef_client_systemd_timer "Run an override recipe" do @@ -52,14 +52,14 @@ class Chef property :job_name, String, description: "The name of the system timer to create.", - default: Chef::Dist::CLIENT + default: ChefUtils::Dist::Infra::CLIENT property :description, String, description: "The description to add to the systemd timer. This will be displayed when running `systemctl status` for the timer.", - default: "#{Chef::Dist::PRODUCT} periodic execution" + default: "#{ChefUtils::Dist::Infra::PRODUCT} periodic execution" property :user, String, - description: "The name of the user that #{Chef::Dist::PRODUCT} runs as.", + description: "The name of the user that #{ChefUtils::Dist::Infra::PRODUCT} runs as.", default: "root" property :delay_after_boot, String, @@ -71,7 +71,7 @@ class Chef default: "30min" property :splay, String, - description: "A interval between 0 and X to add to the interval so that all #{Chef::Dist::CLIENT} commands don't execute at the same time. This is expressed as a systemd time span such as `300seconds`, `1hr`, or `1m`. See <https://www.freedesktop.org/software/systemd/man/systemd.time.html> for a complete list of allowed time span values.", + description: "A interval between 0 and X to add to the interval so that all #{ChefUtils::Dist::Infra::CLIENT} commands don't execute at the same time. This is expressed as a systemd time span such as `300seconds`, `1hr`, or `1m`. See <https://www.freedesktop.org/software/systemd/man/systemd.time.html> for a complete list of allowed time span values.", default: "5min" property :accept_chef_license, [true, false], @@ -79,19 +79,19 @@ class Chef default: false property :run_on_battery, [true, false], - description: "Run the timer for #{Chef::Dist::PRODUCT} if the system is on battery.", + description: "Run the timer for #{ChefUtils::Dist::Infra::PRODUCT} if the system is on battery.", default: true property :config_directory, String, description: "The path of the config directory.", - default: Chef::Dist::CONF_DIR + default: ChefConfig::Config.etc_chef_dir property :chef_binary_path, String, - description: "The path to the #{Chef::Dist::CLIENT} binary.", - default: "/opt/#{Chef::Dist::DIR_SUFFIX}/bin/#{Chef::Dist::CLIENT}" + description: "The path to the #{ChefUtils::Dist::Infra::CLIENT} binary.", + default: "/opt/#{ChefUtils::Dist::Infra::DIR_SUFFIX}/bin/#{ChefUtils::Dist::Infra::CLIENT}" property :daemon_options, Array, - description: "An array of options to pass to the #{Chef::Dist::CLIENT} command.", + description: "An array of options to pass to the #{ChefUtils::Dist::Infra::CLIENT} command.", default: lazy { [] } property :environment, Hash, @@ -99,7 +99,7 @@ class Chef default: lazy { {} } property :cpu_quota, [Integer, String], - description: "The systemd CPUQuota to run the #{Chef::Dist::CLIENT} process with. This is a percentage value of the total CPU time available on the system. If the system has more than 1 core this may be a value greater than 100.", + description: "The systemd CPUQuota to run the #{ChefUtils::Dist::Infra::CLIENT} process with. This is a percentage value of the total CPU time available on the system. If the system has more than 1 core this may be a value greater than 100.", introduced: "16.5", coerce: proc { |x| Integer(x) }, callbacks: { "should be a positive Integer" => proc { |v| v > 0 } } diff --git a/lib/chef/resource/chef_client_trusted_certificate.rb b/lib/chef/resource/chef_client_trusted_certificate.rb index 855407b12a..b5272fbe01 100644 --- a/lib/chef/resource/chef_client_trusted_certificate.rb +++ b/lib/chef/resource/chef_client_trusted_certificate.rb @@ -15,7 +15,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -24,7 +24,7 @@ class Chef provides :chef_client_trusted_certificate - description "Use the **chef_client_trusted_certificate** resource to add certificates to #{Chef::Dist::PRODUCT}'s trusted certificate directory. This allows the #{Chef::Dist::PRODUCT} to communicate with internal encrypted resources without errors." + description "Use the **chef_client_trusted_certificate** resource to add certificates to #{ChefUtils::Dist::Infra::PRODUCT}'s trusted certificate directory. This allows the #{ChefUtils::Dist::Infra::PRODUCT} to communicate with internal encrypted resources without errors." introduced "16.5" examples <<~DOC **Trust a self signed certificate**: @@ -98,4 +98,4 @@ class Chef end end end -end
\ No newline at end of file +end diff --git a/lib/chef/resource/chef_gem.rb b/lib/chef/resource/chef_gem.rb index b44f9e1771..fc23555cbd 100644 --- a/lib/chef/resource/chef_gem.rb +++ b/lib/chef/resource/chef_gem.rb @@ -18,7 +18,7 @@ require_relative "package" require_relative "gem_package" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -27,27 +27,27 @@ class Chef provides :chef_gem description <<~DESC - Use the **chef_gem** resource to install a gem only for the instance of Ruby that is dedicated to the #{Chef::Dist::CLIENT}. + Use the **chef_gem** resource to install a gem only for the instance of Ruby that is dedicated to the #{ChefUtils::Dist::Infra::CLIENT}. When a gem is installed from a local file, it must be added to the node using the **remote_file** or **cookbook_file** resources. The **chef_gem** resource works with all of the same properties and options as the **gem_package** resource, but does not - accept the `gem_binary` property because it always uses the `CurrentGemEnvironment` under which the `#{Chef::Dist::CLIENT}` is + accept the `gem_binary` property because it always uses the `CurrentGemEnvironment` under which the `#{ChefUtils::Dist::Infra::CLIENT}` is running. In addition to performing actions similar to the **gem_package** resource, the **chef_gem** resource does the following: - Runs its actions immediately, before convergence, allowing a gem to be used in a recipe immediately after it is installed. - Runs `Gem.clear_paths` after the action, ensuring that gem is aware of changes so that it can be required immediately after it is installed. - Warning: The **chef_gem** and **gem_package** resources are both used to install Ruby gems. For any machine on which #{Chef::Dist::PRODUCT} is + Warning: The **chef_gem** and **gem_package** resources are both used to install Ruby gems. For any machine on which #{ChefUtils::Dist::Infra::PRODUCT} is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is - available only to #{Chef::Dist::PRODUCT}. - Use the **chef_gem** resource to install gems into the instance of Ruby that is dedicated to #{Chef::Dist::PRODUCT}. + available only to #{ChefUtils::Dist::Infra::PRODUCT}. + Use the **chef_gem** resource to install gems into the instance of Ruby that is dedicated to #{ChefUtils::Dist::Infra::PRODUCT}. Use the **gem_package** resource to install all other gems (i.e. install gems system-wide). DESC examples <<~EXAMPLES **Compile time vs. converge time installation of gems** - To install a gem while #{Chef::Dist::PRODUCT} is configuring the node (the converge phase), set the `compile_time` property to `false`: + To install a gem while #{ChefUtils::Dist::Infra::PRODUCT} is configuring the node (the converge phase), set the `compile_time` property to `false`: ```ruby chef_gem 'right_aws' do compile_time false @@ -63,7 +63,7 @@ class Chef end ``` - Install MySQL for Chef + **Install MySQL gem into #{ChefUtils::Dist::Infra::PRODUCT}*** ```ruby apt_update @@ -84,8 +84,8 @@ class Chef property :gem_binary, String, default: "#{RbConfig::CONFIG["bindir"]}/gem", - default_description: "The `gem` binary included with #{Chef::Dist::PRODUCT}.", - description: "The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by #{Chef::Dist::PRODUCT} will be used.", + default_description: "The `gem` binary included with #{ChefUtils::Dist::Infra::PRODUCT}.", + description: "The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by #{ChefUtils::Dist::Infra::PRODUCT} will be used.", callbacks: { "The `chef_gem` resource is restricted to the current gem environment, use `gem_package` to install to other environments." => proc { |v| v == "#{RbConfig::CONFIG["bindir"]}/gem" }, diff --git a/lib/chef/resource/chef_handler.rb b/lib/chef/resource/chef_handler.rb index f2daab3d6e..a006b2648a 100644 --- a/lib/chef/resource/chef_handler.rb +++ b/lib/chef/resource/chef_handler.rb @@ -16,7 +16,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -25,8 +25,153 @@ class Chef provides(:chef_handler) { true } - description "Use the **chef_handler** resource to install or uninstall reporting/exception handlers." + description "Use the **chef_handler** resource to enable handlers during a #{ChefUtils::Dist::Infra::PRODUCT} run. The resource allows arguments to be passed to #{ChefUtils::Dist::Infra::PRODUCT}, which then applies the conditions defined by the custom handler to the node attribute data collected during a #{ChefUtils::Dist::Infra::PRODUCT} run, and then processes the handler based on that data.\nThe **chef_handler** resource is typically defined early in a node's run-list (often being the first item). This ensures that all of the handlers will be available for the entire #{ChefUtils::Dist::Infra::PRODUCT} run." introduced "14.0" + examples <<~'DOC' + **Enable the 'MyHandler' handler** + + The following example shows how to enable a fictional 'MyHandler' handler which is located on disk at `/etc/chef/my_handler.rb`. The handler will be configured to run with Chef Infra Client and will be passed values to the handler's initializer method: + + ```ruby + chef_handler 'MyHandler' do + source '/etc/chef/my_handler.rb' # the file should already be at this path + arguments path: '/var/chef/reports' + action :enable + end + ``` + + **Enable handlers during the compile phase** + + ```ruby + chef_handler 'Chef::Handler::JsonFile' do + source 'chef/handler/json_file' + arguments path: '/var/chef/reports' + action :enable + compile_time true + end + ``` + + **Handle only exceptions** + + ```ruby + chef_handler 'Chef::Handler::JsonFile' do + source 'chef/handler/json_file' + arguments path: '/var/chef/reports' + type exception: true + action :enable + end + ``` + + **Cookbook Versions (a custom handler)** + + [@juliandunn](https://github.com/juliandunn) created a custom report handler that logs all of the cookbooks and cookbook versions that were used during a Chef Infra Client run, and then reports after the run is complete. + + cookbook_versions.rb: + + The following custom handler defines how cookbooks and cookbook versions that are used during a Chef Infra Client run will be compiled into a report using the `Chef::Log` class in Chef Infra Client: + + ```ruby + require 'chef/log' + + module Chef + class CookbookVersionsHandler < Chef::Handler + def report + cookbooks = run_context.cookbook_collection + Chef::Log.info('Cookbooks and versions run: #{cookbooks.map {|x| x.name.to_s + ' ' + x.version }}') + end + end + end + ``` + + default.rb: + + The following recipe is added to the run-list for every node on which a list of cookbooks and versions will be generated as report output after every Chef Infra Client run. + + ```ruby + cookbook_file '/etc/chef/cookbook_versions.rb' do + source 'cookbook_versions.rb' + action :create + end + + chef_handler 'Chef::CookbookVersionsHandler' do + source '/etc/chef/cookbook_versions.rb' + type report: true + action :enable + end + ``` + + This recipe will generate report output similar to the following: + + ``` + [2013-11-26T03:11:06+00:00] INFO: Chef Infra Client Run complete in 0.300029878 seconds + [2013-11-26T03:11:06+00:00] INFO: Running report handlers + [2013-11-26T03:11:06+00:00] INFO: Cookbooks and versions run: ["cookbook_versions_handler 1.0.0"] + [2013-11-26T03:11:06+00:00] INFO: Report handlers complete + ``` + + **JsonFile Handler** + + The JsonFile handler is available from the `chef_handler` cookbook and can be used with exceptions and reports. It serializes run status data to a JSON file. This handler may be enabled in one of the following ways. + + By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how Chef Infra Client is being run: + + ```ruby + require 'chef/handler/json_file' + report_handlers << Chef::Handler::JsonFile.new(path: '/var/chef/reports') + exception_handlers << Chef::Handler::JsonFile.new(path: '/var/chef/reports') + ``` + + By using the `chef_handler` resource in a recipe, similar to the following: + + ```ruby + chef_handler 'Chef::Handler::JsonFile' do + source 'chef/handler/json_file' + arguments path: '/var/chef/reports' + action :enable + end + ``` + + After it has run, the run status data can be loaded and inspected via Interactive Ruby (IRb): + + ``` + irb(main):002:0> require 'json' => true + irb(main):003:0> require 'chef' => true + irb(main):004:0> r = JSON.parse(IO.read('/var/chef/reports/chef-run-report-20110322060731.json')) => ... output truncated + irb(main):005:0> r.keys => ['end_time', 'node', 'updated_resources', 'exception', 'all_resources', 'success', 'elapsed_time', 'start_time', 'backtrace'] + irb(main):006:0> r['elapsed_time'] => 0.00246 + ``` + + Register the JsonFile handler + + ```ruby + chef_handler 'Chef::Handler::JsonFile' do + source 'chef/handler/json_file' + arguments path: '/var/chef/reports' + action :enable + end + ``` + + **ErrorReport Handler** + + The ErrorReport handler is built into Chef Infra Client and can be used for both exceptions and reports. It serializes error report data to a JSON file. This handler may be enabled in one of the following ways. + + By adding the following lines of Ruby code to either the client.rb file or the solo.rb file, depending on how Chef Infra Client is being run: + + ```ruby + require 'chef/handler/error_report' + report_handlers << Chef::Handler::ErrorReport.new + exception_handlers << Chef::Handler::ErrorReport.new + ``` + + By using the `chef_handler` resource in a recipe, similar to the following: + + ```ruby + chef_handler 'Chef::Handler::ErrorReport' do + source 'chef/handler/error_report' + action :enable + end + ``` + DOC property :class_name, String, description: "The name of the handler class. This can be module name-spaced.", @@ -50,7 +195,7 @@ class Chef # This action needs to find an rb file that presumably contains the indicated class in it and the # load that file. It then instantiates that class by name and registers it as a handler. action :enable do - description "Enables the handler for the current #{Chef::Dist::PRODUCT} run on the current node" + description "Enables the handler for the current #{ChefUtils::Dist::Infra::PRODUCT} run on the current node" class_name = new_resource.class_name new_resource.type.each do |type, enable| @@ -74,7 +219,7 @@ class Chef end action :disable do - description "Disables the handler for the current #{Chef::Dist::PRODUCT} run on the current node" + description "Disables the handler for the current #{ChefUtils::Dist::Infra::PRODUCT} run on the current node" new_resource.type.each_key do |type| unregister_handler(type, new_resource.class_name) diff --git a/lib/chef/resource/chef_sleep.rb b/lib/chef/resource/chef_sleep.rb index 828ce07bc9..219fac83a3 100644 --- a/lib/chef/resource/chef_sleep.rb +++ b/lib/chef/resource/chef_sleep.rb @@ -15,7 +15,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -24,7 +24,7 @@ class Chef unified_mode true - description "Use the **chef_sleep** resource to pause (sleep) for a number of seconds during a #{Chef::Dist::PRODUCT} run. Only use this resource when a command or service exits successfully but is not ready for the next step in a recipe." + description "Use the **chef_sleep** resource to pause (sleep) for a number of seconds during a #{ChefUtils::Dist::Infra::PRODUCT} run. Only use this resource when a command or service exits successfully but is not ready for the next step in a recipe." introduced "15.5" examples <<~DOC **Sleep for 10 seconds**: diff --git a/lib/chef/resource/cookbook_file.rb b/lib/chef/resource/cookbook_file.rb index 5981aab194..f1ae195426 100644 --- a/lib/chef/resource/cookbook_file.rb +++ b/lib/chef/resource/cookbook_file.rb @@ -21,7 +21,7 @@ require_relative "file" require_relative "../provider/cookbook_file" require_relative "../mixin/securable" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -31,7 +31,7 @@ class Chef provides :cookbook_file - description "Use the **cookbook_file** resource to transfer files from a sub-directory of COOKBOOK_NAME/files/ to a specified path located on a host that is running the #{Chef::Dist::PRODUCT}. The file is selected according to file specificity, which allows different source files to be used based on the hostname, host platform (operating system, distro, or as appropriate), or platform version. Files that are located in the COOKBOOK_NAME/files/default sub-directory may be used on any platform.\n\nDuring a #{Chef::Dist::PRODUCT} run, the checksum for each local file is calculated and then compared against the checksum for the same file as it currently exists in the cookbook on the #{Chef::Dist::SERVER_PRODUCT}. A file is not transferred when the checksums match. Only files that require an update are transferred from the #{Chef::Dist::SERVER_PRODUCT} to a node." + description "Use the **cookbook_file** resource to transfer files from a sub-directory of COOKBOOK_NAME/files/ to a specified path located on a host that is running the #{ChefUtils::Dist::Infra::PRODUCT}. The file is selected according to file specificity, which allows different source files to be used based on the hostname, host platform (operating system, distro, or as appropriate), or platform version. Files that are located in the COOKBOOK_NAME/files/default sub-directory may be used on any platform.\n\nDuring a #{ChefUtils::Dist::Infra::PRODUCT} run, the checksum for each local file is calculated and then compared against the checksum for the same file as it currently exists in the cookbook on the #{ChefUtils::Dist::Server::PRODUCT}. A file is not transferred when the checksums match. Only files that require an update are transferred from the #{ChefUtils::Dist::Server::PRODUCT} to a node." property :source, [ String, Array ], description: "The name of the file in COOKBOOK_NAME/files/default or the path to a file located in COOKBOOK_NAME/files. The path must include the file name and its extension. This can be used to distribute specific files depending upon the platform used.", diff --git a/lib/chef/resource/cron/_cron_shared.rb b/lib/chef/resource/cron/_cron_shared.rb index 2f6a116a05..6d11035862 100644 --- a/lib/chef/resource/cron/_cron_shared.rb +++ b/lib/chef/resource/cron/_cron_shared.rb @@ -89,6 +89,7 @@ property :time_out, Hash, } private + # Convert weekday input value into crontab format that # could be written in the crontab # @return [Integer, String] A weekday formed as per the user inputs. diff --git a/lib/chef/resource/cron/cron_d.rb b/lib/chef/resource/cron/cron_d.rb index 882544a8bc..8276fb8587 100644 --- a/lib/chef/resource/cron/cron_d.rb +++ b/lib/chef/resource/cron/cron_d.rb @@ -18,7 +18,6 @@ require_relative "../../resource" require_relative "../helpers/cron_validations" require "shellwords" unless defined?(Shellwords) -require_relative "../../dist" class Chef class Resource diff --git a/lib/chef/resource/dnf_package.rb b/lib/chef/resource/dnf_package.rb index b2401c797d..80727de7d0 100644 --- a/lib/chef/resource/dnf_package.rb +++ b/lib/chef/resource/dnf_package.rb @@ -18,7 +18,7 @@ require_relative "package" require_relative "../mixin/which" require_relative "../mixin/shell_out" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -52,7 +52,7 @@ class Chef # Flush the in-memory available/installed cache, this does not flush the dnf caches on disk property :flush_cache, Hash, - description: "Flush the in-memory cache before or after a DNF operation that installs, upgrades, or removes a package. DNF automatically synchronizes remote metadata to a local cache. The #{Chef::Dist::CLIENT} creates a copy of the local cache, and then stores it in-memory during the #{Chef::Dist::CLIENT} run. The in-memory cache allows packages to be installed during the #{Chef::Dist::CLIENT} run without the need to continue synchronizing the remote metadata to the local cache while the #{Chef::Dist::CLIENT} run is in-progress.", + description: "Flush the in-memory cache before or after a DNF operation that installs, upgrades, or removes a package. DNF automatically synchronizes remote metadata to a local cache. The #{ChefUtils::Dist::Infra::CLIENT} creates a copy of the local cache, and then stores it in-memory during the #{ChefUtils::Dist::Infra::CLIENT} run. The in-memory cache allows packages to be installed during the #{ChefUtils::Dist::Infra::CLIENT} run without the need to continue synchronizing the remote metadata to the local cache while the #{ChefUtils::Dist::Infra::CLIENT} run is in-progress.", default: { before: false, after: false }, coerce: proc { |v| if v.is_a?(Hash) diff --git a/lib/chef/resource/dsc_resource.rb b/lib/chef/resource/dsc_resource.rb index 76d0b37b37..679deef47b 100644 --- a/lib/chef/resource/dsc_resource.rb +++ b/lib/chef/resource/dsc_resource.rb @@ -16,7 +16,6 @@ # limitations under the License. # require_relative "../dsl/powershell" -require_relative "../dist" class Chef class Resource diff --git a/lib/chef/resource/dsc_script.rb b/lib/chef/resource/dsc_script.rb index 2a4392630b..42b12cac5a 100644 --- a/lib/chef/resource/dsc_script.rb +++ b/lib/chef/resource/dsc_script.rb @@ -19,7 +19,7 @@ require_relative "../resource" require_relative "../exceptions" require_relative "../dsl/powershell" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -29,7 +29,7 @@ class Chef unified_mode true provides :dsc_script - description "Many DSC resources are comparable to built-in #{Chef::Dist::PRODUCT} resources. For example, both DSC and #{Chef::Dist::PRODUCT} have file, package, and service resources. The dsc_script resource is most useful for those DSC resources that do not have a direct comparison to a resource in #{Chef::Dist::PRODUCT}, such as the Archive resource, a custom DSC resource, an existing DSC script that performs an important task, and so on. Use the dsc_script resource to embed the code that defines a DSC configuration directly within a #{Chef::Dist::PRODUCT} recipe." + description "Many DSC resources are comparable to built-in #{ChefUtils::Dist::Infra::PRODUCT} resources. For example, both DSC and #{ChefUtils::Dist::Infra::PRODUCT} have file, package, and service resources. The dsc_script resource is most useful for those DSC resources that do not have a direct comparison to a resource in #{ChefUtils::Dist::Infra::PRODUCT}, such as the Archive resource, a custom DSC resource, an existing DSC script that performs an important task, and so on. Use the dsc_script resource to embed the code that defines a DSC configuration directly within a #{ChefUtils::Dist::Infra::PRODUCT} recipe." default_action :run diff --git a/lib/chef/resource/execute.rb b/lib/chef/resource/execute.rb index e8d74fa178..11d1c2fc40 100644 --- a/lib/chef/resource/execute.rb +++ b/lib/chef/resource/execute.rb @@ -18,7 +18,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -533,7 +533,7 @@ class Chef description: "The group name or group ID that must be changed before running a command." property :live_stream, [ TrueClass, FalseClass ], default: false, - description: "Send the output of the command run by this execute resource block to the #{Chef::Dist::PRODUCT} event stream." + description: "Send the output of the command run by this execute resource block to the #{ChefUtils::Dist::Infra::PRODUCT} event stream." # default_env defaults to `false` so that the command execution more exactly matches what the user gets on the command line without magic property :default_env, [ TrueClass, FalseClass ], desired_state: false, default: false, @@ -553,7 +553,7 @@ class Chef property :domain, String, introduced: "12.21", - description: "Windows only: The domain of the user user specified by the user property. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running #{Chef::Dist::PRODUCT} is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property." + description: "Windows only: The domain of the user user specified by the user property. If not specified, the user name and password specified by the user and password properties will be used to resolve that user against the domain in which the system running #{ChefUtils::Dist::Infra::PRODUCT} is joined, or if that system is not joined to a domain it will resolve the user as a local account on that system. An alternative way to specify the domain is to leave this property unspecified and specify the domain as part of the user property." property :password, String, sensitive: true, introduced: "12.21", @@ -561,11 +561,11 @@ class Chef # lazy used to set default value of sensitive to true if password is set property :sensitive, [ TrueClass, FalseClass ], - description: "Ensure that sensitive resource data is not logged by the #{Chef::Dist::PRODUCT}.", + description: "Ensure that sensitive resource data is not logged by the #{ChefUtils::Dist::Infra::PRODUCT}.", default: lazy { password ? true : false }, default_description: "True if the password property is set. False otherwise." property :elevated, [ TrueClass, FalseClass ], default: false, - description: "Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) interactively blocking the process.\nThis will cause the process to be run under a batch login instead of an interactive login. The user running #{Chef::Dist::CLIENT} needs the 'Replace a process level token' and 'Adjust Memory Quotas for a process' permissions. The user that is running the command needs the 'Log on as a batch job' permission.\nBecause this requires a login, the user and password properties are required.", + description: "Determines whether the script will run with elevated permissions to circumvent User Access Control (UAC) interactively blocking the process.\nThis will cause the process to be run under a batch login instead of an interactive login. The user running #{ChefUtils::Dist::Infra::CLIENT} needs the 'Replace a process level token' and 'Adjust Memory Quotas for a process' permissions. The user that is running the command needs the 'Log on as a batch job' permission.\nBecause this requires a login, the user and password properties are required.", introduced: "13.3" property :input, [String], @@ -587,7 +587,7 @@ class Chef ancestor_attributes = superclass.guard_inherited_attributes end - ancestor_attributes.concat(@class_inherited_attributes ? @class_inherited_attributes : []).uniq + ancestor_attributes.concat(@class_inherited_attributes || []).uniq end # post resource creation validation diff --git a/lib/chef/resource/file.rb b/lib/chef/resource/file.rb index eacddd02af..7bebc4ae4c 100644 --- a/lib/chef/resource/file.rb +++ b/lib/chef/resource/file.rb @@ -22,7 +22,7 @@ require_relative "../platform/query_helpers" require_relative "../mixin/securable" require_relative "file/verification" require "pathname" unless defined?(Pathname) -require_relative "../dist" +require "chef-utils" unless defined?(ChefUtils::CANARY) class Chef class Resource @@ -56,7 +56,7 @@ class Chef allowed_actions :create, :delete, :touch, :create_if_missing property :path, String, name_property: true, - description: "The full path to the file, including the file name and its extension. For example: /files/file.txt. Default value: the name of the resource block. Microsoft Windows: A path that begins with a forward slash (/) will point to the root of the current working directory of the #{Chef::Dist::CLIENT} process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (/) is not recommended." + description: "The full path to the file, including the file name and its extension. For example: /files/file.txt. Default value: the name of the resource block. Microsoft Windows: A path that begins with a forward slash (/) will point to the root of the current working directory of the #{ChefUtils::Dist::Infra::CLIENT} process. This path can vary from system to system. Therefore, using a path that begins with a forward slash (/) is not recommended." property :atomic_update, [ TrueClass, FalseClass ], desired_state: false, default: lazy { docker? && special_docker_files?(path) ? false : Chef::Config[:file_atomic_update] }, default_description: "False if modifying /etc/hosts, /etc/hostname, or /etc/resolv.conf within Docker containers. Otherwise default to the client.rb 'file_atomic_update' config value.", @@ -76,10 +76,10 @@ class Chef property :diff, [ String, nil ], desired_state: false, skip_docs: true property :force_unlink, [ TrueClass, FalseClass ], desired_state: false, default: false, - description: "How #{Chef::Dist::PRODUCT} handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for #{Chef::Dist::PRODUCT} to delete the non-file target and replace it with the specified file. Set to `false` for #{Chef::Dist::PRODUCT} to raise an error." + description: "How #{ChefUtils::Dist::Infra::PRODUCT} handles certain situations when the target file turns out not to be a file. For example, when a target file is actually a symlink. Set to `true` for #{ChefUtils::Dist::Infra::PRODUCT} to delete the non-file target and replace it with the specified file. Set to `false` for #{ChefUtils::Dist::Infra::PRODUCT} to raise an error." property :manage_symlink_source, [ TrueClass, FalseClass ], desired_state: false, - description: "Change the behavior of the file resource if it is pointed at a symlink. When this value is set to true, #{Chef::Dist::PRODUCT} will manage the symlink's permissions or will replace the symlink with a normal file if the resource has content. When this value is set to false, #{Chef::Dist::PRODUCT} will follow the symlink and will manage the permissions and content of symlink's target file. The default behavior is true but emits a warning that the default value will be changed to false in a future version; setting this explicitly to true or false suppresses this warning." + description: "Change the behavior of the file resource if it is pointed at a symlink. When this value is set to true, #{ChefUtils::Dist::Infra::PRODUCT} will manage the symlink's permissions or will replace the symlink with a normal file if the resource has content. When this value is set to false, #{ChefUtils::Dist::Infra::PRODUCT} will follow the symlink and will manage the permissions and content of symlink's target file. The default behavior is true but emits a warning that the default value will be changed to false in a future version; setting this explicitly to true or false suppresses this warning." property :verifications, Array, default: lazy { [] } diff --git a/lib/chef/resource/gem_package.rb b/lib/chef/resource/gem_package.rb index 05f8611233..c893e7a2f9 100644 --- a/lib/chef/resource/gem_package.rb +++ b/lib/chef/resource/gem_package.rb @@ -17,7 +17,7 @@ # require_relative "package" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -31,10 +31,10 @@ class Chef Note: The **gem_package** resource must be specified as `gem_package` and cannot be shortened to `package` in a recipe. - Warning: The **chef_gem** and **gem_package** resources are both used to install Ruby gems. For any machine on which #{Chef::Dist::PRODUCT} is + Warning: The **chef_gem** and **gem_package** resources are both used to install Ruby gems. For any machine on which #{ChefUtils::Dist::Infra::PRODUCT} is installed, there are two instances of Ruby. One is the standard, system-wide instance of Ruby and the other is a dedicated instance that is - available only to #{Chef::Dist::PRODUCT}. - Use the **chef_gem** resource to install gems into the instance of Ruby that is dedicated to #{Chef::Dist::PRODUCT}. + available only to #{ChefUtils::Dist::Infra::PRODUCT}. + Use the **chef_gem** resource to install gems into the instance of Ruby that is dedicated to #{ChefUtils::Dist::Infra::PRODUCT}. Use the **gem_package** resource to install all other gems (i.e. install gems system-wide). DESC @@ -86,7 +86,7 @@ class Chef default: lazy { Chef::Config[:clear_gem_sources] }, desired_state: false property :gem_binary, String, desired_state: false, - description: "The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by #{Chef::Dist::PRODUCT} will be used." + description: "The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by #{ChefUtils::Dist::Infra::PRODUCT} will be used." property :include_default_source, [ TrueClass, FalseClass, nil ], description: "Set to `false` to not include `Chef::Config[:rubygems_url]` in the sources.", diff --git a/lib/chef/resource/homebrew_package.rb b/lib/chef/resource/homebrew_package.rb index fef0561e38..3874622005 100644 --- a/lib/chef/resource/homebrew_package.rb +++ b/lib/chef/resource/homebrew_package.rb @@ -19,7 +19,7 @@ require_relative "../provider/package" require_relative "package" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -29,7 +29,7 @@ class Chef provides :homebrew_package provides :package, os: "darwin" - description "Use the **homebrew_package** resource to manage packages for the macOS platform. Note: Starting with #{Chef::Dist::PRODUCT} 16 the homebrew resource now accepts an array of packages for installing multiple packages at once." + description "Use the **homebrew_package** resource to manage packages for the macOS platform. Note: Starting with #{ChefUtils::Dist::Infra::PRODUCT} 16 the homebrew resource now accepts an array of packages for installing multiple packages at once." introduced "12.0" examples <<~DOC **Install a package**: @@ -62,7 +62,7 @@ class Chef DOC property :homebrew_user, [ String, Integer ], - description: "The name or uid of the Homebrew owner to be used by #{Chef::Dist::PRODUCT} when executing a command." + description: "The name or uid of the Homebrew owner to be used by #{ChefUtils::Dist::Infra::PRODUCT} when executing a command." end end diff --git a/lib/chef/resource/homebrew_update.rb b/lib/chef/resource/homebrew_update.rb index 17d756b039..cc191cbbdb 100644 --- a/lib/chef/resource/homebrew_update.rb +++ b/lib/chef/resource/homebrew_update.rb @@ -19,7 +19,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -38,7 +38,7 @@ class Chef action :periodic end ``` - **Update the Homebrew repository at the start of a #{Chef::Dist::PRODUCT} run**: + **Update the Homebrew repository at the start of a #{ChefUtils::Dist::Infra::PRODUCT} run**: ```ruby homebrew_update 'update' ``` diff --git a/lib/chef/resource/hostname.rb b/lib/chef/resource/hostname.rb index e76ea88e8d..e959084fa5 100644 --- a/lib/chef/resource/hostname.rb +++ b/lib/chef/resource/hostname.rb @@ -16,7 +16,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -248,7 +248,7 @@ class Chef # reboot because $windows reboot "setting hostname" do - reason "#{Chef::Dist::PRODUCT} updated system hostname" + reason "#{ChefUtils::Dist::Infra::PRODUCT} updated system hostname" only_if { new_resource.windows_reboot } action :request_reboot end diff --git a/lib/chef/resource/locale.rb b/lib/chef/resource/locale.rb index ea7f5098ab..5e4a63c06b 100644 --- a/lib/chef/resource/locale.rb +++ b/lib/chef/resource/locale.rb @@ -16,7 +16,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -71,7 +71,7 @@ class Chef # def lc_all(arg = nil) unless arg.nil? - Chef.deprecated(:locale_lc_all, "Changing LC_ALL can break #{Chef::Dist::PRODUCT}'s parsing of command output in unexpected ways.\n Use one of the more specific LC_ properties as needed.") + Chef.deprecated(:locale_lc_all, "Changing LC_ALL can break #{ChefUtils::Dist::Infra::PRODUCT}'s parsing of command output in unexpected ways.\n Use one of the more specific LC_ properties as needed.") end end diff --git a/lib/chef/resource/macos_userdefaults.rb b/lib/chef/resource/macos_userdefaults.rb index ab789635e7..a150aeb9ed 100644 --- a/lib/chef/resource/macos_userdefaults.rb +++ b/lib/chef/resource/macos_userdefaults.rb @@ -16,7 +16,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) autoload :Plist, "plist" class Chef @@ -97,7 +97,7 @@ class Chef desired_state: false property :sudo, [TrueClass, FalseClass], - description: "Set to true if the setting you wish to modify requires privileged access. This requires passwordless sudo for the '/usr/bin/defaults' command to be setup for the user running #{Chef::Dist::PRODUCT}.", + description: "Set to true if the setting you wish to modify requires privileged access. This requires passwordless sudo for the '/usr/bin/defaults' command to be setup for the user running #{ChefUtils::Dist::Infra::PRODUCT}.", default: false, desired_state: false diff --git a/lib/chef/resource/notify_group.rb b/lib/chef/resource/notify_group.rb index a8bc71527d..9a1edf3eb8 100644 --- a/lib/chef/resource/notify_group.rb +++ b/lib/chef/resource/notify_group.rb @@ -15,7 +15,6 @@ # require_relative "../resource" -require_relative "../dist" class Chef class Resource diff --git a/lib/chef/resource/ohai.rb b/lib/chef/resource/ohai.rb index 93fdb82676..560a15353a 100644 --- a/lib/chef/resource/ohai.rb +++ b/lib/chef/resource/ohai.rb @@ -19,7 +19,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) require "ohai" unless defined?(Ohai::System) class Chef @@ -29,10 +29,53 @@ class Chef provides :ohai - description "Use the **ohai** resource to reload the Ohai configuration on a node. This allows recipes that change system attributes (like a recipe that adds a user) to refer to those attributes later on during the #{Chef::Dist::CLIENT} run." + description "Use the **ohai** resource to reload the Ohai configuration on a node. This allows recipes that change system attributes (like a recipe that adds a user) to refer to those attributes later on during the #{ChefUtils::Dist::Infra::PRODUCT} run." + + examples <<~DOC + Reload All Ohai Plugins + + ```ruby + ohai 'reload' do + action :reload + end + ``` + + Reload A Single Ohai Plugin + + ```ruby + ohai 'reload' do + plugin 'ipaddress' + action :reload + end + ``` + + Reload Ohai after a new user is created + + ```ruby + ohai 'reload_passwd' do + action :nothing + plugin 'etc' + end + + user 'daemon_user' do + home '/dev/null' + shell '/sbin/nologin' + system true + notifies :reload, 'ohai[reload_passwd]', :immediately + end + + ruby_block 'just an example' do + block do + # These variables will now have the new values + puts node['etc']['passwd']['daemon_user']['uid'] + puts node['etc']['passwd']['daemon_user']['gid'] + end + end + ``` + DOC property :plugin, String, - description: "The name of an Ohai plugin to be reloaded. If this property is not specified, #{Chef::Dist::PRODUCT} will reload all plugins." + description: "Specific Ohai attribute data to reload. This property behaves similar to specifying attributes when running Ohai on the command line and takes the attribute that you wish to reload instead of the actual plugin name. For instance, you can pass `ipaddress` to reload `node['ipaddress']` even though that data comes from the `Network` plugin. If this property is not specified, #{ChefUtils::Dist::Infra::PRODUCT} will reload all plugins." def load_current_resource true diff --git a/lib/chef/resource/ohai_hint.rb b/lib/chef/resource/ohai_hint.rb index 2c962f0957..88ea02c809 100644 --- a/lib/chef/resource/ohai_hint.rb +++ b/lib/chef/resource/ohai_hint.rb @@ -26,6 +26,39 @@ class Chef description "Use the **ohai_hint** resource to aid in configuration detection by passing hint data to Ohai." introduced "14.0" + examples <<~DOC + **Create a hint file** + + ```ruby + ohai_hint 'example' do + content a: 'test_content' + end + ``` + + **Create a hint file with a name that does not match the resource name** + + ```ruby + ohai_hint 'example' do + hint_name 'custom' + end + ``` + + **Create a hint file that is not loaded at compile time** + + ```ruby + ohai_hint 'example' do + compile_time false + end + ``` + + **Delete a hint file** + + ```ruby + ohai_hint 'example' do + action :delete + end + ``` + DOC property :hint_name, String, description: "An optional property to set the hint name if it differs from the resource block's name.", diff --git a/lib/chef/resource/openssl_dhparam.rb b/lib/chef/resource/openssl_dhparam.rb index 087296e9a8..3d20b1b439 100644 --- a/lib/chef/resource/openssl_dhparam.rb +++ b/lib/chef/resource/openssl_dhparam.rb @@ -27,15 +27,37 @@ class Chef provides(:openssl_dhparam) { true } - description "Use the **openssl_dhparam** resource to generate dhparam.pem files. If a valid dhparam.pem file is found at the specified location, no new file will be created. If a file is found at the specified location but it is not a valid dhparam file, it will be overwritten." + description "Use the **openssl_dhparam** resource to generate `dhparam.pem` files. If a valid `dhparam.pem` file is found at the specified location, no new file will be created. If a file is found at the specified location but it is not a valid `dhparam.pem` file, it will be overwritten." introduced "14.0" examples <<~DOC - Create a 1024bit dhparam file + **Create a dhparam file** ```ruby - openssl_dhparam '/etc/ssl_files/dhparam.pem' do - key_length 1024 - action :create + openssl_dhparam '/etc/httpd/ssl/dhparam.pem' + ``` + + **Create a dhparam file with a specific key length** + + ```ruby + openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do + key_length 4096 + end + ``` + + **Create a dhparam file with specific user/group ownership** + + ```ruby + openssl_dhparam '/etc/httpd/ssl/dhparam.pem' do + owner 'www-data' + group 'www-data' + end + ``` + + **Manually specify the dhparam file path** + + ```ruby + openssl_dhparam 'httpd_dhparam' do + path '/etc/httpd/ssl/dhparam.pem' end ``` DOC diff --git a/lib/chef/resource/openssl_ec_private_key.rb b/lib/chef/resource/openssl_ec_private_key.rb index 26f28b1ad8..7625b5ea6e 100644 --- a/lib/chef/resource/openssl_ec_private_key.rb +++ b/lib/chef/resource/openssl_ec_private_key.rb @@ -68,6 +68,7 @@ class Chef property :key_cipher, String, description: "The designed cipher to use when generating your key. Run `openssl list-cipher-algorithms` to see available options.", default: lazy { "des3" }, + default_description: "des3", callbacks: { "key_cipher must be a cipher known to openssl. Run `openssl list-cipher-algorithms` to see available options." => proc { |v| OpenSSL::Cipher.ciphers.include?(v) }, diff --git a/lib/chef/resource/openssl_ec_public_key.rb b/lib/chef/resource/openssl_ec_public_key.rb index ec61bc95c2..44441eb72d 100644 --- a/lib/chef/resource/openssl_ec_public_key.rb +++ b/lib/chef/resource/openssl_ec_public_key.rb @@ -31,7 +31,7 @@ class Chef description "Use the **openssl_ec_public_key** resource to generate elliptic curve (EC) public key files from a given EC private key." introduced "14.4" examples <<~DOC - Generate new ec public key from a private key on disk + **Generate new EC public key from a private key on disk** ```ruby openssl_ec_public_key '/etc/ssl_files/eckey_prime256v1_des3.pub' do @@ -41,7 +41,7 @@ class Chef end ``` - Generate new ec public key by passing in a private key + **Generate new EC public key by passing in a private key** ```ruby openssl_ec_public_key '/etc/ssl_files/eckey_prime256v1_des3_2.pub' do diff --git a/lib/chef/resource/openssl_rsa_private_key.rb b/lib/chef/resource/openssl_rsa_private_key.rb index 381e2af696..e9e6ef24ca 100644 --- a/lib/chef/resource/openssl_rsa_private_key.rb +++ b/lib/chef/resource/openssl_rsa_private_key.rb @@ -67,6 +67,7 @@ class Chef property :key_cipher, String, description: "The designed cipher to use when generating your key. Run `openssl list-cipher-algorithms` to see available options.", default: lazy { "des3" }, + default_description: "des3", callbacks: { "key_cipher must be a cipher known to openssl. Run `openssl list-cipher-algorithms` to see available options." => proc { |v| OpenSSL::Cipher.ciphers.include?(v) }, diff --git a/lib/chef/resource/openssl_x509_certificate.rb b/lib/chef/resource/openssl_x509_certificate.rb index de0be22f40..c723f47d61 100644 --- a/lib/chef/resource/openssl_x509_certificate.rb +++ b/lib/chef/resource/openssl_x509_certificate.rb @@ -86,32 +86,32 @@ class Chef description: "The permission mode applied to all files created by the resource." property :country, String, - description: "Value for the C certificate field." + description: "Value for the `C` certificate field." property :state, String, - description: "Value for the ST certificate field." + description: "Value for the `ST` certificate field." property :city, String, - description: "Value for the L certificate field." + description: "Value for the `L` certificate field." property :org, String, - description: "Value for the O certificate field." + description: "Value for the `O` certificate field." property :org_unit, String, - description: "Value for the OU certificate field." + description: "Value for the `OU` certificate field." property :common_name, String, - description: "Value for the CN certificate field." + description: "Value for the `CN` certificate field." property :email, String, - description: "Value for the email certificate field." + description: "Value for the `email` certificate field." property :extensions, Hash, - description: "Hash of X509 Extensions entries, in format { 'keyUsage' => { 'values' => %w( keyEncipherment digitalSignature), 'critical' => true } }.", + description: "Hash of X509 Extensions entries, in format `{ 'keyUsage' => { 'values' => %w( keyEncipherment digitalSignature), 'critical' => true } }`.", default: lazy { {} } property :subject_alt_name, Array, - description: "Array of Subject Alternative Name entries, in format DNS:example.com or IP:1.2.3.4.", + description: "Array of Subject Alternative Name entries, in format `DNS:example.com` or `IP:1.2.3.4`.", default: lazy { [] } property :key_file, String, @@ -122,7 +122,7 @@ class Chef property :key_type, String, equal_to: %w{rsa ec}, - description: "The desired type of the generated key (rsa or ec).", + description: "The desired type of the generated key.", default: "rsa" property :key_length, Integer, @@ -131,18 +131,18 @@ class Chef default: 2048 property :key_curve, String, - description: "The desired curve of the generated key (if key_type is equal to 'ec'). Run openssl ecparam -list_curves to see available options.", + description: "The desired curve of the generated key (if key_type is equal to 'ec'). Run `openssl ecparam -list_curves` to see available options.", equal_to: %w{secp384r1 secp521r1 prime256v1}, default: "prime256v1" property :csr_file, String, - description: "The path to a X509 Certificate Request (CSR) on the filesystem. If the csr_file property is specified, the resource will attempt to source a CSR from this location. If no CSR file is found, the resource will generate a Self-Signed Certificate and the certificate fields must be specified (common_name at last)." + description: "The path to a X509 Certificate Request (CSR) on the filesystem. If the `csr_file` property is specified, the resource will attempt to source a CSR from this location. If no CSR file is found, the resource will generate a Self-Signed Certificate and the certificate fields must be specified (common_name at last)." property :ca_cert_file, String, - description: "The path to the CA X509 Certificate on the filesystem. If the ca_cert_file property is specified, the ca_key_file property must also be specified, the certificate will be signed with them." + description: "The path to the CA X509 Certificate on the filesystem. If the `ca_cert_file` property is specified, the `ca_key_file` property must also be specified, the certificate will be signed with them." property :ca_key_file, String, - description: "The path to the CA private key on the filesystem. If the ca_key_file property is specified, the 'ca_cert_file' property must also be specified, the certificate will be signed with them." + description: "The path to the CA private key on the filesystem. If the `ca_key_file` property is specified, the `ca_cert_file` property must also be specified, the certificate will be signed with them." property :ca_key_pass, String, description: "The passphrase for CA private key's passphrase." diff --git a/lib/chef/resource/openssl_x509_crl.rb b/lib/chef/resource/openssl_x509_crl.rb index 7bc96fa4da..6e7f905084 100644 --- a/lib/chef/resource/openssl_x509_crl.rb +++ b/lib/chef/resource/openssl_x509_crl.rb @@ -31,15 +31,24 @@ class Chef description "Use the **openssl_x509_crl** resource to generate PEM-formatted x509 certificate revocation list (CRL) files." introduced "14.4" examples <<~DOC - Generate a CRL file given a cert file and key file + **Create a certificate revocation file** - ```ruby - openssl_x509_crl '/etc/ssl_files/my_ca2.crl' do - ca_cert_file '/etc/ssl_files/my_ca2.crt' - ca_key_file '/etc/ssl_files/my_ca2.key' - expire 1 - end - ``` + ```ruby + openssl_x509_crl '/etc/ssl_test/my_ca.crl' do + ca_cert_file '/etc/ssl_test/my_ca.crt' + ca_key_file '/etc/ssl_test/my_ca.key' + end + ``` + + **Create a certificate revocation file for a particular serial** + + ```ruby + openssl_x509_crl '/etc/ssl_test/my_ca.crl' do + ca_cert_file '/etc/ssl_test/my_ca.crt' + ca_key_file '/etc/ssl_test/my_ca.key' + serial_to_revoke C7BCB6602A2E4251EF4E2827A228CB52BC0CEA2F + end + ``` DOC property :path, String, @@ -62,11 +71,11 @@ class Chef default: 1 property :ca_cert_file, String, - description: "The path to the CA X509 Certificate on the filesystem. If the ca_cert_file property is specified, the ca_key_file property must also be specified, the CRL will be signed with them.", + description: "The path to the CA X509 Certificate on the filesystem. If the `ca_cert_file` property is specified, the `ca_key_file` property must also be specified, the CRL will be signed with them.", required: true property :ca_key_file, String, - description: "The path to the CA private key on the filesystem. If the ca_key_file property is specified, the ca_cert_file property must also be specified, the CRL will be signed with them.", + description: "The path to the CA private key on the filesystem. If the `ca_key_file` property is specified, the `ca_cert_file` property must also be specified, the CRL will be signed with them.", required: true property :ca_key_pass, String, diff --git a/lib/chef/resource/openssl_x509_request.rb b/lib/chef/resource/openssl_x509_request.rb index 8ebf6fe8eb..0e68337b05 100644 --- a/lib/chef/resource/openssl_x509_request.rb +++ b/lib/chef/resource/openssl_x509_request.rb @@ -31,7 +31,7 @@ class Chef description "Use the **openssl_x509_request** resource to generate PEM-formatted x509 certificates requests. If no existing key is specified, the resource will automatically generate a passwordless key with the certificate." introduced "14.4" examples <<~DOC - Generate new ec key and csr file + **Generate new EC key and CSR file** ```ruby openssl_x509_request '/etc/ssl_files/my_ec_request.csr' do @@ -42,7 +42,7 @@ class Chef end ``` - Generate a new csr file from an existing ec key + **Generate a new CSR file from an existing EC key** ```ruby openssl_x509_request '/etc/ssl_files/my_ec_request2.csr' do @@ -54,7 +54,7 @@ class Chef end ``` - Generate new rsa key and csr file + **Generate new RSA key and CSR file** ```ruby openssl_x509_request '/etc/ssl_files/my_rsa_request.csr' do @@ -80,46 +80,44 @@ class Chef description: "The permission mode applied to all files created by the resource." property :country, String, - description: "Value for the C certificate field." + description: "Value for the `C` certificate field." property :state, String, - description: "Value for the ST certificate field." + description: "Value for the `ST` certificate field." property :city, String, - description: "Value for the L certificate field." + description: "Value for the `L` certificate field." property :org, String, - description: "Value for the O certificate field." + description: "Value for the `O` certificate field." property :org_unit, String, - description: "Value for the OU certificate field." + description: "Value for the `OU` certificate field." property :common_name, String, required: true, - description: "Value for the CN certificate field." + description: "Value for the `CN` certificate field." property :email, String, - description: "Value for the email certificate field." + description: "Value for the `email` certificate field." property :key_file, String, - description: "The path to a certificate key file on the filesystem. If the key_file property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the key_file property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate." + description: "The path to a certificate key file on the filesystem. If the `key_file` property is specified, the resource will attempt to source a key from this location. If no key file is found, the resource will generate a new key file at this location. If the `key_file` property is not specified, the resource will generate a key file in the same directory as the generated certificate, with the same name as the generated certificate." property :key_pass, String, description: "The passphrase for an existing key's passphrase." property :key_type, String, equal_to: %w{rsa ec}, default: "ec", - description: "The desired type of the generated key (rsa or ec)." + description: "The desired type of the generated key." property :key_length, Integer, equal_to: [1024, 2048, 4096, 8192], default: 2048, - description: "The desired bit length of the generated key (if key_type is equal to 'rsa')." + description: "The desired bit length of the generated key (if key_type is equal to `rsa`)." property :key_curve, String, equal_to: %w{secp384r1 secp521r1 prime256v1}, default: "prime256v1", - description: "The desired curve of the generated key (if key_type is equal to 'ec'). Run openssl ecparam -list_curves to see available options." - - default_action :create + description: "The desired curve of the generated key (if key_type is equal to `ec`). Run `openssl ecparam -list_curves` to see available options." action :create do description "Generate a certificate request." diff --git a/lib/chef/resource/osx_profile.rb b/lib/chef/resource/osx_profile.rb index d1a2791d3c..6c0028301d 100644 --- a/lib/chef/resource/osx_profile.rb +++ b/lib/chef/resource/osx_profile.rb @@ -30,8 +30,72 @@ class Chef provides :osx_profile provides :osx_config_profile - description "Use the **osx_profile** resource to manage configuration profiles (.mobileconfig files) on the macOS platform. The osx_profile resource installs profiles by using the uuidgen library to generate a unique ProfileUUID, and then using the profiles command to install the profile on the system." + description "Use the **osx_profile** resource to manage configuration profiles (`.mobileconfig` files) on the macOS platform. The **osx_profile** resource installs profiles by using the uuidgen library to generate a unique `ProfileUUID`, and then using the `profiles` command to install the profile on the system." introduced "12.7" + examples <<~DOC + **Install a profile from a cookbook file** + + ```ruby + osx_profile 'com.company.screensaver.mobileconfig' + ``` + + **Install profile from a hash** + + ```ruby + profile_hash = { + 'PayloadIdentifier' => 'com.company.screensaver', + 'PayloadRemovalDisallowed' => false, + 'PayloadScope' => 'System', + 'PayloadType' => 'Configuration', + 'PayloadUUID' => '1781fbec-3325-565f-9022-8aa28135c3cc', + 'PayloadOrganization' => 'Chef', + 'PayloadVersion' => 1, + 'PayloadDisplayName' => 'Screensaver Settings', + 'PayloadContent'=> [ + { + 'PayloadType' => 'com.apple.ManagedClient.preferences', + 'PayloadVersion' => 1, + 'PayloadIdentifier' => 'com.company.screensaver', + 'PayloadUUID' => '73fc30e0-1e57-0131-c32d-000c2944c108', + 'PayloadEnabled' => true, + 'PayloadDisplayName' => 'com.apple.screensaver', + 'PayloadContent' => { + 'com.apple.screensaver' => { + 'Forced' => [ + { + 'mcx_preference_settings' => { + 'idleTime' => 0, + } + } + ] + } + } + } + ] + } + + osx_profile 'Install screensaver profile' do + profile profile_hash + end + ``` + + **Remove profile using identifier in resource name** + + ```ruby + osx_profile 'com.company.screensaver' do + action :remove + end + ``` + + **Remove profile by identifier and user friendly resource name** + + ```ruby + osx_profile 'Remove screensaver profile' do + identifier 'com.company.screensaver' + action :remove + end + ``` + DOC property :profile_name, String, description: "Use to specify the name of the profile, if different from the name of the resource block.", @@ -41,7 +105,7 @@ class Chef description: "Use to specify a profile. This may be the name of a profile contained in a cookbook or a Hash that contains the contents of the profile." property :identifier, String, - description: "Use to specify the identifier for the profile, such as com.company.screensaver." + description: "Use to specify the identifier for the profile, such as `com.company.screensaver`." # this is not a property it is necessary for the tempfile this resource uses to work (FIXME: this is terrible) # @@ -244,19 +308,18 @@ class Chef # def get_installed_profiles(update = nil) + logger.trace("Saving profile data to node.run_state") if update node.run_state[:config_profiles] = query_installed_profiles else node.run_state[:config_profiles] ||= query_installed_profiles end - logger.trace("Saved profiles to run_state") end def query_installed_profiles - Tempfile.open("allprofiles.plist") do |tempfile| - shell_out( "/usr/bin/profiles", "-P", "-o", tempfile.path ) - ::Plist.parse_xml(tempfile) - end + logger.trace("Running /usr/bin/profiles -P -o stdout-xml to determine profile state") + so = shell_out( "/usr/bin/profiles", "-P", "-o", "stdout-xml" ) + ::Plist.parse_xml(so.stdout) end def profile_installed? diff --git a/lib/chef/resource/powershell_package_source.rb b/lib/chef/resource/powershell_package_source.rb index 051b6d4239..e17c23abe2 100644 --- a/lib/chef/resource/powershell_package_source.rb +++ b/lib/chef/resource/powershell_package_source.rb @@ -33,7 +33,7 @@ class Chef name_property: true property :url, String, - description: "The url to the package source.", + description: "The URL to the package source.", required: [:register] property :trusted, [TrueClass, FalseClass], @@ -43,17 +43,17 @@ class Chef property :provider_name, String, equal_to: %w{ Programs msi NuGet msu PowerShellGet psl chocolatey }, validation_message: "The following providers are supported: 'Programs', 'msi', 'NuGet', 'msu', 'PowerShellGet', 'psl' or 'chocolatey'", - description: "The package management provider for the source. It supports the following providers: 'Programs', 'msi', 'NuGet', 'msu', 'PowerShellGet', 'psl' and 'chocolatey'.", + description: "The package management provider for the source.", default: "NuGet" property :publish_location, String, - description: "The url where modules will be published to for this source. Only valid if the provider is 'PowerShellGet'." + description: "The URL where modules will be published to for this source. Only valid if the provider is `PowerShellGet`." property :script_source_location, String, - description: "The url where scripts are located for this source. Only valid if the provider is 'PowerShellGet'." + description: "The URL where scripts are located for this source. Only valid if the provider is `PowerShellGet`." property :script_publish_location, String, - description: "The location where scripts will be published to for this source. Only valid if the provider is 'PowerShellGet'." + description: "The location where scripts will be published to for this source. Only valid if the provider is `PowerShellGet`." load_current_value do cmd = load_resource_state_script(source_name) diff --git a/lib/chef/resource/reboot.rb b/lib/chef/resource/reboot.rb index 38a493cfae..6ac19e299b 100644 --- a/lib/chef/resource/reboot.rb +++ b/lib/chef/resource/reboot.rb @@ -17,7 +17,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -36,7 +36,7 @@ class Chef property :reason, String, description: "A string that describes the reboot action.", - default: "Reboot by #{Chef::Dist::PRODUCT}" + default: "Reboot by #{ChefUtils::Dist::Infra::PRODUCT}" property :delay_mins, Integer, description: "The amount of time (in minutes) to delay a reboot request.", diff --git a/lib/chef/resource/remote_file.rb b/lib/chef/resource/remote_file.rb index d183fed64f..ac0b2fe6a7 100644 --- a/lib/chef/resource/remote_file.rb +++ b/lib/chef/resource/remote_file.rb @@ -22,7 +22,7 @@ require_relative "file" require_relative "../provider/remote_file" require_relative "../mixin/securable" require_relative "../mixin/uris" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -74,7 +74,7 @@ class Chef end property :checksum, String, - description: "Optional, see `use_conditional_get`. The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, #{Chef::Dist::PRODUCT} does not download it." + description: "Optional, see `use_conditional_get`. The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, #{ChefUtils::Dist::Infra::PRODUCT} does not download it." # Disable or enable ETag and Last Modified conditional GET. Equivalent to # use_etag(true_or_false) @@ -93,7 +93,7 @@ class Chef description: "Enable `If-Modified-Since` headers. Set to `false` to disable `If-Modified-Since` headers. To use this setting, `use_conditional_get` must also be set to `true`." property :ftp_active_mode, [ TrueClass, FalseClass ], default: false, - description: "Whether #{Chef::Dist::PRODUCT} uses active or passive FTP. Set to `true` to use active FTP." + description: "Whether #{ChefUtils::Dist::Infra::PRODUCT} uses active or passive FTP. Set to `true` to use active FTP." property :headers, Hash, default: lazy { {} }, description: "A Hash of custom HTTP headers." diff --git a/lib/chef/resource/rhsm_register.rb b/lib/chef/resource/rhsm_register.rb index 80cf62e169..07c4dbc8d7 100644 --- a/lib/chef/resource/rhsm_register.rb +++ b/lib/chef/resource/rhsm_register.rb @@ -16,7 +16,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) require "shellwords" unless defined?(Shellwords) class Chef @@ -65,7 +65,7 @@ class Chef default: false, desired_state: false property :https_for_ca_consumer, [TrueClass, FalseClass], - description: "If true, #{Chef::Dist::PRODUCT} will fetch the katello-ca-consumer-latest.noarch.rpm from the satellite_host using HTTPS.", + description: "If true, #{ChefUtils::Dist::Infra::PRODUCT} will fetch the katello-ca-consumer-latest.noarch.rpm from the satellite_host using HTTPS.", default: false, desired_state: false, introduced: "15.9" diff --git a/lib/chef/resource/ruby_block.rb b/lib/chef/resource/ruby_block.rb index 1fcebe090a..427c3e25da 100644 --- a/lib/chef/resource/ruby_block.rb +++ b/lib/chef/resource/ruby_block.rb @@ -19,7 +19,7 @@ require_relative "../resource" require_relative "../provider/ruby_block" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -28,7 +28,7 @@ class Chef provides :ruby_block, target_mode: true - description "Use the **ruby_block** resource to execute Ruby code during a #{Chef::Dist::PRODUCT} run. Ruby code in the ruby_block resource is evaluated with other resources during convergence, whereas Ruby code outside of a ruby_block resource is evaluated before other resources, as the recipe is compiled." + description "Use the **ruby_block** resource to execute Ruby code during a #{ChefUtils::Dist::Infra::PRODUCT} run. Ruby code in the ruby_block resource is evaluated with other resources during convergence, whereas Ruby code outside of a ruby_block resource is evaluated before other resources, as the recipe is compiled." default_action :run allowed_actions :create, :run diff --git a/lib/chef/resource/scm/subversion.rb b/lib/chef/resource/scm/subversion.rb index 14360e9816..f5637b04ad 100644 --- a/lib/chef/resource/scm/subversion.rb +++ b/lib/chef/resource/scm/subversion.rb @@ -17,7 +17,7 @@ # limitations under the License. # -require_relative "../../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -38,7 +38,7 @@ class Chef default: "--no-auth-cache" property :svn_info_args, [String, nil, FalseClass], - description: "Use when the `svn info` command is used by #{Chef::Dist::PRODUCT} and arguments need to be passed. The `svn_arguments` command does not work when the `svn info` command is used.", + description: "Use when the `svn info` command is used by #{ChefUtils::Dist::Infra::PRODUCT} and arguments need to be passed. The `svn_arguments` command does not work when the `svn info` command is used.", coerce: proc { |v| v == false ? nil : v }, # coerce false to nil default: "--no-auth-cache" diff --git a/lib/chef/resource/service.rb b/lib/chef/resource/service.rb index 9a6ad20ee8..63674a3c93 100644 --- a/lib/chef/resource/service.rb +++ b/lib/chef/resource/service.rb @@ -20,7 +20,7 @@ require "chef-utils/dsl/service" unless defined?(ChefUtils::DSL::Service) require_relative "../resource" require "shellwords" unless defined?(Shellwords) -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -39,7 +39,7 @@ class Chef # this is a poor API please do not re-use this pattern property :supports, Hash, default: { restart: nil, reload: nil, status: nil }, - description: "A list of properties that controls how #{Chef::Dist::PRODUCT} is to attempt to manage a service: :restart, :reload, :status. For :restart, the init script or other service provider can use a restart command; if :restart is not specified, the #{Chef::Dist::CLIENT} attempts to stop and then start a service. For :reload, the init script or other service provider can use a reload command. For :status, the init script or other service provider can use a status command to determine if the service is running; if :status is not specified, the #{Chef::Dist::CLIENT} attempts to match the service_name against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: { restart: false, reload: false, status: false } for all platforms (except for the Red Hat platform family, which defaults to { restart: false, reload: false, status: true }.)", + description: "A list of properties that controls how #{ChefUtils::Dist::Infra::PRODUCT} is to attempt to manage a service: :restart, :reload, :status. For :restart, the init script or other service provider can use a restart command; if :restart is not specified, the #{ChefUtils::Dist::Infra::CLIENT} attempts to stop and then start a service. For :reload, the init script or other service provider can use a reload command. For :status, the init script or other service provider can use a status command to determine if the service is running; if :status is not specified, the #{ChefUtils::Dist::Infra::CLIENT} attempts to match the service_name against the process table as a regular expression, unless a pattern is specified as a parameter property. Default value: { restart: false, reload: false, status: false } for all platforms (except for the Red Hat platform family, which defaults to { restart: false, reload: false, status: true }.)", coerce: proc { |x| x.is_a?(Array) ? x.each_with_object({}) { |i, m| m[i] = true } : x } property :service_name, String, @@ -82,7 +82,7 @@ class Chef # specify overrides for the start_command, stop_command and # restart_command properties. property :init_command, String, - description: "The path to the init script that is associated with the service. Use init_command to prevent the need to specify overrides for the start_command, stop_command, and restart_command properties. When this property is not specified, the #{Chef::Dist::PRODUCT} will use the default init command for the service provider being used.", + description: "The path to the init script that is associated with the service. Use init_command to prevent the need to specify overrides for the start_command, stop_command, and restart_command properties. When this property is not specified, the #{ChefUtils::Dist::Infra::PRODUCT} will use the default init command for the service provider being used.", desired_state: false # if the service is enabled or not diff --git a/lib/chef/resource/ssh_known_hosts_entry.rb b/lib/chef/resource/ssh_known_hosts_entry.rb index 533cb42279..1db811978c 100644 --- a/lib/chef/resource/ssh_known_hosts_entry.rb +++ b/lib/chef/resource/ssh_known_hosts_entry.rb @@ -18,7 +18,7 @@ # limitations under the License. require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -130,7 +130,7 @@ class Chef # all this does is send an immediate run_action(:create) to the template resource action :flush do - description "Immediately flush the entries to the config file. Without this the actual writing of the file is delayed in the #{Chef::Dist::PRODUCT} run so all entries can be accumulated before writing the file out." + description "Immediately flush the entries to the config file. Without this the actual writing of the file is delayed in the #{ChefUtils::Dist::Infra::PRODUCT} run so all entries can be accumulated before writing the file out." with_run_context :root do # if you haven't ever called ssh_known_hosts_entry before you're definitely doing it wrong so we blow up hard. diff --git a/lib/chef/resource/support/cron.d.erb b/lib/chef/resource/support/cron.d.erb index a00b541cd1..579e64f405 100644 --- a/lib/chef/resource/support/cron.d.erb +++ b/lib/chef/resource/support/cron.d.erb @@ -1,4 +1,4 @@ -# Generated by <%= Chef::Dist::PRODUCT %>. Changes will be overwritten. +# Generated by <%= ChefUtils::Dist::Infra::PRODUCT %>. Changes will be overwritten. <% if @mailto -%> MAILTO=<%= @mailto %> <% end -%> diff --git a/lib/chef/resource/support/cron_access.erb b/lib/chef/resource/support/cron_access.erb index 5e5813457c..1f4e74ab23 100644 --- a/lib/chef/resource/support/cron_access.erb +++ b/lib/chef/resource/support/cron_access.erb @@ -1,4 +1,4 @@ -# Generated by <%= Chef::Dist::PRODUCT %>. Changes will be overwritten. +# Generated by <%= ChefUtils::Dist::Infra::PRODUCT %>. Changes will be overwritten. <% @users.sort.uniq.each do |user| -%> <%= user %> <% end -%> diff --git a/lib/chef/resource/support/sudoer.erb b/lib/chef/resource/support/sudoer.erb index 8c570affdc..f8c9760d94 100644 --- a/lib/chef/resource/support/sudoer.erb +++ b/lib/chef/resource/support/sudoer.erb @@ -1,4 +1,4 @@ -# This file is managed by <%= Chef::Dist::PRODUCT %>. Changes will be overwritten. +# This file is managed by <%= ChefUtils::Dist::Infra::PRODUCT %>. Changes will be overwritten. <% @command_aliases.each do |a| -%> Cmnd_Alias <%= a[:name].upcase %> = <%= a[:command_list].join(', ') %> diff --git a/lib/chef/resource/support/ulimit.erb b/lib/chef/resource/support/ulimit.erb index 6abfc14e07..25ac0fde5c 100644 --- a/lib/chef/resource/support/ulimit.erb +++ b/lib/chef/resource/support/ulimit.erb @@ -1,4 +1,4 @@ -# Generated by <%= Chef::Dist::PRODUCT %>. Changes will be overwritten. +# Generated by <%= ChefUtils::Dist::Infra::PRODUCT %>. Changes will be overwritten. # Limits settings for <%= @ulimit_user %> diff --git a/lib/chef/resource/systemd_unit.rb b/lib/chef/resource/systemd_unit.rb index 8bb14be636..c220c18450 100644 --- a/lib/chef/resource/systemd_unit.rb +++ b/lib/chef/resource/systemd_unit.rb @@ -17,7 +17,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) require "iniparse" class Chef @@ -52,7 +52,7 @@ class Chef description: "The user account that the systemd unit process is run under. The path to the unit for that user would be something like '/etc/systemd/user/sshd.service'. If no user account is specified, the systemd unit will run under a 'system' account, with the path to the unit being something like '/etc/systemd/system/sshd.service'." property :content, [String, Hash], - description: "A string or hash that contains a systemd [unit file](https://www.freedesktop.org/software/systemd/man/systemd.unit.html) definition that describes the properties of systemd-managed entities, such as services, sockets, devices, and so on. In #{Chef::Dist::PRODUCT} 14.4 or later, repeatable options can be implemented with an array." + description: "A string or hash that contains a systemd [unit file](https://www.freedesktop.org/software/systemd/man/systemd.unit.html) definition that describes the properties of systemd-managed entities, such as services, sockets, devices, and so on. In #{ChefUtils::Dist::Infra::PRODUCT} 14.4 or later, repeatable options can be implemented with an array." property :triggers_reload, [TrueClass, FalseClass], description: "Specifies whether to trigger a daemon reload when creating or deleting a unit.", diff --git a/lib/chef/resource/template.rb b/lib/chef/resource/template.rb index 0ffa2194d8..88fde45a25 100644 --- a/lib/chef/resource/template.rb +++ b/lib/chef/resource/template.rb @@ -20,7 +20,7 @@ require_relative "file" require_relative "../mixin/securable" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -69,7 +69,7 @@ class Chef property :local, [ TrueClass, FalseClass ], default: false, desired_state: false, - description: "Load a template from a local path. By default, the #{Chef::Dist::CLIENT} loads templates from a cookbook's /templates directory. When this property is set to true, use the source property to specify the path to a template on the local node." + description: "Load a template from a local path. By default, the #{ChefUtils::Dist::Infra::CLIENT} loads templates from a cookbook's /templates directory. When this property is set to true, use the source property to specify the path to a template on the local node." # Declares a helper method to be defined in the template context when # rendering. diff --git a/lib/chef/resource/windows_ad_join.rb b/lib/chef/resource/windows_ad_join.rb index d46a5399e5..6201b57379 100644 --- a/lib/chef/resource/windows_ad_join.rb +++ b/lib/chef/resource/windows_ad_join.rb @@ -16,7 +16,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -76,8 +76,8 @@ class Chef property :reboot, Symbol, equal_to: %i{immediate delayed never request_reboot reboot_now}, - validation_message: "The reboot property accepts :immediate (reboot as soon as the resource completes), :delayed (reboot once the #{Chef::Dist::PRODUCT} run completes), and :never (Don't reboot)", - description: "Controls the system reboot behavior post domain joining. Reboot immediately, after the #{Chef::Dist::PRODUCT} run completes, or never. Note that a reboot is necessary for changes to take effect.", + validation_message: "The reboot property accepts :immediate (reboot as soon as the resource completes), :delayed (reboot once the #{ChefUtils::Dist::Infra::PRODUCT} run completes), and :never (Don't reboot)", + description: "Controls the system reboot behavior post domain joining. Reboot immediately, after the #{ChefUtils::Dist::Infra::PRODUCT} run completes, or never. Note that a reboot is necessary for changes to take effect.", default: :immediate property :reboot_delay, Integer, diff --git a/lib/chef/resource/windows_certificate.rb b/lib/chef/resource/windows_certificate.rb index 215f87d9c3..62028c0c6e 100644 --- a/lib/chef/resource/windows_certificate.rb +++ b/lib/chef/resource/windows_certificate.rb @@ -23,7 +23,7 @@ module Win32 autoload :Certstore, "win32-certstore" if Chef::Platform.windows? end autoload :OpenSSL, "openssl" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -84,7 +84,7 @@ class Chef # lazy used to set default value of sensitive to true if password is set property :sensitive, [TrueClass, FalseClass], - description: "Ensure that sensitive resource data is not logged by the #{Chef::Dist::CLIENT}.", + description: "Ensure that sensitive resource data is not logged by the #{ChefUtils::Dist::Infra::CLIENT}.", default: lazy { pfx_password ? true : false }, skip_docs: true action :create do diff --git a/lib/chef/resource/windows_package.rb b/lib/chef/resource/windows_package.rb index b11567311f..2e10dde43d 100644 --- a/lib/chef/resource/windows_package.rb +++ b/lib/chef/resource/windows_package.rb @@ -20,7 +20,7 @@ require_relative "../mixin/uris" require_relative "package" require_relative "../provider/package/windows" require_relative "../win32/error" if RUBY_PLATFORM.match?(/mswin|mingw|windows/) -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -162,7 +162,7 @@ class Chef property :checksum, String, desired_state: false, coerce: (proc { |c| c.downcase }), - description: "The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, #{Chef::Dist::PRODUCT} does not download it. Use when a URL is specified by the `source` property." + description: "The SHA-256 checksum of the file. Use to prevent a file from being re-downloaded. When the local file matches the checksum, #{ChefUtils::Dist::Infra::PRODUCT} does not download it. Use when a URL is specified by the `source` property." property :remote_file_attributes, Hash, desired_state: false, diff --git a/lib/chef/resource/windows_user_privilege.rb b/lib/chef/resource/windows_user_privilege.rb index 142a49639b..971338303d 100644 --- a/lib/chef/resource/windows_user_privilege.rb +++ b/lib/chef/resource/windows_user_privilege.rb @@ -23,52 +23,6 @@ class Chef class WindowsUserPrivilege < Chef::Resource unified_mode true - privilege_opts = %w{ SeAssignPrimaryTokenPrivilege - SeAuditPrivilege - SeBackupPrivilege - SeBatchLogonRight - SeChangeNotifyPrivilege - SeCreateGlobalPrivilege - SeCreatePagefilePrivilege - SeCreatePermanentPrivilege - SeCreateSymbolicLinkPrivilege - SeCreateTokenPrivilege - SeDebugPrivilege - SeDenyBatchLogonRight - SeDenyInteractiveLogonRight - SeDenyNetworkLogonRight - SeDenyRemoteInteractiveLogonRight - SeDenyServiceLogonRight - SeEnableDelegationPrivilege - SeImpersonatePrivilege - SeIncreaseBasePriorityPrivilege - SeIncreaseQuotaPrivilege - SeIncreaseWorkingSetPrivilege - SeInteractiveLogonRight - SeLoadDriverPrivilege - SeLockMemoryPrivilege - SeMachineAccountPrivilege - SeManageVolumePrivilege - SeNetworkLogonRight - SeProfileSingleProcessPrivilege - SeRelabelPrivilege - SeRemoteInteractiveLogonRight - SeRemoteShutdownPrivilege - SeRestorePrivilege - SeSecurityPrivilege - SeServiceLogonRight - SeShutdownPrivilege - SeSyncAgentPrivilege - SeSystemEnvironmentPrivilege - SeSystemProfilePrivilege - SeSystemtimePrivilege - SeTakeOwnershipPrivilege - SeTcbPrivilege - SeTimeZonePrivilege - SeTrustedCredManAccessPrivilege - SeUndockPrivilege - } - provides :windows_user_privilege description "The windows_user_privilege resource allows to add and set principal (User/Group) to the specified privilege.\n Ref: https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/user-rights-assignment" @@ -125,31 +79,66 @@ class Chef ``` DOC + PRIVILEGE_OPTS = %w{ SeAssignPrimaryTokenPrivilege + SeAuditPrivilege + SeBackupPrivilege + SeBatchLogonRight + SeChangeNotifyPrivilege + SeCreateGlobalPrivilege + SeCreatePagefilePrivilege + SeCreatePermanentPrivilege + SeCreateSymbolicLinkPrivilege + SeCreateTokenPrivilege + SeDebugPrivilege + SeDenyBatchLogonRight + SeDenyInteractiveLogonRight + SeDenyNetworkLogonRight + SeDenyRemoteInteractiveLogonRight + SeDenyServiceLogonRight + SeEnableDelegationPrivilege + SeImpersonatePrivilege + SeIncreaseBasePriorityPrivilege + SeIncreaseQuotaPrivilege + SeIncreaseWorkingSetPrivilege + SeInteractiveLogonRight + SeLoadDriverPrivilege + SeLockMemoryPrivilege + SeMachineAccountPrivilege + SeManageVolumePrivilege + SeNetworkLogonRight + SeProfileSingleProcessPrivilege + SeRelabelPrivilege + SeRemoteInteractiveLogonRight + SeRemoteShutdownPrivilege + SeRestorePrivilege + SeSecurityPrivilege + SeServiceLogonRight + SeShutdownPrivilege + SeSyncAgentPrivilege + SeSystemEnvironmentPrivilege + SeSystemProfilePrivilege + SeSystemtimePrivilege + SeTakeOwnershipPrivilege + SeTcbPrivilege + SeTimeZonePrivilege + SeTrustedCredManAccessPrivilege + SeUndockPrivilege + }.freeze + property :principal, String, description: "An optional property to add the user to the given privilege. Use only with add and remove action.", name_property: true - property :users, Array, - description: "An optional property to set the privilege for given users. Use only with set action." + property :users, [Array, String], + description: "An optional property to set the privilege for given users. Use only with set action.", + coerce: proc { |v| Array(v) } property :privilege, [Array, String], - description: "Privilege to set for users.", + description: "One or more privileges to set for users.", required: true, - coerce: proc { |v| v.is_a?(String) ? Array[v] : v }, + coerce: proc { |v| Array(v) }, callbacks: { - "Option privilege must include any of the: #{privilege_opts}" => lambda { |n| - if n.is_a?(String) - these_options = Array[n] - else - these_options = n - end - - if (these_options - privilege_opts).empty? - true - else - false - end - }, + "Privilege property restricted to the following values: #{PRIVILEGE_OPTS}" => lambda { |n| (n - PRIVILEGE_OPTS).empty? }, } load_current_value do |new_resource| diff --git a/lib/chef/resource/windows_workgroup.rb b/lib/chef/resource/windows_workgroup.rb index ce6129c4f7..aa2af646dc 100644 --- a/lib/chef/resource/windows_workgroup.rb +++ b/lib/chef/resource/windows_workgroup.rb @@ -16,7 +16,7 @@ # require_relative "../resource" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -59,8 +59,8 @@ class Chef property :reboot, Symbol, equal_to: %i{never request_reboot reboot_now}, - validation_message: "The reboot property accepts :immediate (reboot as soon as the resource completes), :delayed (reboot once the #{Chef::Dist::PRODUCT} run completes), and :never (Don't reboot)", - description: "Controls the system reboot behavior post workgroup joining. Reboot immediately, after the #{Chef::Dist::PRODUCT} run completes, or never. Note that a reboot is necessary for changes to take effect.", + validation_message: "The reboot property accepts :immediate (reboot as soon as the resource completes), :delayed (reboot once the #{ChefUtils::Dist::Infra::PRODUCT} run completes), and :never (Don't reboot)", + description: "Controls the system reboot behavior post workgroup joining. Reboot immediately, after the #{ChefUtils::Dist::Infra::PRODUCT} run completes, or never. Note that a reboot is necessary for changes to take effect.", coerce: proc { |x| clarify_reboot(x) }, default: :immediate, desired_state: false diff --git a/lib/chef/resource/yum_package.rb b/lib/chef/resource/yum_package.rb index 7db8bcc948..f7c4517c6d 100644 --- a/lib/chef/resource/yum_package.rb +++ b/lib/chef/resource/yum_package.rb @@ -17,7 +17,7 @@ # require_relative "package" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) class Chef class Resource @@ -135,7 +135,7 @@ class Chef coerce: proc { |x| x.is_a?(Array) ? x.to_a : x } property :flush_cache, Hash, - description: "Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Accepts a Hash in the form: { :before => true/false, :after => true/false } or an Array in the form [ :before, :after ].\nYum automatically synchronizes remote metadata to a local cache. The #{Chef::Dist::CLIENT} creates a copy of the local cache, and then stores it in-memory during the #{Chef::Dist::CLIENT} run. The in-memory cache allows packages to be installed during the #{Chef::Dist::CLIENT} run without the need to continue synchronizing the remote metadata to the local cache while the #{Chef::Dist::CLIENT} run is in-progress.", + description: "Flush the in-memory cache before or after a Yum operation that installs, upgrades, or removes a package. Accepts a Hash in the form: { :before => true/false, :after => true/false } or an Array in the form [ :before, :after ].\nYum automatically synchronizes remote metadata to a local cache. The #{ChefUtils::Dist::Infra::CLIENT} creates a copy of the local cache, and then stores it in-memory during the #{ChefUtils::Dist::Infra::CLIENT} run. The in-memory cache allows packages to be installed during the #{ChefUtils::Dist::Infra::CLIENT} run without the need to continue synchronizing the remote metadata to the local cache while the #{ChefUtils::Dist::Infra::CLIENT} run is in-progress.", default: { before: false, after: false }, coerce: proc { |v| if v.is_a?(Hash) diff --git a/lib/chef/resource_reporter.rb b/lib/chef/resource_reporter.rb index 379201768f..4051ac2f49 100644 --- a/lib/chef/resource_reporter.rb +++ b/lib/chef/resource_reporter.rb @@ -19,8 +19,6 @@ # limitations under the License. # -require "uri" unless defined?(URI) -require "securerandom" unless defined?(SecureRandom) require_relative "event_dispatch/base" class Chef diff --git a/lib/chef/run_context.rb b/lib/chef/run_context.rb index bfefc6e101..75c18f2fcf 100644 --- a/lib/chef/run_context.rb +++ b/lib/chef/run_context.rb @@ -627,7 +627,7 @@ class Chef # @return [Train::Plugins::Transport] The child class for our train transport. # def transport - @transport ||= Chef::TrainTransport.build_transport(logger) + @transport ||= Chef::TrainTransport.new(logger).build_transport end # Remote connection object from Train diff --git a/lib/chef/run_lock.rb b/lib/chef/run_lock.rb index a7c66837d5..75d1432773 100644 --- a/lib/chef/run_lock.rb +++ b/lib/chef/run_lock.rb @@ -23,7 +23,7 @@ end require_relative "config" require_relative "exceptions" require "timeout" unless defined?(Timeout) -require_relative "dist" +require "chef-utils" unless defined?(ChefUtils::CANARY) class Chef @@ -96,7 +96,7 @@ class Chef # Waits until acquiring the system-wide lock. # def wait - Chef::Log.warn("#{Chef::Dist::PRODUCT} #{runpid} is running, will wait for it to finish and then run.") + Chef::Log.warn("#{ChefUtils::Dist::Infra::PRODUCT} #{runpid} is running, will wait for it to finish and then run.") if ChefUtils.windows? mutex.wait else diff --git a/lib/chef/search/query.rb b/lib/chef/search/query.rb index 70b31cd5e4..c278ea9a68 100644 --- a/lib/chef/search/query.rb +++ b/lib/chef/search/query.rb @@ -21,7 +21,9 @@ require_relative "../exceptions" require_relative "../server_api" autoload :URI, "uri" -autoload :Addressable, "addressable/uri" +module Addressable + autoload :URI, "addressable/uri" +end class Chef class Search diff --git a/lib/chef/shell.rb b/lib/chef/shell.rb index 1a012144ed..a425129fa8 100644 --- a/lib/chef/shell.rb +++ b/lib/chef/shell.rb @@ -24,13 +24,13 @@ require "singleton" unless defined?(Singleton) require "pp" unless defined?(PP) require "etc" unless defined?(Etc) require "mixlib/cli" unless defined?(Mixlib::CLI) +require "chef-utils/dist" unless defined?(ChefUtils::Dist) require_relative "../chef" require_relative "version" require_relative "client" require_relative "config" require_relative "config_fetcher" -require_relative "dist" require_relative "shell/shell_session" require_relative "workstation_config_loader" @@ -131,11 +131,11 @@ module Shell irb_conf[:IRB_RC] = lambda do |conf| m = conf.main - conf.prompt_c = "#{Chef::Dist::EXEC}#{leader(m)} > " + conf.prompt_c = "#{ChefUtils::Dist::Infra::EXEC}#{leader(m)} > " conf.return_format = " => %s \n" - conf.prompt_i = "#{Chef::Dist::EXEC}#{leader(m)} (#{Chef::VERSION})> " - conf.prompt_n = "#{Chef::Dist::EXEC}#{leader(m)} ?> " - conf.prompt_s = "#{Chef::Dist::EXEC}#{leader(m)}%l> " + conf.prompt_i = "#{ChefUtils::Dist::Infra::EXEC}#{leader(m)} (#{Chef::VERSION})> " + conf.prompt_n = "#{ChefUtils::Dist::Infra::EXEC}#{leader(m)} ?> " + conf.prompt_s = "#{ChefUtils::Dist::Infra::EXEC}#{leader(m)}%l> " conf.use_tracer = false conf.instance_variable_set(:@use_multiline, false) conf.instance_variable_set(:@use_singleline, false) @@ -217,17 +217,17 @@ module Shell @footer end - banner("#{Chef::Dist::SHELL} #{Chef::VERSION}\n\nUsage: #{Chef::Dist::SHELL} [NAMED_CONF] (OPTIONS)") + banner("#{ChefUtils::Dist::Infra::SHELL} #{Chef::VERSION}\n\nUsage: #{ChefUtils::Dist::Infra::SHELL} [NAMED_CONF] (OPTIONS)") footer(<<~FOOTER) - When no CONFIG is specified, #{Chef::Dist::SHELL} attempts to load a default configuration file: - * If a NAMED_CONF is given, #{Chef::Dist::SHELL} will load ~/#{Chef::Dist::USER_CONF_DIR}/NAMED_CONF/#{Chef::Dist::SHELL_CONF} - * If no NAMED_CONF is given #{Chef::Dist::SHELL} will load ~/#{Chef::Dist::USER_CONF_DIR}/#{Chef::Dist::SHELL_CONF} if it exists - * If no #{Chef::Dist::SHELL_CONF} can be found, #{Chef::Dist::SHELL} falls back to load: - #{Chef::Dist::CONF_DIR}/client.rb if -z option is given. - #{Chef::Dist::CONF_DIR}/solo.rb if --solo-legacy-mode option is given. - #{Chef::Dist::USER_CONF_DIR}/config.rb if -s option is given. - #{Chef::Dist::USER_CONF_DIR}/knife.rb if -s option is given. + When no CONFIG is specified, #{ChefUtils::Dist::Infra::SHELL} attempts to load a default configuration file: + * If a NAMED_CONF is given, #{ChefUtils::Dist::Infra::SHELL} will load ~/#{ChefUtils::Dist::Infra::USER_CONF_DIR}/NAMED_CONF/#{ChefUtils::Dist::Infra::SHELL_CONF} + * If no NAMED_CONF is given #{ChefUtils::Dist::Infra::SHELL} will load ~/#{ChefUtils::Dist::Infra::USER_CONF_DIR}/#{ChefUtils::Dist::Infra::SHELL_CONF} if it exists + * If no #{ChefUtils::Dist::Infra::SHELL_CONF} can be found, #{ChefUtils::Dist::Infra::SHELL} falls back to load: + #{ChefConfig::Config.etc_chef_dir}/client.rb if -z option is given. + #{ChefConfig::Config.etc_chef_dir}/solo.rb if --solo-legacy-mode option is given. + #{ChefUtils::Dist::Infra::USER_CONF_DIR}/config.rb if -s option is given. + #{ChefUtils::Dist::Infra::USER_CONF_DIR}/knife.rb if -s option is given. FOOTER option :use_multiline, @@ -274,19 +274,19 @@ module Shell option :solo_shell, short: "-s", long: "--solo", - description: "#{Chef::Dist::SOLO} session", + description: "#{ChefUtils::Dist::Solo::PRODUCT} session", boolean: true, proc: proc { Chef::Config[:solo] = true } option :client, short: "-z", long: "--client", - description: "#{Chef::Dist::PRODUCT} session", + description: "#{ChefUtils::Dist::Infra::PRODUCT} session", boolean: true option :solo_legacy_shell, long: "--solo-legacy-mode", - description: "#{Chef::Dist::SOLO} legacy session", + description: "#{ChefUtils::Dist::Solo::PRODUCT} legacy session", boolean: true, proc: proc { Chef::Config[:solo_legacy_mode] = true } @@ -299,15 +299,15 @@ module Shell option :chef_server_url, short: "-S CHEFSERVERURL", long: "--server CHEFSERVERURL", - description: "The #{Chef::Dist::SERVER_PRODUCT} URL", + description: "The #{ChefUtils::Dist::Server::PRODUCT} URL", proc: nil option :version, short: "-v", long: "--version", - description: "Show #{Chef::Dist::PRODUCT} version", + description: "Show #{ChefUtils::Dist::Infra::PRODUCT} version", boolean: true, - proc: lambda { |v| puts "#{Chef::Dist::PRODUCT}: #{::Chef::VERSION}" }, + proc: lambda { |v| puts "#{ChefUtils::Dist::Infra::PRODUCT}: #{::Chef::VERSION}" }, exit: 0 option :override_runlist, @@ -356,18 +356,18 @@ module Shell config[:config_file] elsif environment Shell.env = environment - config_file_to_try = ::File.join(dot_chef_dir, environment, Chef::Dist::SHELL_CONF) + config_file_to_try = ::File.join(dot_chef_dir, environment, ChefUtils::Dist::Infra::SHELL_CONF) unless ::File.exist?(config_file_to_try) - puts "could not find #{Chef::Dist::SHELL} config for environment #{environment} at #{config_file_to_try}" + puts "could not find #{ChefUtils::Dist::Infra::SHELL} config for environment #{environment} at #{config_file_to_try}" exit 1 end config_file_to_try - elsif dot_chef_dir && ::File.exist?(File.join(dot_chef_dir, Chef::Dist::SHELL_CONF)) - File.join(dot_chef_dir, Chef::Dist::SHELL_CONF) + elsif dot_chef_dir && ::File.exist?(File.join(dot_chef_dir, ChefUtils::Dist::Infra::SHELL_CONF)) + File.join(dot_chef_dir, ChefUtils::Dist::Infra::SHELL_CONF) elsif config[:solo_legacy_shell] - Chef::Config.platform_specific_path("#{Chef::Dist::CONF_DIR}/solo.rb") + Chef::Config.platform_specific_path("#{ChefConfig::Config.etc_chef_dir}/solo.rb") elsif config[:client] - Chef::Config.platform_specific_path("#{Chef::Dist::CONF_DIR}/client.rb") + Chef::Config.platform_specific_path("#{ChefConfig::Config.etc_chef_dir}/client.rb") elsif config[:solo_shell] Chef::WorkstationConfigLoader.new(nil, Chef::Log).config_location else diff --git a/lib/chef/shell/ext.rb b/lib/chef/shell/ext.rb index f8b8d2e0e3..c840f90aae 100644 --- a/lib/chef/shell/ext.rb +++ b/lib/chef/shell/ext.rb @@ -25,7 +25,7 @@ require_relative "shell_session" require_relative "model_wrapper" require_relative "../server_api" require_relative "../json_compat" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) module Shell module Extensions @@ -69,7 +69,7 @@ module Shell def help_banner banner = [] banner << "" - banner << "#{Chef::Dist::SHELL} Help" + banner << "#{ChefUtils::Dist::Infra::SHELL} Help" banner << "".ljust(80, "=") banner << "| " + "Command".ljust(25) + "| " + "Description" banner << "".ljust(80, "=") @@ -194,7 +194,7 @@ module Shell explain(<<~E) ## SUMMARY ## When called with no argument, +help+ prints a table of all - #{Chef::Dist::SHELL} commands. When called with an argument COMMAND, +help+ + #{ChefUtils::Dist::Infra::SHELL} commands. When called with an argument COMMAND, +help+ prints a detailed explanation of the command if available, or the description if no explanation is available. E @@ -208,9 +208,9 @@ module Shell end alias :halp :help - desc "prints information about #{Chef::Dist::PRODUCT}" + desc "prints information about #{ChefUtils::Dist::Infra::PRODUCT}" def version - puts "Welcome to the #{Chef::Dist::SHELL} #{::Chef::VERSION}\n" + + puts "Welcome to the #{ChefUtils::Dist::Infra::SHELL} #{::Chef::VERSION}\n" + "For usage see https://docs.chef.io/chef_shell/" :ucanhaz_automation end @@ -228,7 +228,7 @@ module Shell :attributes end - desc "run #{Chef::Dist::PRODUCT} using the current recipe" + desc "run #{ChefUtils::Dist::Infra::PRODUCT} using the current recipe" def run_chef Chef::Log.level = :debug session = Shell.session @@ -237,8 +237,8 @@ module Shell runrun end - desc "returns an object to control a paused #{Chef::Dist::PRODUCT} run" - subcommands resume: "resume the #{Chef::Dist::PRODUCT} run", + desc "returns an object to control a paused #{ChefUtils::Dist::Infra::PRODUCT} run" + subcommands resume: "resume the #{ChefUtils::Dist::Infra::PRODUCT} run", step: "run only the next resource", skip_back: "move back in the run list", skip_forward: "move forward in the run list" @@ -309,9 +309,9 @@ module Shell new_node = edit(existing_node) ## EDITOR SELECTION ## - #{Chef::Dist::SHELL} looks for an editor using the following logic + #{ChefUtils::Dist::Infra::SHELL} looks for an editor using the following logic 1. Looks for an EDITOR set by Shell.editor = "EDITOR" - 2. Looks for an EDITOR configured in your #{Chef::Dist::SHELL} config file + 2. Looks for an EDITOR configured in your #{ChefUtils::Dist::Infra::SHELL} config file 3. Uses the value of the EDITOR environment variable E def edit(object) @@ -320,7 +320,7 @@ module Shell return :failburger end - filename = "#{Chef::Dist::SHELL}-edit-#{object.class.name}-" + filename = "#{ChefUtils::Dist::Infra::SHELL}-edit-#{object.class.name}-" if object.respond_to?(:name) filename += object.name elsif object.respond_to?(:id) diff --git a/lib/chef/shell/shell_session.rb b/lib/chef/shell/shell_session.rb index a1957c6667..a17d8bbc84 100644 --- a/lib/chef/shell/shell_session.rb +++ b/lib/chef/shell/shell_session.rb @@ -28,7 +28,7 @@ require_relative "../run_list/run_list_expansion" require_relative "../formatters/base" require_relative "../formatters/doc" require_relative "../formatters/minimal" -require_relative "../dist" +require "chef-utils/dist" unless defined?(ChefUtils::Dist) module Shell class ShellSession @@ -90,7 +90,7 @@ module Shell end def save_node - raise "Not Supported! #{self.class.name} doesn't support #save_node, maybe you need to run #{Chef::Dist::SHELL} in client mode?" + raise "Not Supported! #{self.class.name} doesn't support #save_node, maybe you need to run #{ChefUtils::Dist::Infra::SHELL} in client mode?" end def rebuild_context diff --git a/lib/chef/train_transport.rb b/lib/chef/train_transport.rb index a4f311fc51..4fe1fcadec 100644 --- a/lib/chef/train_transport.rb +++ b/lib/chef/train_transport.rb @@ -15,114 +15,15 @@ # limitations under the License. # -require "chef-config/mixin/credentials" -autoload :Train, "train" -require_relative "dist" +require "chef-config/mixin/train_transport" unless defined?(ChefConfig::Mixin::TrainTransport) class Chef class TrainTransport - extend ChefConfig::Mixin::Credentials + include ChefConfig::Mixin::TrainTransport - # - # Returns a RFC099 credentials profile as a hash - # - def self.load_credentials(profile) - # Tomlrb.load_file returns a hash with keys as strings - credentials = parse_credentials_file - if contains_split_fqdn?(credentials, profile) - Chef::Log.warn("Credentials file #{credentials_file_path} contains target '#{profile}' as a Hash, expected a string.") - Chef::Log.warn("Hostnames must be surrounded by single quotes, e.g. ['host.example.org']") - end - - # host names must be specified in credentials file as ['foo.example.org'] with quotes - if !credentials.nil? && !credentials[profile].nil? - credentials[profile].map { |k, v| [k.to_sym, v] }.to_h # return symbolized keys to match Train.options() - else - nil - end - end - - # Toml creates hashes when a key is separated by periods, e.g. - # [host.example.org] => { host: { example: { org: {} } } } - # - # Returns true if the above example is true - # - # A hostname has to be specified as ['host.example.org'] - # This will be a common mistake so we should catch it - # - def self.contains_split_fqdn?(hash, fqdn) - fqdn.split(".").reduce(hash) do |h, k| - v = h[k] - if Hash === v - v - else - break false - end - end - end - - # ChefConfig::Mixin::Credentials.credentials_file_path is designed around knife, - # overriding it here. - # - # Credentials file preference: - # - # 1) target_mode.credentials_file - # 2) /etc/chef/TARGET_MODE_HOST/credentials - # 3) #credentials_file_path from parent ($HOME/.chef/credentials) - # - def self.credentials_file_path - tm_config = Chef::Config.target_mode - profile = tm_config.host - - credentials_file = - if tm_config.credentials_file && File.exist?(tm_config.credentials_file) - tm_config.credentials_file - elsif File.exist?(Chef::Config.platform_specific_path("#{Chef::Dist::CONF_DIR}/#{profile}/credentials")) - Chef::Config.platform_specific_path("#{Chef::Dist::CONF_DIR}/#{profile}/credentials") - else - super - end - - raise ArgumentError, "No credentials file found for target '#{profile}'" unless credentials_file - raise ArgumentError, "Credentials file specified for target mode does not exist: '#{credentials_file}'" unless File.exist?(credentials_file) - - Chef::Log.debug("Loading credentials file '#{credentials_file}' for target '#{profile}'") - - credentials_file - end - - def self.build_transport(logger = Chef::Log.with_child(subsystem: "transport")) - return nil unless Chef::Config.target_mode? - - # TODO: Consider supporting parsing the protocol from a URI passed to `--target` - # - train_config = {} - - # Load the target_mode config context from Chef::Config, and place any valid settings into the train configuration - tm_config = Chef::Config.target_mode - protocol = tm_config.protocol - train_config = tm_config.to_hash.select { |k| Train.options(protocol).key?(k) } - Chef::Log.trace("Using target mode options from #{Chef::Dist::PRODUCT} config file: #{train_config.keys.join(", ")}") if train_config - - # Load the credentials file, and place any valid settings into the train configuration - credentials = load_credentials(tm_config.host) - if credentials - valid_settings = credentials.select { |k| Train.options(protocol).key?(k) } - valid_settings[:enable_password] = credentials[:enable_password] if credentials.key?(:enable_password) - train_config.merge!(valid_settings) - Chef::Log.trace("Using target mode options from credentials file: #{valid_settings.keys.join(", ")}") if valid_settings - end - - train_config[:logger] = logger - - # Train handles connection retries for us - Train.create(protocol, train_config) - rescue SocketError => e # likely a dns failure, not caught by train - e.message.replace "Error connecting to #{train_config[:target]} - #{e.message}" - raise e - rescue Train::PluginLoadError - logger.error("Invalid target mode protocol: #{protocol}") - exit(false) + def config + require "chef/config" unless defined?(Chef::Config) + Chef::Config end end end diff --git a/lib/chef/util/backup.rb b/lib/chef/util/backup.rb index 5728dcaedd..e739488fb9 100644 --- a/lib/chef/util/backup.rb +++ b/lib/chef/util/backup.rb @@ -36,7 +36,7 @@ class Chef slice_number = @new_resource.backup backup_files = sorted_backup_files if backup_files.length >= @new_resource.backup - remainder = backup_files.slice(slice_number..-1) + remainder = backup_files.slice(slice_number..) remainder.each do |backup_to_delete| delete_backup(backup_to_delete) end diff --git a/lib/chef/util/threaded_job_queue.rb b/lib/chef/util/threaded_job_queue.rb index efbb67216f..bce25e9225 100644 --- a/lib/chef/util/threaded_job_queue.rb +++ b/lib/chef/util/threaded_job_queue.rb @@ -13,8 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -require "thread" - class Chef class Util # A simple threaded job queue diff --git a/lib/chef/version.rb b/lib/chef/version.rb index 34415037c7..ad4190bbb5 100644 --- a/lib/chef/version.rb +++ b/lib/chef/version.rb @@ -23,7 +23,7 @@ require_relative "version_string" class Chef CHEF_ROOT = File.expand_path("..", __dir__) - VERSION = Chef::VersionString.new("16.5.51") + VERSION = Chef::VersionString.new("16.5.77") end # diff --git a/lib/chef/win32/file.rb b/lib/chef/win32/file.rb index e898144414..55fc2461e8 100644 --- a/lib/chef/win32/file.rb +++ b/lib/chef/win32/file.rb @@ -124,7 +124,7 @@ class Chef # Return the link destination (strip off \??\ at the beginning, which is a local filesystem thing) link_dest = reparse_buffer.reparse_buffer.substitute_name if /^\\\?\?\\/.match?(link_dest) - link_dest = link_dest[4..-1] + link_dest = link_dest[4..] end link_dest end diff --git a/lib/chef/win32/unicode.rb b/lib/chef/win32/unicode.rb index f6e97737de..731fe2fbd9 100644 --- a/lib/chef/win32/unicode.rb +++ b/lib/chef/win32/unicode.rb @@ -40,7 +40,7 @@ module FFI last_char = nil while last_char != "\000\000" length += 1 - last_char = get_bytes(0, length * 2)[-2..-1] + last_char = get_bytes(0, length * 2)[-2..] end num_wchars = length diff --git a/omnibus/Gemfile.lock b/omnibus/Gemfile.lock index 4458b409bc..30eca638df 100644 --- a/omnibus/Gemfile.lock +++ b/omnibus/Gemfile.lock @@ -1,9 +1,9 @@ GIT remote: https://github.com/chef/omnibus - revision: 22ce15145e83cefbe8ae8603bacf8a340e274715 + revision: 0f9a7a996f9bb783d7f6faac05959c2d9a295b03 branch: master specs: - omnibus (7.0.24) + omnibus (7.0.25) aws-sdk-s3 (~> 1) chef-cleanroom (~> 1.0) chef-sugar (>= 3.3) @@ -18,7 +18,7 @@ GIT GIT remote: https://github.com/chef/omnibus-software - revision: 0d5f81dc0515357d571e9210031b3fa0edab0903 + revision: 0e0686b82299ca2ddc6b9251319e4309142c4b7d branch: master specs: omnibus-software (4.0.0) @@ -32,16 +32,16 @@ GEM artifactory (3.0.15) awesome_print (1.8.0) aws-eventstream (1.1.0) - aws-partitions (1.366.0) - aws-sdk-core (3.105.0) + aws-partitions (1.376.0) + aws-sdk-core (3.108.0) aws-eventstream (~> 1, >= 1.0.2) aws-partitions (~> 1, >= 1.239.0) aws-sigv4 (~> 1.1) jmespath (~> 1.0) - aws-sdk-kms (1.37.0) + aws-sdk-kms (1.38.0) aws-sdk-core (~> 3, >= 3.99.0) aws-sigv4 (~> 1.1) - aws-sdk-s3 (1.79.1) + aws-sdk-s3 (1.81.1) aws-sdk-core (~> 3, >= 3.104.3) aws-sdk-kms (~> 1) aws-sigv4 (~> 1.1) @@ -64,12 +64,12 @@ GEM solve (~> 4.0) thor (>= 0.20) builder (3.2.4) - chef (16.4.41) + chef (16.5.64) addressable bcrypt_pbkdf (= 1.1.0.rc1) bundler (>= 1.10) - chef-config (= 16.4.41) - chef-utils (= 16.4.41) + chef-config (= 16.5.64) + chef-utils (= 16.5.64) chef-vault chef-zero (>= 14.0.11) diff-lcs (>= 1.2.4, < 1.4.0) @@ -80,7 +80,7 @@ GEM ffi-yajl (~> 2.2) highline (>= 1.6.9, < 3) iniparse (~> 1.4) - license-acceptance (~> 1.0, >= 1.0.5) + license-acceptance (>= 1.0.5, < 3) mixlib-archive (>= 0.4, < 2.0) mixlib-authentication (>= 2.1, < 4) mixlib-cli (>= 2.1.1, < 3.0) @@ -98,13 +98,14 @@ GEM train-winrm (>= 0.2.5) tty-prompt (~> 0.21) tty-screen (~> 0.6) + tty-table (~> 0.11.0) uuidtools (~> 2.1.5) - chef (16.4.41-universal-mingw32) + chef (16.5.64-universal-mingw32) addressable bcrypt_pbkdf (= 1.1.0.rc1) bundler (>= 1.10) - chef-config (= 16.4.41) - chef-utils (= 16.4.41) + chef-config (= 16.5.64) + chef-utils (= 16.5.64) chef-vault chef-zero (>= 14.0.11) diff-lcs (>= 1.2.4, < 1.4.0) @@ -116,7 +117,7 @@ GEM highline (>= 1.6.9, < 3) iniparse (~> 1.4) iso8601 (>= 0.12.1, < 0.14) - license-acceptance (~> 1.0, >= 1.0.5) + license-acceptance (>= 1.0.5, < 3) mixlib-archive (>= 0.4, < 2.0) mixlib-authentication (>= 2.1, < 4) mixlib-cli (>= 2.1.1, < 3.0) @@ -134,6 +135,7 @@ GEM train-winrm (>= 0.2.5) tty-prompt (~> 0.21) tty-screen (~> 0.6) + tty-table (~> 0.11.0) uuidtools (~> 2.1.5) win32-api (~> 1.5.3) win32-certstore (~> 0.3) @@ -146,17 +148,17 @@ GEM win32-taskscheduler (~> 2.0) wmi-lite (~> 1.0) chef-cleanroom (1.0.2) - chef-config (16.4.41) + chef-config (16.5.64) addressable - chef-utils (= 16.4.41) + chef-utils (= 16.5.64) fuzzyurl mixlib-config (>= 2.2.12, < 4.0) mixlib-shellout (>= 2.0, < 4.0) tomlrb (~> 1.2) chef-sugar (5.1.11) - chef-utils (16.4.41) - chef-vault (4.0.11) - chef-zero (15.0.2) + chef-utils (16.5.64) + chef-vault (4.0.12) + chef-zero (15.0.3) ffi-yajl (~> 2.2) hashie (>= 2.0, < 5.0) mixlib-log (>= 2.0, < 4.0) @@ -167,6 +169,7 @@ GEM concurrent-ruby (1.1.7) diff-lcs (1.3) ed25519 (1.2.4) + equatable (0.6.1) erubi (1.9.0) erubis (2.7.0) faraday (1.0.1) @@ -202,7 +205,7 @@ GEM tomlrb (~> 1.2) tty-box (~> 0.3) tty-prompt (~> 0.18) - license_scout (1.1.9) + license_scout (1.1.11) ffi-yajl (~> 2.2) mixlib-shellout (>= 2.2, < 4.0) toml-rb (>= 1, < 3) @@ -224,9 +227,9 @@ GEM mixlib-versioning thor mixlib-log (3.0.9) - mixlib-shellout (3.1.4) + mixlib-shellout (3.1.6) chef-utils - mixlib-shellout (3.1.4-universal-mingw32) + mixlib-shellout (3.1.6-universal-mingw32) chef-utils win32-process (~> 0.8.2) wmi-lite (~> 1.0) @@ -234,6 +237,7 @@ GEM molinillo (0.6.6) multi_json (1.15.0) multipart-post (2.1.1) + necromancer (0.5.1) net-scp (3.0.0) net-ssh (>= 2.6.5, < 7.0.0) net-sftp (3.0.0) @@ -248,7 +252,7 @@ GEM octokit (4.18.0) faraday (>= 0.9) sawyer (~> 0.8.0, >= 0.5.3) - ohai (16.5.0) + ohai (16.5.6) chef-config (>= 12.8, < 17) chef-utils (>= 16.0, < 17) ffi (~> 1.9) @@ -260,7 +264,8 @@ GEM mixlib-shellout (>= 2.0, < 4.0) plist (~> 3.1) wmi-lite (~> 1.0) - pastel (0.8.0) + pastel (0.7.4) + equatable (~> 0.6) tty-color (~> 0.5) pedump (0.6.1) awesome_print @@ -284,14 +289,14 @@ GEM solve (4.0.4) molinillo (~> 0.6) semverse (>= 1.1, < 4.0) - strings (0.2.0) - strings-ansi (~> 0.2) + strings (0.1.8) + strings-ansi (~> 0.1) unicode-display_width (~> 1.5) unicode_utils (~> 1.4) strings-ansi (0.2.0) structured_warnings (0.4.0) syslog-logger (1.6.8) - test-kitchen (2.7.0) + test-kitchen (2.7.1) bcrypt_pbkdf (~> 1.0) ed25519 (~> 1.2) license-acceptance (>= 1.0.11, < 3.0) @@ -308,7 +313,7 @@ GEM toml-rb (2.0.1) citrus (~> 3.0, > 3.0) tomlrb (1.3.0) - train-core (3.3.16) + train-core (3.3.21) addressable (~> 2.5) ffi (!= 1.13.0) json (>= 1.8, < 3.0) @@ -318,20 +323,27 @@ GEM train-winrm (0.2.6) winrm (~> 2.0) winrm-fs (~> 1.0) - tty-box (0.6.0) - pastel (~> 0.8) - strings (~> 0.2.0) + tty-box (0.5.0) + pastel (~> 0.7.2) + strings (~> 0.1.6) tty-cursor (~> 0.7) tty-color (0.5.2) tty-cursor (0.7.1) - tty-prompt (0.22.0) - pastel (~> 0.8) - tty-reader (~> 0.8) - tty-reader (0.8.0) + tty-prompt (0.21.0) + necromancer (~> 0.5.0) + pastel (~> 0.7.0) + tty-reader (~> 0.7.0) + tty-reader (0.7.0) tty-cursor (~> 0.7) - tty-screen (~> 0.8) - wisper (~> 2.0) + tty-screen (~> 0.7) + wisper (~> 2.0.0) tty-screen (0.8.1) + tty-table (0.11.0) + equatable (~> 0.6) + necromancer (~> 0.5) + pastel (~> 0.7.2) + strings (~> 0.1.5) + tty-screen (~> 0.7) unicode-display_width (1.7.0) unicode_utils (1.4.0) uuidtools (2.1.5) @@ -366,11 +378,11 @@ GEM logging (>= 1.6.1, < 3.0) nori (~> 2.0) rubyntlm (~> 0.6.0, >= 0.6.1) - winrm-elevated (1.2.1) + winrm-elevated (1.2.2) erubi (~> 1.8) winrm (~> 2.0) winrm-fs (~> 1.0) - winrm-fs (1.3.4) + winrm-fs (1.3.5) erubi (~> 1.8) logging (>= 1.6.1, < 3.0) rubyzip (~> 2.0) diff --git a/spec/functional/event_loggers/windows_eventlog_spec.rb b/spec/functional/event_loggers/windows_eventlog_spec.rb index 2ebf45fb84..b9f10fd4dc 100644 --- a/spec/functional/event_loggers/windows_eventlog_spec.rb +++ b/spec/functional/event_loggers/windows_eventlog_spec.rb @@ -19,6 +19,7 @@ require "spec_helper" require "securerandom" require "chef/event_loggers/windows_eventlog" +require "chef-utils" if ChefUtils.windows? require "win32/eventlog" include Win32 @@ -49,7 +50,7 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only do logger.run_start(version, run_status) expect(event_log.read(flags, offset).any? do |e| - e.source == Chef::Dist::SHORT && e.event_id == 10000 && + e.source == ChefUtils::Dist::Infra::SHORT && e.event_id == 10000 && e.string_inserts[0].include?(version) end ).to be_truthy end @@ -58,7 +59,7 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only do logger.run_started(run_status) expect(event_log.read(flags, offset).any? do |e| - e.source == Chef::Dist::SHORT && e.event_id == 10001 && + e.source == ChefUtils::Dist::Infra::SHORT && e.event_id == 10001 && e.string_inserts[0].include?(run_id) end ).to be_truthy end @@ -68,7 +69,7 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only do logger.run_completed(node) expect(event_log.read(flags, offset).any? do |e| - e.source == Chef::Dist::SHORT && e.event_id == 10002 && + e.source == ChefUtils::Dist::Infra::SHORT && e.event_id == 10002 && e.string_inserts[0].include?(run_id) && e.string_inserts[1].include?(elapsed_time.to_s) end).to be_truthy @@ -79,7 +80,7 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only do logger.run_failed(mock_exception) expect(event_log.read(flags, offset).any? do |e| - e.source == Chef::Dist::SHORT && e.event_id == 10003 && + e.source == ChefUtils::Dist::Infra::SHORT && e.event_id == 10003 && e.string_inserts[0].include?(run_id) && e.string_inserts[1].include?(elapsed_time.to_s) && e.string_inserts[2].include?(mock_exception.class.name) && @@ -93,7 +94,7 @@ describe Chef::EventLoggers::WindowsEventLogger, :windows_only do logger.run_failed(mock_exception) expect(event_log.read(flags, offset).any? do |e| - e.source == Chef::Dist::SHORT && e.event_id == 10003 && + e.source == ChefUtils::Dist::Infra::SHORT && e.event_id == 10003 && e.string_inserts[0].include?("UNKNOWN") && e.string_inserts[1].include?("UNKNOWN") && e.string_inserts[2].include?(mock_exception.class.name) && diff --git a/spec/functional/resource/windows_task_spec.rb b/spec/functional/resource/windows_task_spec.rb index 196e627272..97ab66c7f5 100644 --- a/spec/functional/resource/windows_task_spec.rb +++ b/spec/functional/resource/windows_task_spec.rb @@ -18,7 +18,7 @@ require "spec_helper" require "chef/provider/windows_task" -require "chef/dist" +require "chef-utils/dist" describe Chef::Resource::WindowsTask, :windows_only do # resource.task.application_name will default to task_name unless resource.command is set @@ -47,37 +47,37 @@ describe Chef::Resource::WindowsTask, :windows_only do context "With Arguments" do it "creates scheduled task and sets command arguments" do - subject.command "#{Chef::Dist::CLIENT} -W" + subject.command "#{ChefUtils::Dist::Infra::CLIENT} -W" call_for_create_action # loading current resource again to check new task is creted and it matches task parameters current_resource = call_for_load_current_resource expect(current_resource.exists).to eq(true) - expect(current_resource.task.application_name).to eq(Chef::Dist::CLIENT) + expect(current_resource.task.application_name).to eq(ChefUtils::Dist::Infra::CLIENT) expect(current_resource.task.parameters).to eq("-W") end it "does not converge the resource if it is already converged" do - subject.command "#{Chef::Dist::CLIENT} -W" + subject.command "#{ChefUtils::Dist::Infra::CLIENT} -W" subject.run_action(:create) - subject.command "#{Chef::Dist::CLIENT} -W" + subject.command "#{ChefUtils::Dist::Infra::CLIENT} -W" subject.run_action(:create) expect(subject).not_to be_updated_by_last_action end it "creates scheduled task and sets command arguments when arguments inclusive single quotes" do - subject.command "#{Chef::Dist::CLIENT} -W -L 'C:\\chef\\chef-ad-join.log'" + subject.command "#{ChefUtils::Dist::Infra::CLIENT} -W -L 'C:\\chef\\chef-ad-join.log'" call_for_create_action # loading current resource again to check new task is creted and it matches task parameters current_resource = call_for_load_current_resource expect(current_resource.exists).to eq(true) - expect(current_resource.task.application_name).to eq(Chef::Dist::CLIENT) + expect(current_resource.task.application_name).to eq(ChefUtils::Dist::Infra::CLIENT) expect(current_resource.task.parameters).to eq("-W -L 'C:\\chef\\chef-ad-join.log'") end it "does not converge the resource if it is already converged" do - subject.command "#{Chef::Dist::CLIENT} -W -L 'C:\\chef\\chef-ad-join.log'" + subject.command "#{ChefUtils::Dist::Infra::CLIENT} -W -L 'C:\\chef\\chef-ad-join.log'" subject.run_action(:create) - subject.command "#{Chef::Dist::CLIENT} -W -L 'C:\\chef\\chef-ad-join.log'" + subject.command "#{ChefUtils::Dist::Infra::CLIENT} -W -L 'C:\\chef\\chef-ad-join.log'" subject.run_action(:create) expect(subject).not_to be_updated_by_last_action end @@ -137,19 +137,19 @@ describe Chef::Resource::WindowsTask, :windows_only do context "Without Arguments" do it "creates scheduled task and sets command arguments" do - subject.command Chef::Dist::CLIENT + subject.command ChefUtils::Dist::Infra::CLIENT call_for_create_action # loading current resource again to check new task is creted and it matches task parameters current_resource = call_for_load_current_resource expect(current_resource.exists).to eq(true) - expect(current_resource.task.application_name).to eq(Chef::Dist::CLIENT) + expect(current_resource.task.application_name).to eq(ChefUtils::Dist::Infra::CLIENT) expect(current_resource.task.parameters).to be_empty end it "does not converge the resource if it is already converged" do - subject.command Chef::Dist::CLIENT + subject.command ChefUtils::Dist::Infra::CLIENT subject.run_action(:create) - subject.command Chef::Dist::CLIENT + subject.command ChefUtils::Dist::Infra::CLIENT subject.run_action(:create) expect(subject).not_to be_updated_by_last_action end diff --git a/spec/functional/version_spec.rb b/spec/functional/version_spec.rb index 294df7542c..5d0f0fce43 100644 --- a/spec/functional/version_spec.rb +++ b/spec/functional/version_spec.rb @@ -19,13 +19,13 @@ require "spec_helper" require "chef/mixin/shell_out" require "chef/version" require "ohai/version" -require "chef/dist" +require "chef-utils/dist" describe "Chef Versions", :executables do include Chef::Mixin::ShellOut let(:chef_dir) { File.join(__dir__, "..", "..") } - binaries = [ Chef::Dist::CLIENT, "chef-shell", "chef-apply", "knife", Chef::Dist::SOLOEXEC ] + binaries = [ ChefUtils::Dist::Infra::CLIENT, "chef-shell", "chef-apply", "knife", ChefUtils::Dist::Solo::EXEC ] binaries.each do |binary| it "#{binary} version should be sane" do diff --git a/spec/integration/client/client_spec.rb b/spec/integration/client/client_spec.rb index a33f84610d..71f517141e 100644 --- a/spec/integration/client/client_spec.rb +++ b/spec/integration/client/client_spec.rb @@ -3,7 +3,7 @@ require "support/shared/integration/integration_helper" require "chef/mixin/shell_out" require "tiny_server" require "tmpdir" -require "chef/dist" +require "chef-utils/dist" describe "chef-client" do @@ -45,8 +45,8 @@ describe "chef-client" do # machine that has omnibus chef installed. In that case we need to ensure # we're running `chef-client` from the source tree and not the external one. # cf. CHEF-4914 - let(:chef_client) { "bundle exec #{Chef::Dist::CLIENT} --minimal-ohai" } - let(:chef_solo) { "bundle exec #{Chef::Dist::SOLOEXEC} --legacy-mode --minimal-ohai" } + let(:chef_client) { "bundle exec #{ChefUtils::Dist::Infra::CLIENT} --minimal-ohai" } + let(:chef_solo) { "bundle exec #{ChefUtils::Dist::Solo::EXEC} --legacy-mode --minimal-ohai" } when_the_repository "has a cookbook with a no-op recipe" do before { file "cookbooks/x/recipes/default.rb", "" } diff --git a/spec/integration/client/exit_code_spec.rb b/spec/integration/client/exit_code_spec.rb index c2f0c2fb45..53a8f1f895 100644 --- a/spec/integration/client/exit_code_spec.rb +++ b/spec/integration/client/exit_code_spec.rb @@ -5,6 +5,7 @@ require "chef/mixin/shell_out" require "tiny_server" require "tmpdir" require "chef/platform" +require "chef-utils/dist" describe "chef-client" do @@ -22,7 +23,7 @@ describe "chef-client" do # machine that has omnibus chef installed. In that case we need to ensure # we're running `chef-client` from the source tree and not the external one. # cf. CHEF-4914 - let(:chef_client) { "bundle exec #{Chef::Dist::CLIENT} --no-fork --minimal-ohai" } + let(:chef_client) { "bundle exec #{ChefUtils::Dist::Infra::CLIENT} --no-fork --minimal-ohai" } let(:critical_env_vars) { %w{PATH RUBYOPT BUNDLE_GEMFILE GEM_PATH}.map { |o| "#{o}=#{ENV[o]}" } .join(" ") } diff --git a/spec/integration/solo/solo_spec.rb b/spec/integration/solo/solo_spec.rb index 75a13b57e4..12a49dade6 100644 --- a/spec/integration/solo/solo_spec.rb +++ b/spec/integration/solo/solo_spec.rb @@ -5,10 +5,10 @@ require "chef/run_lock" require "chef/config" require "timeout" require "fileutils" +require "chef-utils" require "chef/win32/security" if ChefUtils.windows? -require "chef/dist" -describe Chef::Dist::SOLOEXEC do +describe ChefUtils::Dist::Solo::EXEC do include IntegrationSupport include Chef::Mixin::ShellOut @@ -18,7 +18,7 @@ describe Chef::Dist::SOLOEXEC do let(:cookbook_ancient_100_metadata_rb) { cb_metadata("ancient", "1.0.0") } - let(:chef_solo) { "bundle exec #{Chef::Dist::SOLOEXEC} --legacy-mode --minimal-ohai" } + let(:chef_solo) { "bundle exec #{ChefUtils::Dist::Solo::EXEC} --legacy-mode --minimal-ohai" } when_the_repository "creates nodes" do let(:nodes_dir) { File.join(@repository_dir, "nodes") } diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 5766af8954..b0a56f4b7f 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -68,7 +68,7 @@ end # If you want to load anything into the testing environment # without versioning it, add it to spec/support/local_gems.rb -require "spec/support/local_gems.rb" if File.exist?(File.join(File.dirname(__FILE__), "support", "local_gems.rb")) +require "spec/support/local_gems" if File.exist?(File.join(File.dirname(__FILE__), "support", "local_gems.rb")) # Explicitly require spec helpers that need to load first require "spec/support/platform_helpers" @@ -309,8 +309,6 @@ RSpec.configure do |config| end require "webrick/utils" -require "thread" - # Webrick uses a centralized/synchronized timeout manager. It works by # starting a thread to check for timeouts on an interval. The timeout # checker thread cannot be stopped or canceled in any easy way, and it diff --git a/spec/support/shared/functional/securable_resource.rb b/spec/support/shared/functional/securable_resource.rb index 26f2b1cc5a..4d3a1f2fe6 100644 --- a/spec/support/shared/functional/securable_resource.rb +++ b/spec/support/shared/functional/securable_resource.rb @@ -242,48 +242,100 @@ shared_examples_for "a securable resource with existing target" do include_context "use Windows permissions" describe "when setting owner" do - before do - resource.owner(SID.admin_account_name) - resource.run_action(:create) - end + context "with user name" do + before do + resource.owner(SID.admin_account_name) + resource.run_action(:create) + end - it "should set the owner" do - expect(descriptor.owner).to eq(SID.Administrator) + it "should set the owner" do + expect(descriptor.owner).to eq(SID.Administrator) + end + + it "is marked as updated only if changes are made" do + expect(resource.updated_by_last_action?).to eq(expect_updated?) + end end - it "is marked as updated only if changes are made" do - expect(resource.updated_by_last_action?).to eq(expect_updated?) + context "with SID" do + before do + resource.owner(SID.Administrator.to_s) + resource.run_action(:create) + end + + it "should set the owner" do + expect(descriptor.owner).to eq(SID.Administrator) + end + + it "is marked as updated only if changes are made" do + expect(resource.updated_by_last_action?).to eq(expect_updated?) + end end end describe "when setting group" do - before do - resource.group("Administrators") - resource.run_action(:create) - end + context "with group name" do + before do + resource.group("Administrators") + resource.run_action(:create) + end + + it "should set the group" do + expect(descriptor.group).to eq(SID.Administrators) + end - it "should set the group" do - expect(descriptor.group).to eq(SID.Administrators) + it "is marked as updated only if changes are made" do + expect(resource.updated_by_last_action?).to eq(expect_updated?) + end end - it "is marked as updated only if changes are made" do - expect(resource.updated_by_last_action?).to eq(expect_updated?) + context "with group SID" do + before do + resource.group(SID.Administrators.to_s) + resource.run_action(:create) + end + + it "should set the group" do + expect(descriptor.group).to eq(SID.Administrators) + end + + it "is marked as updated only if changes are made" do + expect(resource.updated_by_last_action?).to eq(expect_updated?) + end end end describe "when setting rights and deny_rights" do - before do - resource.deny_rights(:modify, "Guest") - resource.rights(:read, "Guest") - resource.run_action(:create) - end + context "with user name" do + before do + resource.deny_rights(:modify, "Guest") + resource.rights(:read, "Guest") + resource.run_action(:create) + end - it "should set the rights and deny_rights" do - expect(explicit_aces).to eq(denied_acl(SID.Guest, expected_modify_perms) + allowed_acl(SID.Guest, expected_read_perms)) + it "should set the rights and deny_rights" do + expect(explicit_aces).to eq(denied_acl(SID.Guest, expected_modify_perms) + allowed_acl(SID.Guest, expected_read_perms)) + end + + it "is marked as updated only if changes are made" do + expect(resource.updated_by_last_action?).to eq(expect_updated?) + end end - it "is marked as updated only if changes are made" do - expect(resource.updated_by_last_action?).to eq(expect_updated?) + context "with SID" do + before do + resource.deny_rights(:modify, SID.Guest.to_s) + resource.rights(:read, SID.Guest.to_s) + resource.run_action(:create) + end + + it "should set the rights and deny_rights" do + expect(explicit_aces).to eq(denied_acl(SID.Guest, expected_modify_perms) + allowed_acl(SID.Guest, expected_read_perms)) + end + + it "is marked as updated only if changes are made" do + expect(resource.updated_by_last_action?).to eq(expect_updated?) + end end end end @@ -302,12 +354,18 @@ shared_examples_for "a securable resource without existing target" do expect(descriptor.owner).to eq(SID.default_security_object_owner) end - it "sets owner when owner is specified" do + it "sets owner when owner is specified by name" do resource.owner "Guest" resource.run_action(:create) expect(descriptor.owner).to eq(SID.Guest) end + it "sets owner when owner is specified by SID" do + resource.owner SID.Guest.to_s + resource.run_action(:create) + expect(descriptor.owner).to eq(SID.Guest) + end + it "fails to set owner when owner has invalid characters" do expect { resource.owner 'Lance "The Nose" Glindenberry III' }.to raise_error(Chef::Exceptions::ValidationFailed) end @@ -339,12 +397,18 @@ shared_examples_for "a securable resource without existing target" do expect(descriptor.group).to eq(SID.default_security_object_group) end - it "sets group when group is specified" do + it "sets group when group is specified by name" do resource.group "Everyone" resource.run_action(:create) expect(descriptor.group).to eq(SID.Everyone) end + it "sets group when group is specified by SID" do + resource.group SID.Everyone.to_s + resource.run_action(:create) + expect(descriptor.group).to eq(SID.Everyone) + end + it "fails to set group when group has invalid characters" do expect { resource.group 'Lance "The Nose" Glindenberry III' }.to raise_error(Chef::Exceptions::ValidationFailed) end @@ -406,6 +470,17 @@ shared_examples_for "a securable resource without existing target" do allowed_acl(SID.Guest, expected_modify_perms) ) end + + it "multiple rights with SID" do + resource.rights(:read, SID.Everyone.to_s) + resource.rights(:modify, SID.Guest.to_s) + resource.run_action(:create) + + expect(explicit_aces).to eq( + allowed_acl(SID.Everyone, expected_read_perms) + + allowed_acl(SID.Guest, expected_modify_perms) + ) + end end end @@ -443,6 +518,12 @@ shared_examples_for "a securable resource without existing target" do expect(explicit_aces).to eq(denied_acl(SID.Guest, expected_full_control_perms)) end + it "using SID" do + resource.deny_rights(:full_control, SID.Guest.to_s) + resource.run_action(:create) + expect(explicit_aces).to eq(denied_acl(SID.Guest, expected_full_control_perms)) + end + it "deny_rights ahead of rights" do resource.rights(:read, "Everyone") resource.deny_rights(:modify, "Guest") diff --git a/spec/support/shared/unit/application_dot_d.rb b/spec/support/shared/unit/application_dot_d.rb index 6d722e3734..692b0f99e1 100644 --- a/spec/support/shared/unit/application_dot_d.rb +++ b/spec/support/shared/unit/application_dot_d.rb @@ -38,7 +38,7 @@ shared_examples_for "an application that loads a dot d" do end it "loads the configuration in order" do - etc_chef_client_rb = Chef::Config.platform_specific_path("#{Chef::Dist::CONF_DIR}/client.rb") + etc_chef_client_rb = Chef::Config.platform_specific_path("#{ChefConfig::Config.etc_chef_dir}/client.rb") expect(IO).to receive(:read).with(Pathname.new("#{client_d_dir}/00-foo.rb").cleanpath.to_s).and_return("foo 0") expect(IO).to receive(:read).with(Pathname.new("#{client_d_dir}/01-bar.rb").cleanpath.to_s).and_return("bar 0") expect(IO).to receive(:read).with(Pathname.new("#{client_d_dir}/02-strings.rb").cleanpath.to_s).and_return("strings 0") diff --git a/spec/tiny_server.rb b/spec/tiny_server.rb index 868933b042..786130d0d5 100644 --- a/spec/tiny_server.rb +++ b/spec/tiny_server.rb @@ -19,7 +19,6 @@ require "webrick" require "webrick/https" require "rack" -require "thread" require "singleton" require "open-uri" require "chef/config" diff --git a/spec/unit/chef_fs/config_spec.rb b/spec/unit/chef_fs/config_spec.rb index 848e789d3c..fc44374ae7 100644 --- a/spec/unit/chef_fs/config_spec.rb +++ b/spec/unit/chef_fs/config_spec.rb @@ -18,7 +18,7 @@ require "spec_helper" require "chef/exceptions" -require "lib/chef/chef_fs/config.rb" +require "lib/chef/chef_fs/config" describe Chef::ChefFS::Config do describe "initialize" do diff --git a/spec/unit/chef_fs/data_handler/data_bag_item_data_handler.rb b/spec/unit/chef_fs/data_handler/data_bag_item_data_handler.rb index a0c7d540ec..b85d811003 100644 --- a/spec/unit/chef_fs/data_handler/data_bag_item_data_handler.rb +++ b/spec/unit/chef_fs/data_handler/data_bag_item_data_handler.rb @@ -17,7 +17,7 @@ # require "spec_helper" -require "lib/chef/chef_fs/data_handler/data_bag_item_data_handler.rb" +require "lib/chef/chef_fs/data_handler/data_bag_item_data_handler" class TestDataBag < Mash attr_accessor :name diff --git a/spec/unit/cookbook/synchronizer_spec.rb b/spec/unit/cookbook/synchronizer_spec.rb index a1d312836b..8df5c1d73f 100644 --- a/spec/unit/cookbook/synchronizer_spec.rb +++ b/spec/unit/cookbook/synchronizer_spec.rb @@ -1,7 +1,7 @@ require "spec_helper" require "chef/cookbook/synchronizer" require "chef/cookbook_version" -require "chef/dist" +require "chef-utils/dist" describe Chef::CookbookCacheCleaner do describe "when cleaning up unused cookbook components" do @@ -50,7 +50,7 @@ describe Chef::CookbookCacheCleaner do cleaner.cleanup_file_cache end - it "does not remove anything on #{Chef::Dist::SOLOEXEC}" do + it "does not remove anything on #{ChefUtils::Dist::Solo::EXEC}" do Chef::Config[:solo_legacy_mode] = true allow(cleaner.cache).to receive(:find).and_return(%w{cookbooks/valid1/recipes/default.rb cookbooks/valid2/recipes/default.rb}) expect(cleaner.cache).not_to receive(:delete) diff --git a/spec/unit/data_collector_spec.rb b/spec/unit/data_collector_spec.rb index 6d9d5e2379..63531663ee 100644 --- a/spec/unit/data_collector_spec.rb +++ b/spec/unit/data_collector_spec.rb @@ -26,10 +26,6 @@ require "socket" # actually running -- another testing requirement similar to the integration testing framework in cheffish as well) # describe Chef::DataCollector do - before(:each) do - Chef::Config[:enable_reporting] = true - end - let(:node) { Chef::Node.new } let(:rest_client) { double("Chef::ServerAPI (mock)") } diff --git a/spec/unit/mixin/openssl_helper_spec.rb b/spec/unit/mixin/openssl_helper_spec.rb index 1cd3960757..7c12037798 100644 --- a/spec/unit/mixin/openssl_helper_spec.rb +++ b/spec/unit/mixin/openssl_helper_spec.rb @@ -99,7 +99,7 @@ describe Chef::Mixin::OpenSSLHelper do context "When the dhparam.pem file does exist, and does contain a vaild dhparam key" do it "returns true" do - @dhparam_file.puts(::OpenSSL::PKey::DH.new(1024).to_pem) + @dhparam_file.puts(::OpenSSL::PKey::DH.new(256).to_pem) # this is 256 to speed up specs @dhparam_file.close expect(instance.dhparam_pem_valid?(@dhparam_file.path)).to be_truthy end diff --git a/spec/unit/resource/osx_profile_spec.rb b/spec/unit/resource/osx_profile_spec.rb index 7e2173f823..c6909a842d 100644 --- a/spec/unit/resource/osx_profile_spec.rb +++ b/spec/unit/resource/osx_profile_spec.rb @@ -102,6 +102,72 @@ describe Chef::Resource::OsxProfile do "ProfileVersion" => 1 }], } end + let(:profile_raw_xml) do + <<~OUT + <?xml version="1.0" encoding="UTF-8"?> + <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> + <plist version="1.0"> + <dict> + <key>tsmith</key> + <array> + <dict> + <key>ProfileDisplayName</key> + <string>Screensaver Settings</string> + <key>ProfileIdentifier</key> + <string>com.company.screensaver</string> + <key>ProfileInstallDate</key> + <string>2020-09-17 17:20:49 +0000</string> + <key>ProfileItems</key> + <array> + <dict> + <key>PayloadContent</key> + <dict> + <key>PayloadContentManagedPreferences</key> + <dict> + <key>com.apple.screensaver</key> + <dict> + <key>Forced</key> + <array> + <dict> + <key>mcx_preference_settings</key> + <dict> + <key>idleTime</key> + <integer>0</integer> + </dict> + </dict> + </array> + </dict> + </dict> + </dict> + <key>PayloadDisplayName</key> + <string>com.apple.screensaver</string> + <key>PayloadIdentifier</key> + <string>com.company.screensaver</string> + <key>PayloadType</key> + <string>com.apple.ManagedClient.preferences</string> + <key>PayloadUUID</key> + <string>73fc30e0-1e57-0131-c32d-000c2944c108</string> + <key>PayloadVersion</key> + <integer>1</integer> + </dict> + </array> + <key>ProfileOrganization</key> + <string>Chef</string> + <key>ProfileType</key> + <string>Configuration</string> + <key>ProfileUUID</key> + <string>ed5e36c8-ea0b-5960-8f49-3c7d9121687e</string> + <key>ProfileVersion</key> + <integer>1</integer> + </dict> + </array> + </dict> + </plist> + OUT + end + let(:shell_out_profiles) do + double("shell_out", exitstatus: 0, error?: false, stdout: profile_raw_xml) + end # If anything is changed within this profile, be sure to update the # ProfileUUID in all_profiles to match the new config specific UUID let(:test_profile) do @@ -155,7 +221,7 @@ describe Chef::Resource::OsxProfile do resource.profile_name profile_name allow(provider).to receive(:get_installed_profiles).and_call_original allow(provider).to receive(:read_plist).and_return(all_profiles) - expect(provider).to receive(:shell_out_compacted).with("/usr/bin/profiles", "-P", "-o", kind_of(String)) + expect(provider).to receive(:shell_out_compacted).with("/usr/bin/profiles", "-P", "-o", "stdout-xml").and_return(shell_out_profiles) provider.load_current_resource end diff --git a/spec/unit/resource/windows_uac_spec.rb b/spec/unit/resource/windows_uac_spec.rb index a82ca65421..48f2f33a16 100644 --- a/spec/unit/resource/windows_uac_spec.rb +++ b/spec/unit/resource/windows_uac_spec.rb @@ -44,7 +44,7 @@ describe Chef::Resource::WindowsUac do expect { resource.consent_behavior_users :bogus }.to raise_error(ArgumentError) end - it "sets the default action as :create" do + it "sets the default action as :configure" do expect(resource.action).to eql([:configure]) end end diff --git a/spec/unit/resource/windows_user_privilege_spec.rb b/spec/unit/resource/windows_user_privilege_spec.rb new file mode 100644 index 0000000000..73c800c8bd --- /dev/null +++ b/spec/unit/resource/windows_user_privilege_spec.rb @@ -0,0 +1,55 @@ +# +# Copyright:: Copyright (c) Chef Software Inc. +# License:: Apache License, Version 2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +require "spec_helper" + +describe Chef::Resource::WindowsUserPrivilege do + let(:resource) { Chef::Resource::WindowsUserPrivilege.new("fakey_fakerton") } + + it "sets resource name as :windows_user_privilege" do + expect(resource.resource_name).to eql(:windows_user_privilege) + end + + it "the principal property is the name_property" do + expect(resource.principal).to eql("fakey_fakerton") + end + + it "the users property coerces to an array" do + resource.users "Administrator" + expect(resource.users).to eql(["Administrator"]) + end + + it "the privilege property coerces to an array" do + resource.privilege "SeDenyRemoteInteractiveLogonRight" + expect(resource.privilege).to eql(["SeDenyRemoteInteractiveLogonRight"]) + end + + it "the privilege property validates inputs against the allowed list of privs" do + expect { resource.privilege "invalidPriv" }.to raise_error(Chef::Exceptions::ValidationFailed) + end + + it "sets the default action as :add" do + expect(resource.action).to eql([:add]) + end + + it "supports :add, :set, :clear, :remove actions" do + expect { resource.action :add }.not_to raise_error + expect { resource.action :set }.not_to raise_error + expect { resource.action :clear }.not_to raise_error + expect { resource.action :remove }.not_to raise_error + end +end diff --git a/spec/unit/runner_spec.rb b/spec/unit/runner_spec.rb index 0dd8d43136..500ec13f7b 100644 --- a/spec/unit/runner_spec.rb +++ b/spec/unit/runner_spec.rb @@ -111,8 +111,7 @@ describe Chef::Runner do it "should use the provider specified by the resource (if it has one)" do provider = Chef::Provider::Easy.new(run_context.resource_collection[0], run_context) - # Expect provider to be called twice, because will fall back to old provider lookup - expect(run_context.resource_collection[0]).to receive(:provider).twice.and_return(Chef::Provider::Easy) + expect(run_context.resource_collection[0]).to receive(:provider).once.and_return(Chef::Provider::Easy) expect(Chef::Provider::Easy).to receive(:new).once.and_return(provider) runner.converge end diff --git a/spec/unit/train_transport_spec.rb b/spec/unit/train_transport_spec.rb index 0922c5b00d..d0724911cb 100644 --- a/spec/unit/train_transport_spec.rb +++ b/spec/unit/train_transport_spec.rb @@ -19,32 +19,33 @@ require "spec_helper" describe Chef::TrainTransport do + let(:transport) { Chef::TrainTransport.new(Chef::Log) } + describe "load_credentials" do - let(:transport) { Chef::TrainTransport.new } let(:good_credentials) { { "switch.cisco.com" => { "user" => "cisco", "password" => "cisco", "enable_password" => "secret" } } } before do - allow(Chef::TrainTransport).to receive(:parse_credentials_file).and_return(good_credentials) + allow(transport).to receive(:parse_credentials_file).and_return(good_credentials) end it "matches credentials when they exist" do - expect(Chef::TrainTransport.load_credentials("switch.cisco.com")[:user]).to eq("cisco") - expect(Chef::TrainTransport.load_credentials("switch.cisco.com")[:password]).to eq("cisco") - expect(Chef::TrainTransport.load_credentials("switch.cisco.com")[:enable_password]).to eq("secret") + expect(transport.load_credentials("switch.cisco.com")[:user]).to eq("cisco") + expect(transport.load_credentials("switch.cisco.com")[:password]).to eq("cisco") + expect(transport.load_credentials("switch.cisco.com")[:enable_password]).to eq("secret") end it "returns nil if there is no match" do - expect(Chef::TrainTransport.load_credentials("router.unicorns.com")).to be_nil + expect(transport.load_credentials("router.unicorns.com")).to be_nil end # [foo.example.org] => {"foo"=>{"example"=>{"org"=>{}}}} # ['foo.example.org'] => {"foo.example.org"=>{}} it "warns if the host has been split by toml" do - allow(Chef::TrainTransport).to receive(:credentials_file_path).and_return("/Users/scotthourglass/.chef/credentials") - allow(Chef::TrainTransport).to receive(:parse_credentials_file).and_return({ "foo" => { "example" => { "org" => {} } } }) + allow(transport).to receive(:credentials_file_path).and_return("/Users/scotthourglass/.chef/credentials") + allow(transport).to receive(:parse_credentials_file).and_return({ "foo" => { "example" => { "org" => {} } } }) expect(Chef::Log).to receive(:warn).with(/as a Hash/) expect(Chef::Log).to receive(:warn).with(/Hostnames must be surrounded by single quotes/) - expect(Chef::TrainTransport.load_credentials("foo.example.org")).to be_nil + expect(transport.load_credentials("foo.example.org")).to be_nil end end @@ -60,25 +61,25 @@ describe Chef::TrainTransport do it "returns the path if it exists" do allow(File).to receive(:exist?).with(config_cred_file_path).and_return(true) - expect(Chef::TrainTransport.credentials_file_path).to eq(config_cred_file_path) + expect(transport.credentials_file_path).to eq(config_cred_file_path) end it "raises an error if it does not exist" do allow(File).to receive(:exist?).and_return(false) - expect { Chef::TrainTransport.credentials_file_path }.to raise_error(ArgumentError, /does not exist/) + expect { transport.credentials_file_path }.to raise_error(ArgumentError, /does not exist/) end end it "raises an error if the default creds files do not exist" do allow(File).to receive(:exist?).and_return(false) - expect { Chef::TrainTransport.credentials_file_path }.to raise_error(ArgumentError, /does not exist/) + expect { transport.credentials_file_path }.to raise_error(ArgumentError, /does not exist/) end it "returns the path to the default config file if it exists" do tm_config = double("Config Context", host: "foo.example.org", credentials_file: nil) allow(Chef::Config).to receive(:target_mode).and_return(tm_config) allow(File).to receive(:exist?).with(host_cred_file_path).and_return(true) - expect(Chef::TrainTransport.credentials_file_path).to eq(host_cred_file_path) + expect(transport.credentials_file_path).to eq(host_cred_file_path) end end end diff --git a/tasks/docs.rb b/tasks/docs.rb index 586115f2f9..ff5a38afda 100755 --- a/tasks/docs.rb +++ b/tasks/docs.rb @@ -190,13 +190,7 @@ namespace :docs_site do properties["properties_resources_common_windows_security"] = true if %w{cookbook_file file template remote_file directory}.include?(name) - properties["properties_shortcode"] = - case name - when "ohai" - "resource_ohai_properties.md" - when "log" - "resource_log_properties.md" - end + properties["properties_shortcode"] = "resource_log_properties.md" if name == "log" properties["ps_credential_helper"] = true if name == "dsc_script" |