Sha256: ee6fca69f7fe305b9c32ce7bddb196b14a9b2be019e89ca4be6b8c45a81431f5

Contents?: true

Size: 1.96 KB

Versions: 1

Compression:

Stored size: 1.96 KB

Contents

module Deplomat
  class RemoteNode < Node

    def initialize(host:, port: 22, user: "deploy")
      super()

      # Create ControlMasters dir, user might not have it
      unless File.exists?("#{ENV['HOME']}/.ssh/controlmasters/")
        Dir.mkdir("#{ENV['HOME']}/.ssh/controlmasters/") 
      end

      # Establish connection
      first_ssh_command = "ssh -MNfS #{ENV['HOME']}/.ssh/controlmasters/%r@%h:%p #{user}@#{host} -p #{port} -o ControlPersist=10m"
      system first_ssh_command

      # get background process id by the full command name
      Sys::ProcTable.ps.each do |process|
        if process.cmdline.match(first_ssh_command)
          @pid = process.pid.to_i 
          puts "Connected with ssh, host #{host}, pid #{@pid}."
          break
        end
      end

      @ssh_command = "ssh -S #{ENV['HOME']}/.ssh/controlmasters/%r@%h:%p #{user}@#{host} -p #{port}"

      @host = host
      @user = user
      @port = port
    end

    alias :local_execute :execute
    def execute(command, path=@current_path, message: [], env_vars: '', login_shell: false, stdout_source: :stdout)

      log("(#{@host}) --> " + command + "\n", color: "white")
      command = "#{env_vars} cd #{path} && #{command}"  if path
      command = "bash -l -c \"#{command}\"" if login_shell
      super("#{@ssh_command} '#{command}'", nil, message: message, stdout_source: stdout_source, log_command: false)
    end

    def upload(what, where)
      local_execute "rsync -arz #{what} #{@user}@#{@host}:#{where} --port=#{@port}"
    end

    def close
      begin
        puts "Closing connection to #{@host}."
        Process.kill 'KILL', @pid
      rescue Errno::ESRCH
        puts "WARNING: no process with #{@pid} found, no connection to close!"
      end
    end

    private

      def path_exist?(path)
        old_raise_exceptions = @raise_exceptions
        @raise_exceptions    = false
        !(execute("ls #{path}", nil){ @raise_exceptions = old_raise_exceptions}[:status] > 0)
      end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
deplomat-0.1.1 lib/deplomat/remote_node.rb