Error “Cannot unregister the machine” on Jenkins, ‘kitchen test’ command

2017/04/06

Ok, it’s a hack… so don’t use it unless you need it, and on your own risk.
For some reason, although the Windows vagrant box is updated using Matt Wrock’s packer templates from here https://github.com/mwrock/packer-templates, and everything goes well, and also on the first manual kitchen test on the Jenkins server everything goes ok, when run from Jenkin’s pipeline mechanism, the box is not destroyed.
Three VirtualBox processes remain hanged in the system.
It’s not a clean solution, but having this error over and over again:

STDERR: There was an error while executing `VBoxManage`, a CLI used by Vagrant for controlling VirtualBox. The command and stderr is shown below.
Command: [“unregistervm”, “some GUID here”, “–delete”]
Stderr: VBoxManage.exe: error: Cannot unregister the machine ‘kitchen-your_cookbook-default-windows2012r2_default_some_numbers’ while it is locked
VBoxManage.exe: error: Details: code VBOX_E_INVALID_OBJECT_STATE (0x80bb0007), component MachineWrap, interface IMachine, callee IUnknown

it’s really annoying, so until the final solution will reveal itself, this might also be a way:

$cookbook = ‘your_cookbook_name’
gwmi -Query “select * from win32_process where name = ‘virtualbox.exe'” | `
? { $_.CommandLine.Contains(“kitchen-$cookbook”)} | `
Select CommandLine, Handle | `
% { Get-Process -Id $_.Handle } | `
Stop-Process -Force -ErrorAction Continue

You’ll need to execute it from Groovy with the bat command, something like

bat “powershell -File \”../killVBoxes.ps1\” ${cookbookName}”

For the path of the PowerShell script you’ll need to provide the correct path.

Note: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.

Advertisements

Clean VirtualBox virtual machines used by Chef on converge

2017/03/31

From time to time I keep getting strange behavior, on local PC, with virtual machines used by Chef, maybe after a ChefDK or VirtualBox update.
Some VMs do not get destroyed properly, or maybe more than one VM is created for the same cookbook.
The following PowerShell script can be used to destroy all VMs for a Chef cookbook; it must be used from the parent folder of the cookbook, using the syntax:
.\clearCache.ps1 my_chef_cookbook .
And here the script clearCache.ps1, located one level above the cookbook, in order to be usable with all its siblings:

[CmdletBinding()]
param(
[string]$cookbook
)

# VBOX_HOME is a user environment variable specifying
# where the VirtualBox VMs are stored
# Something like C:\Users\[your_user]\VBox_VMs

$dir = (pwd).Path
cd $cookbook
Write-Output “Removing folder content for .kitchen”
rm “.\.kitchen\” -Force -Recurse

Write-Output “Power-off VMs”
((& ‘C:\Program Files\Oracle\VirtualBox\vboxmanage’ list vms) | `
  % { ($_.Replace(‘”‘,”) -split ” “)[0] } | ` # Replace double quotes with nothing
  ? { $_.Contains(“kitchen-“) }) | `
  % { & ‘C:\Program Files\Oracle\VirtualBox\vboxmanage’ controlvm $_ poweroff }
Write-Output “Delete VMs”
((& ‘C:\Program Files\Oracle\VirtualBox\vboxmanage’ list vms) | `
  % { ($_.Replace(‘”‘,”) -split ” “)[0] } | `
  ? { $_.Contains(“kitchen-“) }) | `
  % { & ‘C:\Program Files\Oracle\VirtualBox\vboxmanage’ unregistervm $_ –delete }

Write-Output “Delete the VMs again, just in case we previously had an error …”
rm “$($env.VBOX_HOME)\kitchen-$cookbook*” -Force -Recurse

Write-Output “Destroy kitchen”
kitchen destroy
rm “.\.kitchen\” -Force -Recurse
vagrant global-status –prune
Write-Output “Done”
ls
cd ..

Note: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


Get folder files recursively in Ruby, without empty folders

2017/03/09

I’ve used the code below to retrieve the files from a folder recursively when I needed to process only the files, but not the subfolders.
The files from subfolders are also included, but not the directories, I wanted especially to omit ” . ” and ” .. ” :

@files = ::Dir.glob(::File.join(source_folder, ‘**/*’), ::File::FNM_DOTMATCH).reject { |p| ::File.directory? p }

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


Disable Skype ads

2017/03/06

Add to blocked sites the addresses apps.skype.com and g.msn.com.
This can be done through Control Panel settings or through the hosts file.

  • For the first method, go to Control Panel > Network and Internet > Internet Options > Security tab > Restricted Sites > open Sites and add the 2 websites to the list
  • For hosts file method, this file is generally found at C:\Windows\Systems32\drivers\etc ( unless you have a specific Windows folder, in which case try %WINDIR%\system32 ) ; it is usually a hidden folder, so you’ll have to display hidden files in Windows Explorer ( via View options -> Folder Options )
    Add to this file 2 lines with the 2 websites pointing to 0.0.0.0 or 127.0.0.1 (if in doubt, check the examples commented in the hosts file)

One more setting is needed:
Close Skype and then go to Users > [Your Windows Username] > AppData > Roaming > Skype > [Your Skype account name] > config.xml , open the file and search for AdvertPlaceholder , for which you’ll have to change the value of 1 to 0 .

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


Download OReilly free books with PowerShell through PasteBin

2017/01/10
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)] [string]$DestinationFolder,
    [Parameter(Mandatory=$false)] [string]$OReillyPasteBinRawUrl = ‘http://pastebin.com/raw/nyFtp2EG‘,
    [Parameter(Mandatory=$false)] [bool]$SimulateSleepBetweenDownloads = $true
)

Import-Module BitsTransfer

function Download-File
{
    param([string] $UrlSource, [string] $Destination)
    $random = Get-Random -Minimum 1 -Maximum 5
    Write-Output “Downloading $filename”
    Start-BitsTransfer -Source $UrlSource -Destination $Destination
    if ($SimulateSleepBetweenDownloads) {
        Write-Output ”    Sleeping $(4 + $random) seconds”
        Start-Sleep -s (4 + $random)
    }
}

$tmpFile = New-TemporaryFile
Set-Content -Path ($tmpFile.FullName) -Value ((Invoke-WebRequest -Uri $OReillyPasteBinRawUrl).Content)

$reader = [System.IO.File]::OpenText($tmpFile.FullName)
while($null -ne ($url = $reader.ReadLine())) {
    $filename = $URL.Substring($URL.LastIndexOf(“/”) + 1)
    $destPath = (Join-Path $DestinationFolder $filename)
    if (!(Test-Path $destPath)) {
        Download-File -UrlSource $url -Destination $destPath
    }
    else {
        if ((Get-Item $destPath).Length -le 0) {
            Download-File -UrlSource $url -Destination $destPath
        }
        else {
            Write-Output “Skipping $filename ; already downloaded”
        }
    }
}

After that, use the script like that:

.\downloadOreallyBooks.ps1 -DestinationFolder E:\temp\ -SimulateSleepBetweenDownloads $false

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


Stub Chef guard_interpreter for ChefSpec test

2016/12/20

If you have a Chef cookbook with a resource containing a “guardian”, like, let’s say a PowerShell guard interpreter, you must stub the content of the Chef guard.
Here is an example of the resource using the guardian:

file “some_log_path” do
  guard_interpreter :powershell_script
  action :delete
  not_if “(ls -Dir ‘C:\temp’).Name.Contains(‘build’)”
end

Here’s how you have to construct your ChefSpec file:

describe ‘my_cookbook::my_recipe’ do
  let(:chef_run) do
    ChefSpec::ServerRunner.new do |node, server|
      stub_chef_server(node, server)
    end.converge(described_recipe)
  end

  before do
    stub_command(“(ls -Dir ‘C:\temp’).Name.Contains(‘build’)”).and_return(false)
  end

  it ‘does not raise an exception’ do
    expect { chef_run }.to_not raise_error
  end

  it ‘deletes the existing log file’ do
    expect(chef_run).to delete_file(‘C:\temp\releases\some_build\log.txt’)
  end
end


Verify if a Chocolatey package is installed

2016/12/19
(choco list –lo | % { $_ -match “winmerge” }).contains($true)
(choco list –lo | % { $_ -match “sdfsdfds” }).contains($true)

%d bloggers like this: