Skip to content

Instantly share code, notes, and snippets.

@aschmidt75
Created September 6, 2014 20:17
Show Gist options
  • Save aschmidt75/bb38d971e4f47172e2de to your computer and use it in GitHub Desktop.
Save aschmidt75/bb38d971e4f47172e2de to your computer and use it in GitHub Desktop.
Serverspec/Specinfra backend for nsenter
require 'specinfra/backend/exec'
require 'open3'
module SpecInfra
module Backend
class Nsenter < Exec
def run_command(cmd, opt={})
cmd = build_command(cmd)
cmd = add_pre_command(cmd)
ret = nsenter_exec!(cmd)
ret[:stdout].gsub!(/\r\n/, "\n")
if @example
@example.metadata[:command] = cmd
@example.metadata[:stdout] = ret[:stdout]
end
CommandResult.new ret
end
def build_command(cmd)
cmd = super(cmd)
disable_sudo = SpecInfra.configuration.disable_sudo
if !disable_sudo
cmd = "#{sudo} #{cmd}"
cmd.gsub!(/(\&\&\s*!?\(?\s*)/, "\\1#{sudo} ")
cmd.gsub!(/(\|\|\s*!?\(?\s*)/, "\\1#{sudo} ")
end
cmd
end
def add_pre_command(cmd)
cmd = super(cmd)
pre_command = SpecInfra.configuration.pre_command
disable_sudo = SpecInfra.configuration.disable_sudo
if pre_command && !disable_sudo
cmd = "#{sudo} #{cmd}"
end
cmd
end
private
def nsenter_exec!(command)
puts "nsenter_exec! #{command}"
stdout_data = ''
stderr_data = ''
exit_status = nil
exit_signal = nil
pass_prompt = SpecInfra.configuration.pass_prompt || /^\[sudo\] password for/
pid = SpecInfra.configuration.nsenter_pid
stdout_data, stderr_data, exit_status = Open3.capture3(
"sudo nsenter --target #{pid} --mount --uts --ipc --net --pid -- #{command}")
{ :stdout => stdout_data, :stderr => stderr_data, :exit_status => exit_status, :exit_signal => exit_signal }
end
def sudo
sudo_path = SpecInfra.configuration.sudo_path
sudo_path += '/' if sudo_path
sudo_options = SpecInfra.configuration.sudo_options
if sudo_options
sudo_options = sudo_options.join(' ') if sudo_options.is_a?(Array)
sudo_options = ' ' + sudo_options
end
"#{sudo_path}sudo#{sudo_options}"
end
end
end
end
@sherzberg
Copy link

Does this work? Any updates since September?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment