Sha256: d69c7c7811b5e6b291e90aab3448b8c752b68438c96f511f3401ccd7891896c9

Contents?: true

Size: 1.62 KB

Versions: 2

Compression:

Stored size: 1.62 KB

Contents

module Datacenter
  module Shell
    class Remote
      
      def initialize(*args)
        @args = args
      end

      def open
        @session ||= Net::SSH.start(*args)
      end

      def close
        if session && !session.closed?
          session.close
          @session = nil
        end
      end

      def run(command, options={})
        if session
          run! command, options
        else
          self.class.open(*args) { |shell| shell.run command, options }
        end
      end

      def self.open(*args)
        shell = new(*args)
        shell.open
        yield shell
      ensure
        shell.close
      end

      private

      attr_reader :args, :session

      def run!(command, options={})
        Datacenter.logger.debug(self.class) { command }

        result = ''
        error = ''
        
        out = options[:out] || StringIO.new
        err = options[:err] || StringIO.new

        exit_code = nil

        session.open_channel do |channel|
          channel.exec(command) do |ch, success|
            abort "FAILED: couldn't execute command (ssh.channel.exec)" unless success
            
            channel.on_data do |ch, data|
              out << data
              result << data
            end

            channel.on_extended_data do |ch, type, data|
              err << data
              error << data
            end

            channel.on_request('exit-status') do |ch, data|
              exit_code = data.read_long
            end
          end
        end

        session.loop

        raise CommandError.new(command, error) unless exit_code == 0

        result
      end

    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
datacenter-0.5.1 lib/datacenter/shell/remote.rb
datacenter-0.5.0 lib/datacenter/shell/remote.rb