summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNathen Harvey <nharvey@customink.com>2011-10-04 15:23:53 -0400
committerNathen Harvey <nharvey@customink.com>2011-10-04 15:23:53 -0400
commitc1f68276e963f6984799b5dd40c4a36a31b9b79c (patch)
treeeb762204cd874a42be29041a94d4bcc9cb47b259
parentc05fbd01c16072b467577a3d58c4af70a93a267b (diff)
parentcb0666616c232ddb3c39838552c335539906bd56 (diff)
downloadmixlib-shellout-c1f68276e963f6984799b5dd40c4a36a31b9b79c.tar.gz
Merge remote-tracking branch 'upstream/master'
-rw-r--r--README.md479
-rw-r--r--attributes/default.rb21
-rw-r--r--files/default/handlers/windows_reboot_handler.rb76
-rw-r--r--libraries/feature_base.rb41
-rw-r--r--libraries/helper.rb87
-rw-r--r--libraries/registry_helper.rb335
-rw-r--r--libraries/version.rb194
-rw-r--r--libraries/windows_privileged.rb94
-rw-r--r--metadata.rb8
-rw-r--r--providers/auto_run.rb32
-rw-r--r--providers/batch.rb62
-rw-r--r--providers/feature_dism.rb47
-rw-r--r--providers/feature_servermanagercmd.rb47
-rw-r--r--providers/package.rb250
-rw-r--r--providers/path.rb27
-rw-r--r--providers/reboot.rb31
-rw-r--r--providers/registry.rb70
-rw-r--r--providers/zipfile.rb54
-rw-r--r--recipes/default.rb34
-rw-r--r--recipes/reboot_handler.rb33
-rw-r--r--resources/auto_run.rb30
-rw-r--r--resources/batch.rb36
-rw-r--r--resources/feature.rb40
-rw-r--r--resources/package.rb36
-rw-r--r--resources/path.rb28
-rw-r--r--resources/reboot.rb29
-rw-r--r--resources/registry.rb32
-rw-r--r--resources/zipfile.rb32
28 files changed, 2285 insertions, 0 deletions
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..1b49f9f
--- /dev/null
+++ b/README.md
@@ -0,0 +1,479 @@
+Description
+===========
+
+Provides a set of Windows-specific primitives (Chef resources) meant to aid in the creation of cookbooks/recipes targeting the Windows platform.
+
+Requirements
+============
+
+Platform
+--------
+
+* Windows XP
+* Windows Vista
+* Windows Server 2003 R2
+* Windows 7
+* Windows Server 2008 (R1, R2)
+
+Cookbooks
+---------
+
+* chef_handler (`windows::reboot_handler` leverages the chef_handler LWRP)
+
+Attributes
+==========
+
+* `node['windows']['allow_pending_reboots']` - used to configure the `WindowsRebootHandler` (via the `windows::reboot_handler` recipe) to act on pending reboots. default is true (ie act on pending reboots). The value of this attribute only has an effect if the `windows::reboot_handler` is in a node's run list.
+
+Resource/Provider
+=================
+
+`windows_auto_run`
+------------------
+
+### Actions
+- :create: Create an item to be run at login
+- :remove: Remove an item that was previously setup to run at login
+
+### Attribute Parameters
+- :name: Name attribute. The name of the value to be stored in the registry
+- :program: The program to be run at login
+- :args: The arguments for the program
+
+### Examples
+
+ # Run BGInfo at login
+ windows_auto_run 'BGINFO' do
+ program "C:/Sysinternals/bginfo.exe"
+ args "\"C:/Sysinternals/Config.bgi\" /NOLICPROMPT /TIMER:0"
+ not_if { Registry.value_exists?(AUTO_RUN_KEY, 'BGINFO') }
+ action :create
+ end
+
+
+`windows_batch`
+------------
+Execute a batch script using the cmd.exe interpreter (much like the script resources for bash, csh, powershell, perl, python and ruby). A temporary file is created and executed like other script resources, rather than run inline. By their nature, Script resources are not idempotent, as they are completely up to the user's imagination. Use the `not_if` or `only_if` meta parameters to guard the resource for idempotence.
+
+### Actions
+
+- :run: run the batch file
+
+### Attribute Parameters
+
+- command: name attribute. Name of the command to execute.
+- code: quoted string of code to execute.
+- creates: a file this command creates - if the file exists, the command will not be run.
+- cwd: current working directory to run the command from.
+- flags: command line flags to pass to the interpreter when invoking.
+- user: A user name or user ID that we should change to before running this command.
+- group: A group name or group ID that we should change to before running this command.
+
+### Examples
+
+ windows_batch "unzip_and_move_ruby" do
+ code <<-EOH
+ 7z.exe x #{Chef::Config[:file_cache_path]}/ruby-1.8.7-p352-i386-mingw32.7z -oC:\\source -r -y
+ xcopy C:\\source\\ruby-1.8.7-p352-i386-mingw32 C:\\ruby /e /y
+ EOH
+ end
+
+ windows_batch "echo some env vars" do
+ code <<-EOH
+ echo %TEMP%
+ echo %SYSTEMDRIVE%
+ echo %PATH%
+ echo %WINDIR%
+ EOH
+ end
+
+
+`windows_feature`
+-----------------
+
+Windows Roles and Features can be thought of as built-in operating system packages that ship with the OS. A server role is a set of software programs that, when they are installed and properly configured, lets a computer perform a specific function for multiple users or other computers within a network. A Role can have multiple Role Services that provide functionality to the Role. Role services are software programs that provide the functionality of a role. Features are software programs that, although they are not directly parts of roles, can support or augment the functionality of one or more roles, or improve the functionality of the server, regardless of which roles are installed. Collectively we refer to all of these attributes as 'features'.
+
+This resource allows you to manage these 'features' in an unattended, idempotent way.
+
+There are two providers for the `windows_features` which map into Microsoft's two major tools for managing roles/features: [Deployment Image Servicing and Management (DISM)](http://msdn.microsoft.com/en-us/library/dd371719(v=vs.85).aspx) and [Servermanagercmd](http://technet.microsoft.com/en-us/library/ee344834(WS.10).aspx) (The CLI for Server Manager). As Servermanagercmd is deprecated, Chef will set the default provider to `Chef::Provider::WindowsFeature::DISM` if DISM is present on the system being configured. The default provider will fall back to `Chef::Provider::WindowsFeature::ServerManagerCmd`.
+
+For more information on Roles, Role Services and Features see the [Microsoft TechNet article on the topic](http://technet.microsoft.com/en-us/library/cc754923.aspx). For a complete list of all features that are available on a node type either of the following commands at a command prompt:
+
+ dism /online /Get-Features
+ servermanagercmd -query
+
+### Actions
+
+- :install: install a Windows role/feature
+- :remove: remove a Windows role/feature
+
+### Attribute Parameters
+
+- feature_name: name of the feature/role to install. The same feature may have different names depending on the provider used (ie DHCPServer vs DHCP; DNS-Server-Full-Role vs DNS).
+
+### Providers
+
+- **Chef::Provider::WindowsFeature::DISM**: Uses Deployment Image Servicing and Management (DISM) to manage roles/features.
+- **Chef::Provider::WindowsFeature::ServerManagerCmd**: Uses Server Manager to manage roles/features.
+
+### Examples
+
+ # enable the node as a DHCP Server
+ windows_feature "DHCPServer" do
+ action :install
+ end
+
+ # enable TFTP
+ windows_feature "TFTP" do
+ action :install
+ end
+
+ # disable Telnet client/server
+ %w{ TelnetServer TelnetClient }.each do |feature|
+ windows_feature feature do
+ action :remove
+ end
+ end
+
+ #
+
+`windows_package`
+-----------------
+
+Manage Windows application packages in an unattended, idempotent way.
+
+The following application installers are currently supported:
+
+* MSI packages
+* InstallShield
+* Wise InstallMaster
+* Inno Setup
+* Nullsoft Scriptable Install System
+
+If the proper installer type is not passed into the resource's installer_type attribute, the provider will do it's best to identify the type by introspecting the installation package. If the installation type cannot be properly identified the `:custom` value can be passed into the installer_type attribute along with the proper flags for silent/quiet installation (using the `options` attribute..see example below).
+
+__PLEASE NOTE__ - For proper idempotence the resource's `package_name` should be the same as the 'DisplayName' registry value in the uninstallation data that is created during package installation. The easiest way to definitively find the proper 'DisplayName' value is to install the package on a machine and search for the uninstall information under the following registry keys:
+
+* `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall`
+* `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall`
+* `HKEY_LOCAL_MACHINE\Software\Wow6464Node\Microsoft\Windows\CurrentVersion\Uninstall`
+
+For maximum flexibility the `source` attribute supports both remote and local installation packages.
+
+### Actions
+
+- :install: install a package
+- :remove: remove a package. The remove action is completely hit or miss as many application uninstallers do not support a full silent/quiet mode.
+
+### Attribute Parameters
+
+- package_name: name attribute. The 'DisplayName' of the application installation package.
+- source: The source of the windows installer. This can either be a URI or a local path.
+- installer_type: They type of windows installation package. valid values are: :msi, :inno, :nsis, :wise, :installshield, :custom. If this value is not provided, the provider will do it's best to identify the installer type through introspection of the file.
+- checksum: useful if source is remote, the SHA-256 checksum of the file--if the local file matches the checksum, Chef will not download it
+- options: Additional options to pass the underlying installation command
+
+### Examples
+
+ # install PuTTY (InnoSetup installer)
+ windows_package "PuTTY version 0.60" do
+ source "http://the.earth.li/~sgtatham/putty/latest/x86/putty-0.60-installer.exe"
+ installer_type :inno
+ action :install
+ end
+
+ # install 7-Zip (MSI installer)
+ windows_package "7-Zip 9.20 (x64 edition)" do
+ source "http://downloads.sourceforge.net/sevenzip/7z920-x64.msi"
+ action :install
+ end
+
+ # install Notepad++ (Y U No Emacs?) using a local installer
+ windows_package "Notepad++" do
+ source "c:/installation_files/npp.5.9.2.Installer.exe"
+ action :install
+ end
+
+ # install VLC for that Xvid (NSIS installer)
+ windows_package "VLC media player 1.1.10" do
+ source "http://superb-sea2.dl.sourceforge.net/project/vlc/1.1.10/win32/vlc-1.1.10-win32.exe"
+ action :install
+ end
+
+ # install Firefox as custom installer and manually set the silent install flags
+ windows_package "Mozilla Firefox 5.0 (x86 en-US)" do
+ source "http://archive.mozilla.org/pub/mozilla.org/mozilla.org/firefox/releases/5.0/win32/en-US/Firefox%20Setup%205.0.exe"
+ options "-ms"
+ installer_type :custom
+ action :install
+ end
+
+ # Google Chrome FTW (MSI installer)
+ windows_package "Google Chrome" do
+ source "https://dl-ssl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B806F36C0-CB54-4A84-A3F3-0CF8A86575E0%7D%26lang%3Den%26browser%3D3%26usagestats%3D0%26appname%3DGoogle%2520Chrome%26needsadmin%3Dfalse/edgedl/chrome/install/GoogleChromeStandaloneEnterprise.msi"
+ action :install
+ end
+
+ # remove Google Chrome (but why??)
+ windows_package "Google Chrome" do
+ action :remove
+ end
+
+ # remove 7-Zip
+ windows_package "7-Zip 9.20 (x64 edition)" do
+ action :remove
+ end
+
+
+`windows_reboot`
+------------------
+
+Sets required data in the node's run_state to notify `WindowsRebootHandler` a reboot is requested. If Chef run completes successfully a reboot will occur if the `WindowsRebootHandler` is properly registered as a report handler. As an action of `:request` will cause a node to reboot every Chef run, this resource is usually notified by other resources...ie restart node after a package is installed (see example below).
+
+### Actions
+- :request: requests a reboot at completion of successful Cher run. requires `WindowsRebootHandler` to be registered as a report handler.
+- :cancel: remove reboot request from node.run_state. this will cancel *ALL* previously requested reboots as this is a binary state.
+
+### Attribute Parameters
+- :timeout: Name attribute. timeout delay in seconds to wait before proceeding with the requested reboot. default is 60 seconds
+- :reason: comment on the reason for the reboot. default is 'Opscode Chef initiated reboot'
+
+### Examples
+
+ # if the package installs, schedule a reboot at end of chef run
+ windows_reboot 60 do
+ reason 'cause chef said so'
+ action :nothing
+ end
+ windows_package 'some_package' do
+ action :install
+ notifies :request, 'windows_reboot[60]'
+ end
+
+ # cancel the previously requested reboot
+ windows_reboot 60 do
+ action :cancel
+ end
+
+`windows_registry`
+-----------------
+
+Creates and modifies Windows registry keys.
+
+### Actions
+
+- :create: create a new registry key with the provided values.
+- :modify: modify an existing registry key with the provided values.
+- :force_modify: modify an existing registry key with the provided values. ensures the value is actually set by checking multiple times. useful for fighting race conditions where two processes are trying to set the same registry key. This will be updated in the near future to use 'RegNotifyChangeKeyValue' which is exposed by the WinAPI and allows a process to register for notification on a registry key change.
+- :remove: removes a value from an existing registry key
+
+### Attribute Parameters
+
+- key_name: name attribute. The registry key to create/modify.
+- values: hash of the values to set under the registry key. The individual hash items will become respective 'Value name' => 'Value data' items in the registry key.
+
+### Examples
+
+ # make the local windows proxy match the one set for Chef
+ proxy = URI.parse(Chef::Config[:http_proxy])
+ windows_registry 'HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings' do
+ values 'ProxyEnable' => 1, 'ProxyServer' => "#{proxy.host}:#{proxy.port}", 'ProxyOverride' => '<local>'
+ end
+
+ # enable Remote Desktop and poke the firewall hole
+ windows_registry 'HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server' do
+ values 'FdenyTSConnections' => 0
+ end
+
+ # Delete an item from the registry
+ windows_registry 'HKCU\Software\Test' do
+ #Key is the name of the value that you want to delete the value is always empty
+ values 'ValueToDelete' => ''
+ action :remove
+ end
+
+### Library Methods
+
+ Registry.value_exists?('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run','BGINFO')
+ Registry.key_exists?('HKLM\SOFTWARE\Microsoft')
+ BgInfo = Registry.get_value('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run','BGINFO')
+
+
+'windows_path'
+--------------
+
+### Actions
+- :add: Add an item to the system path
+
+### Attribute Parameters
+- :path: Name attribute. The name of the value to add to the system path
+
+### Examples
+
+ #Add Sysinternals to the system path
+ windows_path 'C:\Sysinternals' do
+ action :add
+ end
+
+
+`windows_zipfile`
+-----------------
+
+Most version of Windows do not ship with native cli utility for managing compressed files. This resource provides a pure-ruby implementation for managing zip files. Be sure to use the `not_if` or `only_if` meta parameters to guard the resource for idempotence or action will be taken on the zip file every Chef run.
+
+### Actions
+
+- :unzip: unzip a compressed file
+
+### Attribute Parameters
+
+- path: name attribute. The path where files will be unzipped to.
+- source: The source of the zip file. This can either be a URI or a local path.
+- overwrite: force an overwrite of the files if the already exists.
+
+### Examples
+
+ # unzip a remote zip file locally
+ windows_zipfile "c:/bin" do
+ source "http://download.sysinternals.com/Files/SysinternalsSuite.zip"
+ action :unzip
+ not_if {::File.exists?("c:/bin/PsExec.exe")}
+ end
+
+ # unzip a local zipfile
+ windows_zipfile "c:/the_codez" do
+ source "c:/foo/baz/the_codez.zip"
+ action :unzip
+ end
+
+
+Exception/Report Handlers
+=========================
+
+`WindowsRebootHandler`
+----------------------
+
+Required reboots are a necessary evil of configuring and managing Windows nodes. This report handler (ie fires at the end of successful Chef runs) acts on requested (Chef initiated) or pending (as determined by the OS per configuration action we performed) reboots. The `allow_pending_reboots` initialization argument should be set to false if you do not want the handler to automatically reboot a node if it has been determined a reboot is pending. Reboots can still be requested explicitly via the `windows_reboot` LWRP.
+
+## Initialization Arguments
+
+- allow_pending_reboots: indicator on whether the handler should act on a the Window's 'pending reboot' state. default is true
+- timeout: timeout delay in seconds to wait before proceeding with the reboot. default is 60 seconds
+- reason: comment on the reason for the reboot. default is 'Opscode Chef initiated reboot'
+
+Usage
+=====
+
+Just place an explicit dependency on this cookbook (using depends in the cookbook's metadata.rb) from any cookbook where you would like to use the Windows-specific resources/providers that ship with this cookbook.
+
+default
+-------
+
+Convenience recipe that installs supporting gems for many of the resources/providers that ship with this cookbook.
+
+reboot_handler
+--------------
+
+Leverages the `chef_handler` LWRP to register the `WindowsRebootHandler` report handler that ships as part of this cookbook. By default this handler is set to automatically act on pending reboots. If you would like to change this behavior override `node['windows']['allow_pending_reboots']` and set the value to false. For example:
+
+ % cat roles/base.rb
+ name "base"
+ description "base role"
+ override_attributes(
+ "windows" => {
+ "allow_pending_reboots" => false
+ }
+ )
+
+This will still allow a reboot to be explicitly requested via the `windows_reboot` LWRP.
+
+Changes/Roadmap
+===============
+
+## Future
+
+* package preseeding/response_file support
+* package installation location via a `target_dir` attribute.
+* [COOK-666] windows_package should support CoApp packages
+* windows_registry :force_modify action should use RegNotifyChangeKeyValue from WinAPI
+* WindowsRebootHandler/windows_reboot LWRP should support kicking off subsequent chef run on reboot.
+
+## v1.2.4
+
+* windows_package - catch Win32::Registry::Error that pops up when searching certain keys
+
+## v1.2.2
+
+* combined numerous helper libarires for easier sharing across libaries/LWRPs
+* renamed Chef::Provider::WindowsFeature::Base file to the more descriptive feature_base.rb
+* refactored windows_path LWRP
+ * :add action should MODIFY the the underlying ENV variable (vs CREATE)
+ * deleted greedy :remove action until it could be made more idempotent
+* added a windows_batch resource/provider for running batch scripts remotely
+
+## v1.2.0
+
+* [COOK-745] gracefully handle required server restarts on Windows platform
+ * WindowsRebootHandler for requested and pending reboots
+ * windows_reboot LWRP for requesting (receiving notifies) reboots
+ * reboot_handler recipe for enabling WindowsRebootHandler as a report handler
+* [COOK-714] Correct initialize misspelling
+* RegistryHelper - new get_values method which returns all values for a particular key.
+
+## v1.0.8
+
+* [COOK-719] resource/provider for managing windows features
+* [COOK-717] remove windows_env_vars resource as env resource exists in core chef
+* new `Windows::Version` helper class
+* refactored `Windows::Helper` mixin
+
+## v1.0.6
+
+* added force_modify action to windows_registry resource
+* add win_friendly_path helper
+* re-purpose default recipe to install useful supporting windows related gems
+
+## v1.0.4
+
+* [COOK-700] new resources and improvements to the windows_registry provider (thanks Paul Morton!)
+ * Open the registry in the bitednes of the OS
+ * Provide convenience methods to check if keys and values exit
+ * Provide convenience method for reading registry values
+ * NEW - `windows_auto_run` resource/provider
+ * NEW - `windows_env_vars` resource/provider
+ * NEW - `windows_path` resource/provider
+* re-write of the windows_package logic for determining current installed packages
+* new checksum attribute for windows_package resource...useful for remote packages
+
+## v1.0.2:
+
+* [COOK-647] account for Wow6432Node registry redirecter
+* [COOK-656] begin/rescue on win32/registry
+
+## 1.0.0:
+
+* [COOK-612] initial release
+
+License and Author
+==================
+
+Author:: Seth Chisamore (<schisamo@opscode.com>)
+Author:: Doug MacEachern (<dougm@vmware.com>)
+Author:: Paul Morton (<pmorton@biaprotect.com>)
+
+Copyright:: 2011, Opscode, Inc.
+Copyright:: 2010, VMware, Inc.
+Copyright:: 2011, Business Intelligence Associates, Inc
+
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/attributes/default.rb b/attributes/default.rb
new file mode 100644
index 0000000..7d37adc
--- /dev/null
+++ b/attributes/default.rb
@@ -0,0 +1,21 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Attribute:: default
+#
+# Copyright 2011, Opscode, Inc
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+default['windows']['allow_pending_reboots'] = true
diff --git a/files/default/handlers/windows_reboot_handler.rb b/files/default/handlers/windows_reboot_handler.rb
new file mode 100644
index 0000000..e94dbb4
--- /dev/null
+++ b/files/default/handlers/windows_reboot_handler.rb
@@ -0,0 +1,76 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Copyright:: Copyright (c) 2011 Opscode, Inc
+# License:: Apache License, Version 2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+class WindowsRebootHandler < Chef::Handler
+ include Chef::Mixin::ShellOut
+
+ def initialize(allow_pending_reboots = true, timeout = 60, reason = "Opscode Chef initiated reboot")
+ @allow_pending_reboots = allow_pending_reboots
+ @timeout = timeout
+ @reason = reason
+ end
+
+ def report
+ log_message, reboot = begin
+ if reboot_requested?
+ ["chef_handler[#{self.class}] requested reboot will occur in #{timeout} seconds", true]
+ elsif reboot_pending?
+ if @allow_pending_reboots
+ ["chef_handler[#{self.class}] reboot pending - automatic reboot will occur in #{timeout} seconds", true]
+ else
+ ["chef_handler[#{self.class}] reboot pending but handler not configured to act on pending reboots - please reboot node manually", false]
+ end
+ else
+ ["chef_handler[#{self.class}] no reboot requested or pending", false]
+ end
+ end
+
+ Chef::Log.warn(log_message)
+ shell_out!("shutdown /r /t #{timeout} /c \"#{reason}\"") if reboot
+ end
+
+ private
+ # reboot cause CHEF says so:
+ # reboot explicitly requested in our cookbook code
+ def reboot_requested?
+ node.run_state[:reboot_requested] == true
+ end
+
+ # reboot cause WIN says so:
+ # reboot pending because of some configuration action we performed
+ def reboot_pending?
+ # Any files listed here means reboot needed
+ (Registry.key_exists?('HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations') &&
+ Registry.get_value('HKLM\SYSTEM\CurrentControlSet\Control\Session Manager','PendingFileRenameOperations').any?) ||
+ # 1 for any value means reboot pending
+ # "9306cdfc-c4a1-4a22-9996-848cb67eddc3"=1
+ (Registry.key_exists?('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired') &&
+ Registry.get_values('HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired').select{|v| v[2] == 1 }.any?) ||
+ # 1 or 2 for 'Flags' value means reboot pending
+ (Registry.key_exists?('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile') &&
+ [1,2].include?(Registry::get_value('HKLM\SOFTWARE\Microsoft\Updates\UpdateExeVolatile','Flags')))
+ end
+
+ def timeout
+ node.run_state[:reboot_timeout] || @timeout
+ end
+
+ def reason
+ node.run_state[:reboot_reason] || @reason
+ end
+end \ No newline at end of file
diff --git a/libraries/feature_base.rb b/libraries/feature_base.rb
new file mode 100644
index 0000000..66cbc42
--- /dev/null
+++ b/libraries/feature_base.rb
@@ -0,0 +1,41 @@
+class Chef
+ class Provider
+ class WindowsFeature
+ module Base
+
+ def action_install
+ unless installed?
+ install_feature(@new_resource.feature_name)
+ @new_resource.updated_by_last_action(true)
+ Chef::Log.info("#{@new_resource} installed feature")
+ else
+ Chef::Log.debug("#{@new_resource} is already installed - nothing to do")
+ end
+ end
+
+ def action_remove
+ if installed?
+ remove_feature(@new_resource.feature_name)
+ @new_resource.updated_by_last_action(true)
+ Chef::Log.info("#{@new_resource} removed")
+ else
+ Chef::Log.debug("#{@new_resource} feature does not exist - nothing to do")
+ end
+ end
+
+ def install_feature(name)
+ raise Chef::Exceptions::UnsupportedAction, "#{self.to_s} does not support :install"
+ end
+
+ def remove_feature(name)
+ raise Chef::Exceptions::UnsupportedAction, "#{self.to_s} does not support :remove"
+ end
+
+ def installed?
+ raise Chef::Exceptions::Override, "You must override installed? in #{self.to_s}"
+ end
+ end
+ end
+ end
+end
+ \ No newline at end of file
diff --git a/libraries/helper.rb b/libraries/helper.rb
new file mode 100644
index 0000000..dc7c7b3
--- /dev/null
+++ b/libraries/helper.rb
@@ -0,0 +1,87 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Library:: helper
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+module Windows
+ module Helper
+
+ AUTO_RUN_KEY = 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
+ ENV_KEY = 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
+
+ # returns windows friendly version of the provided path,
+ # ensures backslashes are used everywhere
+ def win_friendly_path(path)
+ path.gsub(::File::SEPARATOR, ::File::ALT_SEPARATOR) if path
+ end
+
+ # account for Window's wacky File System Redirector
+ # http://msdn.microsoft.com/en-us/library/aa384187(v=vs.85).aspx
+ # especially important for 32-bit processes (like Ruby) on a
+ # 64-bit instance of Windows.
+ def locate_sysnative_cmd(cmd)
+ if ::File.exists?("#{ENV['WINDIR']}\\sysnative\\#{cmd}")
+ "#{ENV['WINDIR']}\\sysnative\\#{cmd}"
+ elsif ::File.exists?("#{ENV['WINDIR']}\\system32\\#{cmd}")
+ "#{ENV['WINDIR']}\\system32\\#{cmd}"
+ else
+ cmd
+ end
+ end
+
+ # Create a feature provider dependent value object.
+ # mainly created becasue Windows Feature names are
+ # different based on whether dism.exe or servicemanagercmd.exe
+ # is used for installation
+ def value_for_feature_provider(provider_hash)
+ p = Chef::Platform.find_provider_for_node(node, :windows_feature)
+ key = p.to_s.downcase.split('::').last
+ provider_hash[key] || provider_hash[key.to_sym]
+ end
+
+ # singleton instance of the Windows Version checker
+ def win_version
+ @win_version ||= Windows::Version.new
+ end
+
+ # if a file is local it returns a windows friendly path version
+ # if a file is remote it caches it locally
+ def cached_file(source, checksum=nil, windows_path=true)
+ @installer_file_path ||= begin
+
+ if(source =~ /^(https?:\/\/)(.*\/)(.*)$/)
+ cache_file_path = "#{Chef::Config[:file_cache_path]}/#{::File.basename(source)}"
+ Chef::Log.debug("Caching a copy of file #{source} at #{cache_file_path}")
+ r = Chef::Resource::RemoteFile.new(cache_file_path, run_context)
+ r.source(source)
+ r.backup(false)
+ r.mode("0755")
+ r.checksum(checksum) if checksum
+ r.run_action(:create)
+ else
+ cache_file_path = source
+ end
+
+ windows_path ? win_friendly_path(cache_file_path) : cache_file_path
+ end
+ end
+
+ end
+end
+
+Chef::Recipe.send(:include, Windows::Helper)
diff --git a/libraries/registry_helper.rb b/libraries/registry_helper.rb
new file mode 100644
index 0000000..a385783
--- /dev/null
+++ b/libraries/registry_helper.rb
@@ -0,0 +1,335 @@
+#
+# Author:: Doug MacEachern (<dougm@vmware.com>)
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Author:: Paul Morotn (<pmorton@biaprotect.com>)
+# Cookbook Name:: windows
+# Provider:: registry
+#
+# Copyright:: 2010, VMware, Inc.
+# Copyright:: 2011, Opscode, Inc.
+# Copyright:: 2011, Business Intelligence Associates, Inc
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+if RUBY_PLATFORM =~ /mswin|mingw32|windows/
+ require 'win32/registry'
+ require 'ruby-wmi'
+end
+
+module Windows
+ module RegistryHelper
+
+ @@native_registry_constant = ENV['PROCESSOR_ARCHITEW6432'] == 'AMD64' ? 0x0100 : 0x0200
+
+ def get_hive_name(path)
+ Chef::Log.debug("Resolving registry shortcuts to full names")
+
+ reg_path = path.split("\\")
+ hive_name = reg_path.shift
+
+ hkey = {
+ "HKLM" => "HKEY_LOCAL_MACHINE",
+ "HKCU" => "HKEY_CURRENT_USER",
+ "HKU" => "HKEY_USERS"
+ }[hive_name] || hive_name
+
+ Chef::Log.debug("Hive resolved to #{hkey}")
+ return hkey
+ end
+
+ def get_hive(path)
+
+ Chef::Log.debug("Getting hive for #{path}")
+ reg_path = path.split("\\")
+ hive_name = reg_path.shift
+
+ hkey = get_hive_name(path)
+
+ hive = {
+ "HKEY_LOCAL_MACHINE" => Win32::Registry::HKEY_LOCAL_MACHINE,
+ "HKEY_USERS" => Win32::Registry::HKEY_USERS,
+ "HKEY_CURRENT_USER" => Win32::Registry::HKEY_CURRENT_USER
+ }[hkey]
+
+ unless hive
+ Chef::Application.fatal!("Unsupported registry hive '#{hive_name}'")
+ end
+
+
+ Chef::Log.debug("Registry hive resolved to #{hkey}")
+ return hive
+ end
+
+ def unload_hive(path)
+ hive = get_hive(path)
+ if hive == Win32::Registry::HKEY_USERS
+ reg_path = path.split("\\")
+ priv = Chef::WindowsPrivileged.new
+ begin
+ priv.reg_unload_key(reg_path[1])
+ rescue
+ end
+ end
+ end
+
+ def set_value(mode,path,values)
+ hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
+ key_name = reg_path.join("\\")
+
+ Chef::Log.debug("Creating #{path})")
+
+ if !key_exists?(path,true)
+ create_key(path)
+ end
+
+ hive.send(mode, key_name, Win32::Registry::KEY_ALL_ACCESS | @@native_registry_constant) do |reg|
+ values.each do |k,val|
+ key = "#{k}" #wtf. avoid "can't modify frozen string" in win32/registry.rb
+ cur_val = nil
+ begin
+ cur_val = reg[key]
+ rescue
+ #subkey does not exist (ok)
+ end
+ if cur_val != val
+ Chef::Log.debug("setting #{key}=#{val}")
+ reg[key] = val
+
+ ensure_hive_unloaded(hive_loaded)
+
+ return true
+ end
+ end
+ end
+ return false
+ end
+
+ def get_value(path,value)
+ hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
+ key = reg_path.join("\\")
+
+ hive.open(key, Win32::Registry::KEY_ALL_ACCESS | @@native_registry_constant) do | reg |
+ begin
+ return reg[value]
+ rescue
+ return nil
+ ensure
+ ensure_hive_unloaded(hive_loaded)
+ end
+ end
+ end
+
+ def get_values(path)
+ hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
+ key = reg_path.join("\\")
+ hive.open(key, Win32::Registry::KEY_ALL_ACCESS | @@native_registry_constant) do | reg |
+ values = []
+ begin
+ reg.each_value do |name, type, data|
+ values << [name, type, data]
+ end
+ rescue
+ ensure
+ ensure_hive_unloaded(hive_loaded)
+ end
+ values
+ end
+ end
+
+ def delete_value(path,values)
+ hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
+ key = reg_path.join("\\")
+ Chef::Log.debug("Deleting values in #{path}")
+ hive.open(key, Win32::Registry::KEY_ALL_ACCESS | @@native_registry_constant) do | reg |
+ values.each_key { |key|
+ name = "#{key}"
+ Chef::Log.debug("Deleting value #{name} in #{path}")
+ reg.delete_value(name)
+ }
+ end
+
+ end
+
+ def create_key(path)
+ hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
+ key = reg_path.join("\\")
+ Chef::Log.debug("Creating registry key #{path}")
+ hive.create(key)
+ end
+
+ def value_exists?(path,value)
+ if key_exists?(path,true)
+
+ hive, reg_path, hive_name, root_key , hive_loaded = get_reg_path_info(path)
+ key = reg_path.join("\\")
+
+ Chef::Log.debug("Attempting to open #{key}");
+ Chef::Log.debug("Native Constant #{@@native_registry_constant}")
+ Chef::Log.debug("Hive #{hive}")
+
+ hive.open(key, Win32::Registry::KEY_READ | @@native_registry_constant) do | reg |
+ begin
+ rtn_value = reg[value]
+ return true
+ rescue
+ return false
+ ensure
+ ensure_hive_unloaded(hive_loaded)
+ end
+ end
+
+ end
+ return false
+ end
+
+ # TODO: Does not load user registry...
+ def key_exists?(path, load_hive = false)
+ if load_hive
+ hive, reg_path, hive_name, root_key , hive_loaded = get_reg_path_info(path)
+ key = reg_path.join("\\")
+ else
+ hive = get_hive(path)
+ reg_path = path.split("\\")
+ hive_name = reg_path.shift
+ root_key = reg_path[0]
+ key = reg_path.join("\\")
+ hive_loaded = false
+ end
+
+ begin
+ hive.open(key, Win32::Registry::Constants::KEY_READ | @@native_registry_constant )
+ return true
+ rescue
+ return false
+ ensure
+ ensure_hive_unloaded(hive_loaded)
+ end
+ end
+
+ def get_user_hive_location(sid)
+ reg_key = "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\#{sid}"
+ Chef::Log.debug("Looking for profile at #{reg_key}")
+ if key_exists?(reg_key)
+ return get_value(reg_key,'ProfileImagePath')
+ else
+ return nil
+ end
+
+ end
+
+ def resolve_user_to_sid(username)
+ begin
+ sid = WMI::Win32_UserAccount.find(:first, :conditions => {:name => username}).sid
+ Chef::Log.debug("Resolved user SID to #{sid}")
+ return sid
+ rescue
+ return nil
+ end
+ end
+
+ def hive_loaded?(path)
+ hive = get_hive(path)
+ reg_path = path.split("\\")
+ hive_name = reg_path.shift
+ user_hive = path[0]
+
+ if is_user_hive?(hive)
+ return key_exists?("#{hive_name}\\#{user_hive}")
+ else
+ return true
+ end
+ end
+
+ def is_user_hive?(hive)
+ if hive == Win32::Registry::HKEY_USERS
+ return true
+ else
+ return true
+ end
+ end
+
+ def get_reg_path_info(path)
+ hive = get_hive(path)
+ reg_path = path.split("\\")
+ hive_name = reg_path.shift
+ root_key = reg_path[0]
+ hive_loaded = false
+
+ if is_user_hive?(hive) && !key_exists?("#{hive_name}\\#{root_key}")
+ reg_path, hive_loaded = load_user_hive(hive,reg_path,root_key)
+ root_key = reg_path[0]
+ Chef::Log.debug("Resolved user (#{path}) to (#{reg_path.join('/')})")
+ end
+
+ return hive, reg_path, hive_name, root_key, hive_loaded
+ end
+
+ def load_user_hive(hive,reg_path,user_hive)
+ Chef::Log.debug("Reg Path #{reg_path}")
+ # See if the hive is loaded. Logged in users will have a key that is named their SID
+ # if the user has specified the a path by SID and the user is logged in, this function
+ # should not be executed.
+ if is_user_hive?(hive) && !key_exists?("HKU\\#{user_hive}")
+ Chef::Log.debug("The user is not logged in and has not been specified by SID")
+ sid = resolve_user_to_sid(user_hive)
+ Chef::Log.debug("User SID resolved to (#{sid})")
+ # Now that the user has been resolved to a SID, check and see if the hive exists.
+ # If this exists by SID, the user is logged in and we should use that key.
+ # TODO: Replace the username with the sid and send it back because the username
+ # does not exist as the key location.
+ load_reg = false
+ if key_exists?("HKU\\#{sid}")
+ reg_path[0] = sid #use the active profile (user is logged on)
+ Chef::Log.debug("HKEY_USERS Mapped: #{user_hive} -> #{sid}")
+ else
+ Chef::Log.debug("User is not logged in")
+ load_reg = true
+ end
+
+ # The user is not logged in, so we should load the registry from disk
+ if load_reg
+ profile_path = get_user_hive_location(sid)
+ if profile_path != nil
+ ntuser_dat = "#{profile_path}\\NTUSER.DAT"
+ if ::File.exists?(ntuser_dat)
+ priv = Chef::WindowsPrivileged.new
+ if priv.reg_load_key(sid,ntuser_dat)
+ Chef::Log.debug("RegLoadKey(#{sid}, #{user_hive}, #{ntuser_dat})")
+ reg_path[0] = sid
+ else
+ Chef::Log.debug("Failed RegLoadKey(#{sid}, #{user_hive}, #{ntuser_dat})")
+ end
+ end
+ end
+ end
+ end
+
+ return reg_path, load_reg
+
+ end
+
+ private
+ def ensure_hive_unloaded(hive_loaded=false)
+ if(hive_loaded)
+ Chef::Log.debug("Hive was loaded, we really should unload it")
+ unload_hive(path)
+ end
+ end
+ end
+end
+
+module Registry
+ module_function
+ extend Windows::RegistryHelper
+end \ No newline at end of file
diff --git a/libraries/version.rb b/libraries/version.rb
new file mode 100644
index 0000000..6e3c541
--- /dev/null
+++ b/libraries/version.rb
@@ -0,0 +1,194 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Library:: version
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+if RUBY_PLATFORM =~ /mswin|mingw32|windows/
+ require 'ruby-wmi'
+ require 'Win32API'
+end
+
+module Windows
+ class Version
+
+ # http://msdn.microsoft.com/en-us/library/ms724833(v=vs.85).aspx
+
+ # Suite Masks
+ # Microsoft BackOffice components are installed.
+ VER_SUITE_BACKOFFICE = 0x00000004
+ # Windows Server 2003, Web Edition is installed.
+ VER_SUITE_BLADE = 0x00000400
+ # Windows Server 2003, Compute Cluster Edition is installed.
+ VER_SUITE_COMPUTE_SERVER = 0x00004000
+ # Windows Server 2008 Datacenter, Windows Server 2003, Datacenter Edition, or Windows 2000 Datacenter Server is installed.
+ VER_SUITE_DATACENTER = 0x00000080
+ # Windows Server 2008 Enterprise, Windows Server 2003, Enterprise Edition, or Windows 2000 Advanced Server is installed. Refer to the Remarks section for more information about this bit flag.
+ VER_SUITE_ENTERPRISE = 0x00000002
+ # Windows XP Embedded is installed.
+ VER_SUITE_EMBEDDEDNT = 0x00000040
+ # Windows Vista Home Premium, Windows Vista Home Basic, or Windows XP Home Edition is installed.
+ VER_SUITE_PERSONAL = 0x00000200
+ # Remote Desktop is supported, but only one interactive session is supported. This value is set unless the system is running in application server mode.
+ VER_SUITE_SINGLEUSERTS = 0x00000100
+ # Microsoft Small Business Server was once installed on the system, but may have been upgraded to another version of Windows. Refer to the Remarks section for more information about this bit flag.
+ VER_SUITE_SMALLBUSINESS = 0x00000001
+ # Microsoft Small Business Server is installed with the restrictive client license in force. Refer to the Remarks section for more information about this bit flag.
+ VER_SUITE_SMALLBUSINESS_RESTRICTED = 0x00000020
+ # Windows Storage Server 2003 R2 or Windows Storage Server 2003is installed.
+ VER_SUITE_STORAGE_SERVER = 0x00002000
+ # Terminal Services is installed. This value is always set.
+ # If VER_SUITE_TERMINAL is set but VER_SUITE_SINGLEUSERTS is not set, the system is running in application server mode.
+ VER_SUITE_TERMINAL = 0x00000010
+ # Windows Home Server is installed.
+ VER_SUITE_WH_SERVER = 0x00008000
+
+ # Product Type
+ # The system is a domain controller and the operating system is Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, or Windows 2000 Server.
+ VER_NT_DOMAIN_CONTROLLER = 0x0000002
+ # The operating system is Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, or Windows 2000 Server.
+ # Note that a server that is also a domain controller is reported as VER_NT_DOMAIN_CONTROLLER, not VER_NT_SERVER.
+ VER_NT_SERVER = 0x0000003
+ # The operating system is Windows 7, Windows Vista, Windows XP Professional, Windows XP Home Edition, or Windows 2000 Professional.
+ VER_NT_WORKSTATION = 0x0000001
+
+ # GetSystemMetrics
+ # The build number if the system is Windows Server 2003 R2; otherwise, 0.
+ SM_SERVERR2 = 89
+
+ # http://msdn.microsoft.com/en-us/library/ms724358(v=vs.85).aspx
+ # this is what it sounds like...when kittens die
+ SKU = {
+ 0x00000006 => {:ms_const => 'PRODUCT_BUSINESS', :name => 'Business'},
+ 0x00000010 => {:ms_const => 'PRODUCT_BUSINESS_N', :name => 'Business N'},
+ 0x00000012 => {:ms_const => 'PRODUCT_CLUSTER_SERVER', :name => 'HPC Edition'},
+ 0x00000008 => {:ms_const => 'PRODUCT_DATACENTER_SERVER', :name => 'Server Datacenter (full installation)'},
+ 0x0000000C => {:ms_const => 'PRODUCT_DATACENTER_SERVER_CORE', :name => 'Server Datacenter (core installation)'},
+ 0x00000027 => {:ms_const => 'PRODUCT_DATACENTER_SERVER_CORE_V', :name => 'Server Datacenter without Hyper-V (core installation)'},
+ 0x00000025 => {:ms_const => 'PRODUCT_DATACENTER_SERVER_V', :name => 'Server Datacenter without Hyper-V (full installation)'},
+ 0x00000004 => {:ms_const => 'PRODUCT_ENTERPRISE', :name => 'Enterprise'},
+ 0x00000046 => {:ms_const => 'PRODUCT_ENTERPRISE_E', :name => 'Not supported'},
+ 0x0000001B => {:ms_const => 'PRODUCT_ENTERPRISE_N', :name => 'Enterprise N'},
+ 0x0000000A => {:ms_const => 'PRODUCT_ENTERPRISE_SERVER', :name => 'Server Enterprise (full installation)'},
+ 0x0000000E => {:ms_const => 'PRODUCT_ENTERPRISE_SERVER_CORE', :name => 'Server Enterprise (core installation)'},
+ 0x00000029 => {:ms_const => 'PRODUCT_ENTERPRISE_SERVER_CORE_V', :name => 'Server Enterprise without Hyper-V (core installation)'},
+ 0x0000000F => {:ms_const => 'PRODUCT_ENTERPRISE_SERVER_IA64', :name => 'Server Enterprise for Itanium-based Systems'},
+ 0x00000026 => {:ms_const => 'PRODUCT_ENTERPRISE_SERVER_V', :name => 'Server Enterprise without Hyper-V (full installation)'},
+ 0x00000002 => {:ms_const => 'PRODUCT_HOME_BASIC', :name => 'Home Basic'},
+ 0x00000043 => {:ms_const => 'PRODUCT_HOME_BASIC_E', :name => 'Not supported'},
+ 0x00000005 => {:ms_const => 'PRODUCT_HOME_BASIC_N', :name => 'Home Basic N'},
+ 0x00000003 => {:ms_const => 'PRODUCT_HOME_PREMIUM', :name => 'Home Premium'},
+ 0x00000044 => {:ms_const => 'PRODUCT_HOME_PREMIUM_E', :name => 'Not supported'},
+ 0x0000001A => {:ms_const => 'PRODUCT_HOME_PREMIUM_N', :name => 'Home Premium N'},
+ 0x0000002A => {:ms_const => 'PRODUCT_HYPERV', :name => 'Microsoft Hyper-V Server'},
+ 0x0000001E => {:ms_const => 'PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT', :name => 'Windows Essential Business Server Management Server'},
+ 0x00000020 => {:ms_const => 'PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING', :name => 'Windows Essential Business Server Messaging Server'},
+ 0x0000001F => {:ms_const => 'PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY', :name => 'Windows Essential Business Server Security Server'},
+ 0x00000030 => {:ms_const => 'PRODUCT_PROFESSIONAL', :name => 'Professional'},
+ 0x00000045 => {:ms_const => 'PRODUCT_PROFESSIONAL_E', :name => 'Not supported'},
+ 0x00000031 => {:ms_const => 'PRODUCT_PROFESSIONAL_N', :name => 'Professional N'},
+ 0x00000018 => {:ms_const => 'PRODUCT_SERVER_FOR_SMALLBUSINESS', :name => 'Windows Server 2008 for Windows Essential Server Solutions'},
+ 0x00000023 => {:ms_const => 'PRODUCT_SERVER_FOR_SMALLBUSINESS_V', :name => 'Windows Server 2008 without Hyper-V for Windows Essential Server Solutions'},
+ 0x00000021 => {:ms_const => 'PRODUCT_SERVER_FOUNDATION', :name => 'Server Foundation'},
+ 0x00000022 => {:ms_const => 'PRODUCT_HOME_PREMIUM_SERVER', :name => 'Windows Home Server 2011'},
+ 0x00000032 => {:ms_const => 'PRODUCT_SB_SOLUTION_SERVER', :name => 'Windows Small Business Server 2011 Essentials'},
+ 0x00000013 => {:ms_const => 'PRODUCT_HOME_SERVER', :name => 'Windows Storage Server 2008 R2 Essentials'},
+ 0x00000009 => {:ms_const => 'PRODUCT_SMALLBUSINESS_SERVER', :name => 'Windows Small Business Server'},
+ 0x00000038 => {:ms_const => 'PRODUCT_SOLUTION_EMBEDDEDSERVER', :name => 'Windows MultiPoint Server'},
+ 0x00000007 => {:ms_const => 'PRODUCT_STANDARD_SERVER', :name => 'Server Standard (full installation)'},
+ 0x0000000D => {:ms_const => 'PRODUCT_STANDARD_SERVER_CORE', :name => 'Server Standard (core installation)'},
+ 0x00000028 => {:ms_const => 'PRODUCT_STANDARD_SERVER_CORE_V', :name => 'Server Standard without Hyper-V (core installation)'},
+ 0x00000024 => {:ms_const => 'PRODUCT_STANDARD_SERVER_V', :name => 'Server Standard without Hyper-V (full installation)'},
+ 0x0000000B => {:ms_const => 'PRODUCT_STARTER', :name => 'Starter'},
+ 0x00000042 => {:ms_const => 'PRODUCT_STARTER_E', :name => 'Not supported'},
+ 0x0000002F => {:ms_const => 'PRODUCT_STARTER_N', :name => 'Starter N'},
+ 0x00000017 => {:ms_const => 'PRODUCT_STORAGE_ENTERPRISE_SERVER', :name => 'Storage Server Enterprise'},
+ 0x00000014 => {:ms_const => 'PRODUCT_STORAGE_EXPRESS_SERVER', :name => 'Storage Server Express'},
+ 0x00000015 => {:ms_const => 'PRODUCT_STORAGE_STANDARD_SERVER', :name => 'Storage Server Standard'},
+ 0x00000016 => {:ms_const => 'PRODUCT_STORAGE_WORKGROUP_SERVER', :name => 'Storage Server Workgroup'},
+ 0x00000000 => {:ms_const => 'PRODUCT_UNDEFINED', :name => 'An unknown product'},
+ 0x00000001 => {:ms_const => 'PRODUCT_ULTIMATE', :name => 'Ultimate'},
+ 0x00000047 => {:ms_const => 'PRODUCT_ULTIMATE_E', :name => 'Not supported'},
+ 0x0000001C => {:ms_const => 'PRODUCT_ULTIMATE_N', :name => 'Ultimate N'},
+ 0x00000011 => {:ms_const => 'PRODUCT_WEB_SERVER', :name => 'Web Server (full installation)'},
+ 0x0000001D => {:ms_const => 'PRODUCT_WEB_SERVER_CORE', :name => 'Web Server (core installation)'}
+ }
+
+ attr_reader :major_version, :minor_version, :build_number, :service_pack_major_version, :service_pack_minor_version
+ attr_reader :version, :product_type, :product_suite, :sku
+
+ def initialize
+ unless RUBY_PLATFORM =~ /mswin|mingw32|windows/
+ raise NotImplementedError, 'only valid on Windows platform'
+ end
+ @version, @product_type, @product_suite, @sku, @service_pack_major_version, @service_pack_minor_version = get_os_info
+ @major_version, @minor_version, @build_number = version.split('.').map{|v| v.to_i }
+ end
+
+ WIN_VERSIONS = {
+ "Windows 7" => {:major => 6, :minor => 1, :callable => lambda{ @product_type == VER_NT_WORKSTATION }},
+ "Windows Server 2008 R2" => {:major => 6, :minor => 1, :callable => lambda{ @product_type != VER_NT_WORKSTATION }},
+ "Windows Server 2008" => {:major => 6, :minor => 0, :callable => lambda{ @product_type != VER_NT_WORKSTATION }},
+ "Windows Vista" => {:major => 6, :minor => 0, :callable => lambda{ @product_type == VER_NT_WORKSTATION }},
+ "Windows Server 2003 R2" => {:major => 5, :minor => 2, :callable => lambda{ sm_serverr2 != 0 }},
+ "Windows Home Server" => {:major => 5, :minor => 2, :callable => lambda{ (@product_suite & VER_SUITE_WH_SERVER) == VER_SUITE_WH_SERVER }},
+ "Windows Server 2003" => {:major => 5, :minor => 2, :callable => lambda{ sm_serverr2 == 0 }},
+ "Windows XP" => {:major => 5, :minor => 1},
+ "Windows 2000" => {:major => 5, :minor => 0}
+ }
+
+ marketing_names = Array.new
+
+ # General Windows checks
+ WIN_VERSIONS.each do |k,v|
+ method_name = "#{k.gsub(/\s/, '_').downcase}?"
+ define_method(method_name) do
+ (@major_version == v[:major]) &&
+ (@minor_version == v[:minor]) &&
+ (v[:callable] ? v[:callable].call : true)
+ end
+ marketing_names << [k, method_name]
+ end
+
+ define_method(:marketing_name) do
+ marketing_names.each do |mn|
+ break mn[0] if self.send(mn[1])
+ end
+ end
+
+ # Server Type checks
+ %w{ core full datacenter }.each do |m|
+ define_method("server_#{m}?") do
+ !(SKU[@sku][:name] =~ /#{m}/i).nil?
+ end
+ end
+
+ private
+ # Win32API call to GetSystemMetrics(SM_SERVERR2)
+ # returns: The build number if the system is Windows Server 2003 R2; otherwise, 0.
+ def sm_serverr2
+ @sm_serverr2 ||= Win32API.new('user32', 'GetSystemMetrics', 'I', 'I').call(SM_SERVERR2)
+ end
+
+ # query WMI Win32_OperatingSystem for required OS info
+ def get_os_info
+ cols = %w{ Version ProductType OSProductSuite OperatingSystemSKU ServicePackMajorVersion ServicePackMinorVersion }
+ os_info = WMI::Win32_OperatingSystem.find(:first)
+ cols.map{|c| os_info.send(c) }
+ end
+ end
+end
diff --git a/libraries/windows_privileged.rb b/libraries/windows_privileged.rb
new file mode 100644
index 0000000..2b3753d
--- /dev/null
+++ b/libraries/windows_privileged.rb
@@ -0,0 +1,94 @@
+#
+# Author:: Doug MacEachern <dougm@vmware.com>
+# Author:: Paul Morton (<pmorton@biaprotect.com>)
+# Cookbook Name:: windows
+# Library:: windows_privileged
+#
+# Copyright:: 2010, VMware, Inc.
+# Copyright:: 2011, Business Intelligence Associates, Inc
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+if RUBY_PLATFORM =~ /mswin|mingw32|windows/
+ require 'windows/error'
+ require 'windows/registry'
+ require 'windows/process'
+ require 'windows/security'
+end
+
+#helpers for Windows API calls that require privilege adjustments
+class Chef
+ class WindowsPrivileged
+ if RUBY_PLATFORM =~ /mswin|mingw32|windows/
+ include Windows::Error
+ include Windows::Registry
+ include Windows::Process
+ include Windows::Security
+ end
+ #File -> Load Hive... in regedit.exe
+ def reg_load_key(name, file)
+ run(SE_BACKUP_NAME, SE_RESTORE_NAME) do
+ rc = RegLoadKey(HKEY_USERS, "#{name}", file)
+ if rc == ERROR_SUCCESS
+ return true
+ elsif rc == ERROR_SHARING_VIOLATION
+ return false
+ else
+ raise get_last_error(rc)
+ end
+ end
+ end
+
+ #File -> Unload Hive... in regedit.exe
+ def reg_unload_key(name)
+ run(SE_BACKUP_NAME, SE_RESTORE_NAME) do
+ rc = RegUnLoadKey(HKEY_USERS, "#{name}")
+ if rc != ERROR_SUCCESS
+ raise get_last_error(rc)
+ end
+ end
+ end
+
+ def run(*privileges)
+ token = [0].pack('L')
+
+ unless OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, token)
+ raise get_last_error
+ end
+ token = token.unpack('L')[0]
+
+ privileges.each do |name|
+ unless adjust_privilege(token, name, SE_PRIVILEGE_ENABLED)
+ raise get_last_error
+ end
+ end
+
+ begin
+ yield
+ ensure #disable privs
+ privileges.each do |name|
+ adjust_privilege(token, name, 0)
+ end
+ end
+ end
+
+ def adjust_privilege(token, priv, attr=0)
+ luid = [0,0].pack('Ll')
+ if LookupPrivilegeValue(nil, priv, luid)
+ new_state = [1, luid.unpack('Ll'), attr].flatten.pack('LLlL')
+ AdjustTokenPrivileges(token, 0, new_state, new_state.size, 0, 0)
+ end
+ end
+ end
+end \ No newline at end of file
diff --git a/metadata.rb b/metadata.rb
new file mode 100644
index 0000000..1beaa6c
--- /dev/null
+++ b/metadata.rb
@@ -0,0 +1,8 @@
+maintainer "Opscode, Inc."
+maintainer_email "cookbooks@opscode.com"
+license "Apache 2.0"
+description "Provides a set of useful Windows-specific primitives."
+long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
+version "1.2.4"
+supports "windows"
+depends "chef_handler"
diff --git a/providers/auto_run.rb b/providers/auto_run.rb
new file mode 100644
index 0000000..36d84d6
--- /dev/null
+++ b/providers/auto_run.rb
@@ -0,0 +1,32 @@
+#
+# Author:: Paul Morotn (<pmorton@biaprotect.com>)
+# Cookbook Name:: windows
+# Provider:: auto_run
+#
+# Copyright:: 2011, Business Intelligence Associates, Inc
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+action :create do
+ windows_registry 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run' do
+ values new_resource.name => "\"#{new_resource.program}\" #{new_resource.args}"
+ end
+end
+
+action :remove do
+ windows_registry 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run' do
+ values new_resource.name => ''
+ action :remove
+ end
+end \ No newline at end of file
diff --git a/providers/batch.rb b/providers/batch.rb
new file mode 100644
index 0000000..9aa347c
--- /dev/null
+++ b/providers/batch.rb
@@ -0,0 +1,62 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windws
+# Provider:: batch
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+require 'tempfile'
+require 'chef/resource/execute'
+
+action :run do
+ begin
+ script_file.puts(@new_resource.code)
+ script_file.close
+ set_owner_and_group
+
+ # cwd hax...shell_out on windows needs to support proper 'cwd'
+ # follow CHEF-2357 for more
+ cwd = @new_resource.cwd ? "cd \"#{@new_resource.cwd}\" & " : ""
+
+ r = Chef::Resource::Execute.new(@new_resource.name, run_context)
+ r.user(@new_resource.user)
+ r.group(@new_resource.group)
+ r.command("#{cwd}call \"#{script_file.path}\" #{@new_resource.flags}")
+ r.creates(@new_resource.creates)
+ r.returns(@new_resource.returns)
+ r.run_action(:run)
+
+ @new_resource.updated_by_last_action(r.updated_by_last_action?)
+ ensure
+ unlink_script_file
+ end
+end
+
+private
+def set_owner_and_group
+ # FileUtils itself implements a no-op if +user+ or +group+ are nil
+ # You can prove this by running FileUtils.chown(nil,nil,'/tmp/file')
+ # as an unprivileged user.
+ FileUtils.chown(@new_resource.user, @new_resource.group, script_file.path)
+end
+
+def script_file
+ @script_file ||= Tempfile.open(['chef-script', '.bat'])
+end
+
+def unlink_script_file
+ @script_file && @script_file.close!
+end
diff --git a/providers/feature_dism.rb b/providers/feature_dism.rb
new file mode 100644
index 0000000..61e443a
--- /dev/null
+++ b/providers/feature_dism.rb
@@ -0,0 +1,47 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Provider:: feature_dism
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+include Chef::Provider::WindowsFeature::Base
+include Chef::Mixin::ShellOut
+include Windows::Helper
+
+def install_feature(name)
+ shell_out!("#{dism} /online /enable-feature /featurename:#{@new_resource.feature_name} /norestart")
+end
+
+def remove_feature(name)
+ shell_out!("#{dism} /online /disable-feature /featurename:#{@new_resource.feature_name} /norestart")
+end
+
+def installed?
+ @installed ||= begin
+ cmd = shell_out("#{dism} /online /Get-Features")
+ cmd.stderr.empty? && (cmd.stdout =~ /^Feature Name : #{@new_resource.feature_name}$\n^State : Enabled$/i)
+ end
+end
+
+private
+# account for File System Redirector
+# http://msdn.microsoft.com/en-us/library/aa384187(v=vs.85).aspx
+def dism
+ @dism ||= begin
+ locate_sysnative_cmd("dism.exe")
+ end
+end \ No newline at end of file
diff --git a/providers/feature_servermanagercmd.rb b/providers/feature_servermanagercmd.rb
new file mode 100644
index 0000000..9802b97
--- /dev/null
+++ b/providers/feature_servermanagercmd.rb
@@ -0,0 +1,47 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Provider:: feature_servermanagercmd
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+include Chef::Provider::WindowsFeature::Base
+include Chef::Mixin::ShellOut
+include Windows::Helper
+
+def install_feature(name)
+ shell_out!("#{servermanagercmd} -install #{@new_resource.feature_name}")
+end
+
+def remove_feature(name)
+ shell_out!("#{servermanagercmd} -remove #{@new_resource.feature_name}")
+end
+
+def installed?
+ @installed ||= begin
+ cmd = shell_out("#{servermanagercmd} -query")
+ cmd.stderr.empty? && (cmd.stdout =~ /^\s*?\[X\]\s.+?\s\[#{@new_resource.feature_name}\]$/i)
+ end
+end
+
+private
+# account for File System Redirector
+# http://msdn.microsoft.com/en-us/library/aa384187(v=vs.85).aspx
+def servermanagercmd
+ @servermanagercmd ||= begin
+ locate_sysnative_cmd("servermanagercmd.exe")
+ end
+end \ No newline at end of file
diff --git a/providers/package.rb b/providers/package.rb
new file mode 100644
index 0000000..3f8d515
--- /dev/null
+++ b/providers/package.rb
@@ -0,0 +1,250 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Provider:: package
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+if RUBY_PLATFORM =~ /mswin|mingw32|windows/
+ require 'win32/registry'
+end
+
+require 'chef/mixin/shell_out'
+require 'chef/mixin/language'
+
+include Chef::Mixin::ShellOut
+include Windows::Helper
+
+# the logic in all action methods mirror that of
+# the Chef::Provider::Package which will make
+# refactoring into core chef easy
+
+action :install do
+ # If we specified a version, and it's not the current version, move to the specified version
+ if @new_resource.version != nil && @new_resource.version != @current_resource.version
+ install_version = @new_resource.version
+ # If it's not installed at all, install it
+ elsif @current_resource.version == nil
+ install_version = candidate_version
+ end
+
+ if install_version
+ Chef::Log.info("Installing #{@new_resource} version #{install_version}")
+ status = install_package(@new_resource.package_name, install_version)
+ if status
+ @new_resource.updated_by_last_action(true)
+ end
+ end
+end
+
+action :upgrade do
+ if @current_resource.version != candidate_version
+ orig_version = @current_resource.version || "uninstalled"
+ Chef::Log.info("Upgrading #{@new_resource} version from #{orig_version} to #{candidate_version}")
+ status = upgrade_package(@new_resource.package_name, candidate_version)
+ if status
+ @new_resource.updated_by_last_action(true)
+ end
+ end
+end
+
+action :remove do
+ if removing_package?
+ Chef::Log.info("Removing #{@new_resource}")
+ remove_package(@current_resource.package_name, @new_resource.version)
+ @new_resource.updated_by_last_action(true)
+ else
+ end
+end
+
+def removing_package?
+ if @current_resource.version.nil?
+ false # nothing to remove
+ elsif @new_resource.version.nil?
+ true # remove any version of a package
+ elsif @new_resource.version == @current_resource.version
+ true # remove the version we have
+ else
+ false # we don't have the version we want to remove
+ end
+end
+
+def expand_options(options)
+ options ? " #{options}" : ""
+end
+
+# these methods are the required overrides of
+# a provider that extends from Chef::Provider::Package
+# so refactoring into core Chef should be easy
+
+def load_current_resource
+ @current_resource = Chef::Resource::WindowsPackage.new(@new_resource.name)
+ @current_resource.package_name(@new_resource.package_name)
+ @current_resource.version(nil)
+
+ unless current_installed_version.nil?
+ @current_resource.version(current_installed_version)
+ end
+
+ @current_resource
+end
+
+def current_installed_version
+ @current_installed_version ||= begin
+ if installed_packages.include?(@new_resource.package_name)
+ installed_packages[@new_resource.package_name][:version]
+ end
+ end
+end
+
+def candidate_version
+ @candidate_version ||= begin
+ @new_resource.version || 'latest'
+ end
+end
+
+def install_package(name,version)
+ Chef::Log.debug("Processing #{@new_resource} as a #{installer_type} installer.")
+ install_args = [cached_file(@new_resource.source, @new_resource.checksum), expand_options(unattended_installation_flags), expand_options(@new_resource.options)]
+ Chef::Log.info("Starting installation...this could take awhile.")
+ shell_out!(sprintf(install_command_template, *install_args), {:returns => [0,42]})
+end
+
+def remove_package(name, version)
+ uninstall_string = installed_packages[@new_resource.package_name][:uninstall_string]
+ Chef::Log.info("Registry provided uninstall string for #{@new_resource} is '#{uninstall_string}'")
+ uninstall_command = begin
+ if uninstall_string =~ /msiexec/i
+ "#{uninstall_string} /qn"
+ else
+ uninstall_string.gsub!('"','')
+ "start /wait /d\"#{::File.dirname(uninstall_string)}\" #{::File.basename(uninstall_string)}#{expand_options(@new_resource.options)} /S"
+ end
+ end
+ Chef::Log.info("Removing #{@new_resource} with uninstall command '#{uninstall_command}'")
+ shell_out!(uninstall_command, {:returns => [0,42]})
+end
+
+private
+
+def install_command_template
+ case installer_type
+ when :msi
+ "msiexec%2$s %1$s%3$s"
+ else
+ "start /wait %1$s%2$s%3$s"
+ end
+end
+
+def uninstall_command_template
+ case installer_type
+ when :msi
+ "msiexec %2$s %1$s"
+ else
+ "start /wait /d\"%1$s\" %2$s %3$s"
+ end
+end
+
+# http://unattended.sourceforge.net/installers.php
+def unattended_installation_flags
+ case installer_type
+ when :msi
+ "/qb /i"
+ when :installshield
+ "/s /sms"
+ when :nsis
+ "/S /NCRC"
+ when :inno
+ #"/sp- /silent /norestart"
+ "/verysilent /norestart"
+ when :wise
+ "/s"
+ else
+ end
+end
+
+def installed_packages
+ @installed_packages || begin
+ installed_packages = {}
+ # Computer\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
+ installed_packages.merge!(extract_installed_packages_from_key(Win32::Registry::HKEY_LOCAL_MACHINE)) #rescue nil
+ # 64-bit registry view
+ # Computer\HKEY_LOCAL_MACHINE\Software\Wow6464Node\Microsoft\Windows\CurrentVersion\Uninstall
+ installed_packages.merge!(extract_installed_packages_from_key(Win32::Registry::HKEY_LOCAL_MACHINE, (Win32::Registry::Constants::KEY_READ | 0x0100))) #rescue nil
+ # 32-bit registry view
+ # Computer\HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
+ installed_packages.merge!(extract_installed_packages_from_key(Win32::Registry::HKEY_LOCAL_MACHINE, (Win32::Registry::Constants::KEY_READ | 0x0200))) #rescue nil
+ # Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall
+ installed_packages.merge!(extract_installed_packages_from_key(Win32::Registry::HKEY_CURRENT_USER)) #rescue nil
+ # require 'pp'
+ # pp installed_packages
+ installed_packages
+ end
+end
+
+def extract_installed_packages_from_key(hkey = Win32::Registry::HKEY_LOCAL_MACHINE, desired = Win32::Registry::Constants::KEY_READ)
+ uninstall_subkey = 'Software\Microsoft\Windows\CurrentVersion\Uninstall'
+ packages = {}
+ begin
+ Win32::Registry.open(hkey, uninstall_subkey, desired) do |reg|
+ reg.each_key do |key, wtime|
+ k = reg.open(key)
+ display_name = k["DisplayName"] rescue nil
+ version = k["DisplayVersion"] rescue "NO VERSION"
+ uninstall_string = k["UninstallString"] rescue nil
+
+ if display_name
+ packages[display_name] = {:name => display_name,
+ :version => version,
+ :uninstall_string => uninstall_string}
+ end
+ end
+ end
+ rescue Win32::Registry::Error
+ end
+ packages
+end
+
+def installer_type
+ @installer_type || begin
+ if @new_resource.installer_type
+ @new_resource.installer_type
+ else
+ basename = ::File.basename(cached_file(@new_resource.source))
+ if basename.split(".").last == "msi" # Microsoft MSI
+ :msi
+ else
+ # search the binary file for installer type
+ contents = ::Kernel.open(::File.expand_path(cached_file(@new_resource.source)), "rb") {|io| io.read } # TODO limit data read in
+ case contents
+ when /inno/i # Inno Setup
+ :inno
+ when /wise/i # Wise InstallMaster
+ :wise
+ when /nsis/i # Nullsoft Scriptable Install System
+ :nsis
+ else
+ # if file is named 'setup.exe' assume installshield
+ if basename == "setup.exe"
+ :installshield
+ else
+ raise Chef::Exceptions::AttributeNotFound, "installer_type could not be determined, please set manually"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/providers/path.rb b/providers/path.rb
new file mode 100644
index 0000000..7f4a97b
--- /dev/null
+++ b/providers/path.rb
@@ -0,0 +1,27 @@
+#
+# Author:: Paul Morotn (<pmorton@biaprotect.com>)
+# Cookbook Name:: windows
+# Provider:: path
+#
+# Copyright:: 2011, Business Intelligence Associates, Inc
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+action :add do
+ env "PATH" do
+ action :modify
+ delim ::File::PATH_SEPARATOR
+ value new_resource.path
+ end
+end
diff --git a/providers/reboot.rb b/providers/reboot.rb
new file mode 100644
index 0000000..4fc5032
--- /dev/null
+++ b/providers/reboot.rb
@@ -0,0 +1,31 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Provider:: reboot
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+action :request do
+ node.run_state[:reboot_requested] = true
+ node.run_state[:reboot_timeout] = @new_resource.timeout
+ node.run_state[:reboot_reason] = @new_resource.reason
+end
+
+action :cancel do
+ node.run_state.delete(:reboot_requested)
+ node.run_state.delete(:reboot_timeout)
+ node.run_state.delete(:reboot_reason)
+end
diff --git a/providers/registry.rb b/providers/registry.rb
new file mode 100644
index 0000000..914b373
--- /dev/null
+++ b/providers/registry.rb
@@ -0,0 +1,70 @@
+#
+# Author:: Doug MacEachern (<dougm@vmware.com>)
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Author:: Paul Morton (<pmorton@biaprotect.com>)
+# Cookbook Name:: windows
+# Provider:: registry
+#
+# Copyright:: 2010, VMware, Inc.
+# Copyright:: 2011, Opscode, Inc.
+# Copyright:: 2011, Business Intelligence Associates, Inc
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+include Windows::RegistryHelper
+
+action :create do
+ registry_update(:create)
+end
+
+action :modify do
+ registry_update(:open)
+end
+
+action :force_modify do
+ require 'timeout'
+ Timeout.timeout(120) do
+ @new_resource.values.each do |value_name, value_data|
+ 5.times do |x|
+ desired_value_data = value_data
+ current_value_data = get_value(@new_resource.key_name.dup, value_name.dup)
+ if current_value_data.to_s == desired_value_data.to_s
+ Chef::Log.debug("#{@new_resource} value [#{value_name}] desired [#{desired_value_data}] data already set. Check #{x+1}/5.")
+ else
+ Chef::Log.debug("#{@new_resource} value [#{value_name}] current [#{current_value_data}] data not equal to desired [#{desired_value_data}] data. Setting value and restarting check loop.")
+ begin
+ registry_update(:open)
+ rescue Exception
+ registry_update(:create)
+ end
+ retry # start count loop over
+ end
+ end
+ end
+ break
+ end
+end
+
+action :remove do
+ delete_value(@new_resource.key_name,@new_resource.values)
+end
+
+private
+def registry_update(mode)
+
+ Chef::Log.debug("Registry Mode (#{mode})")
+ updated = set_value(mode,@new_resource.key_name,@new_resource.values)
+ @new_resource.updated_by_last_action(updated)
+
+end
diff --git a/providers/zipfile.rb b/providers/zipfile.rb
new file mode 100644
index 0000000..cc287d9
--- /dev/null
+++ b/providers/zipfile.rb
@@ -0,0 +1,54 @@
+#
+# Author:: Doug MacEachern (<dougm@vmware.com>)
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Provider:: unzip
+#
+# Copyright:: 2010, VMware, Inc.
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+include Windows::Helper
+
+action :unzip do
+ ensure_rubyzip_gem_installed
+ Chef::Log.debug("unzip #{@new_resource.source} => #{@new_resource.path} (overwrite=#{@new_resource.overwrite})")
+
+ Zip::ZipFile.open(cached_file(@new_resource.source)) do |zip|
+ zip.each do |entry|
+ path = ::File.join(@new_resource.path, entry.name)
+ FileUtils.mkdir_p(::File.dirname(path))
+ if @new_resource.overwrite && ::File.exists?(path) && !::File.directory?(path)
+ FileUtils.rm(path)
+ end
+ zip.extract(entry, path)
+ end
+ end
+ @new_resource.updated_by_last_action(true)
+end
+
+private
+def ensure_rubyzip_gem_installed
+ begin
+ require 'zip/zip'
+ rescue LoadError
+ Chef::Log.info("Missing gem 'rubyzip'...installing now.")
+ gem_package "rubyzip" do
+ action :nothing
+ end.run_action(:install)
+ Gem.clear_paths
+ require 'zip/zip'
+ end
+end \ No newline at end of file
diff --git a/recipes/default.rb b/recipes/default.rb
new file mode 100644
index 0000000..18a9bea
--- /dev/null
+++ b/recipes/default.rb
@@ -0,0 +1,34 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Recipe:: default
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# gems with precompiled binaries
+%w{ win32-api win32-service }.each do |win_gem|
+ gem_package win_gem do
+ options '--platform=mswin32'
+ action :install
+ end
+end
+
+# the rest
+%w{ windows-api windows-pr win32-dir win32-event win32-mutex }.each do |win_gem|
+ gem_package win_gem do
+ action :install
+ end
+end
diff --git a/recipes/reboot_handler.rb b/recipes/reboot_handler.rb
new file mode 100644
index 0000000..4aa2f02
--- /dev/null
+++ b/recipes/reboot_handler.rb
@@ -0,0 +1,33 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Recipe:: restart_handler
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+remote_directory node['chef_handler']['handler_path'] do
+ source 'handlers'
+ mode "0755"
+ recursive true
+ action :create
+end
+
+chef_handler 'WindowsRebootHandler' do
+ source "#{node['chef_handler']['handler_path']}/windows_reboot_handler.rb"
+ arguments node['windows']['allow_pending_reboots']
+ supports :report => true, :exception => false
+ action :enable
+end
diff --git a/resources/auto_run.rb b/resources/auto_run.rb
new file mode 100644
index 0000000..7beecc5
--- /dev/null
+++ b/resources/auto_run.rb
@@ -0,0 +1,30 @@
+#
+# Author:: Paul Morotn (<pmorton@biaprotect.com>)
+# Cookbook Name:: windows
+# Resource:: auto_run
+#
+# Copyright:: 2011, Business Intelligence Associates, Inc
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+def initialize(name,run_context=nil)
+ super
+ @action = :create
+end
+
+actions :create, :remove
+
+attribute :program, :kind_of => String
+attribute :name, :kind_of => String, :name_attribute => true
+attribute :args, :kind_of => String, :default => ''
diff --git a/resources/batch.rb b/resources/batch.rb
new file mode 100644
index 0000000..7d4e917
--- /dev/null
+++ b/resources/batch.rb
@@ -0,0 +1,36 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Resource:: batch
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+actions :run
+
+attribute :command, :kind_of => String, :name_attribute => true
+attribute :cwd, :kind_of => String, :default => nil
+attribute :code, :kind_of => String, :default => nil
+attribute :user, :kind_of => [ String, Integer ], :default => nil
+attribute :group, :kind_of => [ String, Integer ], :default => nil
+attribute :creates, :kind_of => [ String ], :default => nil
+attribute :flags, :kind_of => [ String ], :default => nil
+attribute :returns, :kind_of => [Integer, Array], :default => 0
+
+def initialize(name, run_context=nil)
+ super
+ @action = :run
+ @command = name
+end
diff --git a/resources/feature.rb b/resources/feature.rb
new file mode 100644
index 0000000..b67c0fb
--- /dev/null
+++ b/resources/feature.rb
@@ -0,0 +1,40 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Resource:: feature
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+include Windows::Helper
+
+actions :install, :remove
+
+attribute :feature_name, :kind_of => String, :name_attribute => true
+
+def initialize(name, run_context=nil)
+ super
+ @action = :install
+ @provider = lookup_provider_constant(locate_default_provider)
+end
+
+private
+def locate_default_provider
+ if ::File.exists?(locate_sysnative_cmd('dism.exe'))
+ :windows_feature_dism
+ elsif ::File.exists?(locate_sysnative_cmd('servermanagercmd.exe'))
+ :windows_feature_servermanagercmd
+ end
+end \ No newline at end of file
diff --git a/resources/package.rb b/resources/package.rb
new file mode 100644
index 0000000..9729d9b
--- /dev/null
+++ b/resources/package.rb
@@ -0,0 +1,36 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Resource:: package
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+actions :install, :remove
+
+attribute :package_name, :kind_of => String, :name_attribute => true
+attribute :source, :kind_of => String, :required => true
+attribute :version, :kind_of => String
+attribute :options, :kind_of => String
+attribute :installer_type, :kind_of => Symbol, :default => nil, :equal_to => [:msi, :inno, :nsis, :wise, :installshield, :custom]
+attribute :checksum, :kind_of => String
+
+# TODO
+
+# add preseeding support
+#attribute :response_file
+
+# allow target dirtory of installation to be set
+#attribute :target_dir \ No newline at end of file
diff --git a/resources/path.rb b/resources/path.rb
new file mode 100644
index 0000000..2d71ab0
--- /dev/null
+++ b/resources/path.rb
@@ -0,0 +1,28 @@
+#
+# Author:: Paul Morotn (<pmorton@biaprotect.com>)
+# Cookbook Name:: windows
+# Resource:: path
+#
+# Copyright:: 2011, Business Intelligence Associates, Inc
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+def initialize(name,run_context=nil)
+ super
+ @action = :add
+end
+
+actions :add
+
+attribute :path, :kind_of => String, :name_attribute => true
diff --git a/resources/reboot.rb b/resources/reboot.rb
new file mode 100644
index 0000000..c788927
--- /dev/null
+++ b/resources/reboot.rb
@@ -0,0 +1,29 @@
+#
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Resource:: reboot
+#
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+actions :request, :cancel
+
+attribute :timeout, :kind_of => Integer, :default => 60, :name_attribute => true
+attribute :reason, :kind_of => String, :default => ''
+
+def initialize(name,run_context=nil)
+ super
+ @action = :request
+end
diff --git a/resources/registry.rb b/resources/registry.rb
new file mode 100644
index 0000000..5b44d2c
--- /dev/null
+++ b/resources/registry.rb
@@ -0,0 +1,32 @@
+#
+# Author:: Doug MacEachern (<dougm@vmware.com>)
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Resource:: registry
+#
+# Copyright:: 2010, VMware, Inc.
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+actions :create, :modify, :force_modify, :remove
+
+attribute :key_name, :kind_of => String, :name_attribute => true
+attribute :values, :kind_of => Hash
+
+def initialize(name, run_context=nil)
+ super
+ @action = :modify
+ @key_name = name
+end
diff --git a/resources/zipfile.rb b/resources/zipfile.rb
new file mode 100644
index 0000000..727cd07
--- /dev/null
+++ b/resources/zipfile.rb
@@ -0,0 +1,32 @@
+#
+# Author:: Doug MacEachern (<dougm@vmware.com>)
+# Author:: Seth Chisamore (<schisamo@opscode.com>)
+# Cookbook Name:: windows
+# Resource:: unzip
+#
+# Copyright:: 2010, VMware, Inc.
+# Copyright:: 2011, Opscode, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+actions :unzip # TODO , :zip
+
+attribute :path, :kind_of => String, :default => ".", :name_attribute => true
+attribute :source, :kind_of => String
+attribute :overwrite, :kind_of => [ TrueClass, FalseClass ], :default => false
+
+def initialize(name, run_context=nil)
+ super
+ @action = :unzip
+end