|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'logging' |
| 4 | +require_relative '../../../bolt/node/errors' |
| 5 | + |
| 6 | +module Bolt |
| 7 | + module Transport |
| 8 | + class Jail < Simple |
| 9 | + class Connection |
| 10 | + attr_reader :user, :target |
| 11 | + |
| 12 | + def initialize(target) |
| 13 | + raise Bolt::ValidationError, "Target #{target.safe_name} does not have a host" unless target.host |
| 14 | + @target = target |
| 15 | + @user = @target.user || ENV['USER'] || Etc.getlogin |
| 16 | + @logger = Bolt::Logger.logger(target.safe_name) |
| 17 | + @jail_info = {} |
| 18 | + @logger.trace("Initializing jail connection to #{target.safe_name}") |
| 19 | + end |
| 20 | + |
| 21 | + def shell |
| 22 | + @shell ||= Bolt::Shell::Bash.new(target, self) |
| 23 | + end |
| 24 | + |
| 25 | + def reset_cwd? |
| 26 | + true |
| 27 | + end |
| 28 | + |
| 29 | + def jail_id |
| 30 | + @jail_info['jid'].to_s |
| 31 | + end |
| 32 | + |
| 33 | + def jail_path |
| 34 | + @jail_info['path'] |
| 35 | + end |
| 36 | + |
| 37 | + def connect |
| 38 | + output = JSON.parse(`jls --libxo=json`) |
| 39 | + @jail_info = output['jail-information']['jail'].select { |jail| jail['hostname'] == target.host }.first |
| 40 | + raise "Could not find a jail with name matching #{target.host}" if @jail_info.nil? |
| 41 | + @logger.trace { "Opened session" } |
| 42 | + true |
| 43 | + rescue StandardError => e |
| 44 | + raise Bolt::Node::ConnectError.new( |
| 45 | + "Failed to connect to #{target.safe_name}: #{e.message}", |
| 46 | + 'CONNECT_ERROR' |
| 47 | + ) |
| 48 | + end |
| 49 | + |
| 50 | + def execute(command) |
| 51 | + args = ['-lU', @user] |
| 52 | + |
| 53 | + jail_command = %w[jexec] + args + [jail_id] + Shellwords.split(command) |
| 54 | + @logger.trace { "Executing #{jail_command.join(' ')}" } |
| 55 | + |
| 56 | + Open3.popen3({}, *jail_command) |
| 57 | + rescue StandardError |
| 58 | + @logger.trace { "Command aborted" } |
| 59 | + raise |
| 60 | + end |
| 61 | + |
| 62 | + def upload_file(source, destination) |
| 63 | + @logger.trace { "Uploading #{source} to #{destination}" } |
| 64 | + jail_destination = File.join(jail_path, destination) |
| 65 | + FileUtils.cp(source, jail_destination) |
| 66 | + rescue StandardError => e |
| 67 | + raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR') |
| 68 | + end |
| 69 | + |
| 70 | + def download_file(source, destination, _download) |
| 71 | + @logger.trace { "Downloading #{source} to #{destination}" } |
| 72 | + jail_source = File.join(jail_path, source) |
| 73 | + FileUtils.mkdir_p(destination) |
| 74 | + FileUtils.cp(jail_source, destination) |
| 75 | + rescue StandardError => e |
| 76 | + raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR') |
| 77 | + end |
| 78 | + end |
| 79 | + end |
| 80 | + end |
| 81 | +end |
0 commit comments