require 'picsolve_docker_builder/base' require 'fileutils' require 'securerandom' module PicsolveDockerBuilder module Helpers # Ruby class that forwards a ssh auth socket into a docker container class SshAuthForwarding include PicsolveDockerBuilder::Base def initialize fail 'Environment var SSH_AUTH_SOCK not found, ssh forward impossible' \ if env_ssh_auth_sock.nil? end def generate_dir_path File.join( File.dirname(env_ssh_auth_sock), "docker_builder_temp_#{SecureRandom.hex(2)}" ) end def create_dir dir = generate_dir_path begin Dir.mkdir(dir, 0700) # ensure cleanup at_exit do cleanup(dir) end rescue Errno::EEXIST FileUtils.rm_rf(dir) log.warn "Directory '#{dir}' already exists, removing it" retry end log.debug \ "Creating temporary dir '#{dir}' for mapping auth socket into docker" FileUtils.chmod 0700, dir FileUtils.ln env_ssh_auth_sock, File.join(dir, 'ssh_auth_sock') dir end def cleanup(dir = nil) # return if nothing to do if dir.nil? if @dir.nil? return else dir = @dir @dir = nil end end log.debug "Removing temporary dir '#{dir}'" FileUtils.rm_rf(dir) end def dir @dir ||= create_dir end def env_var_name 'SSH_AUTH_SOCK' end def env_ssh_auth_sock ENV[env_var_name] end end end end