class Mybot::Node

Public Class Methods

new(host, user, options = {}) click to toggle source
# File lib/mybot/node.rb, line 8
def initialize(host, user, options = {})
  @host, @user, @options = host, user, options
end

Public Instance Methods

download(from, to, options = {}) click to toggle source
# File lib/mybot/node.rb, line 88
def download(from, to, options = {})
  print_cmd! "download", "#{from} -> #{to}", :green, :bold
  sftp.download!(from, to) do |event, uploader, *args|
    case event
    when :get
      size = 0
      if args[0].size
        size = args[0].size
      else
        size = sftp.stat!(from).size
      end
      n = (args[1].to_f * 100 / size.to_f).to_i
      print_progress(n)
    when :finish
      print_progress(100)
    end
  end
end
exists?(file) click to toggle source
# File lib/mybot/node.rb, line 67
def exists?(file)
  sftp.stat!(file) do |resp|
    return resp.ok?
  end
rescue Net::SFTP::StatusException
  false
end
run(cmd, options = {}) { |command| ... } click to toggle source
# File lib/mybot/node.rb, line 12
def run(cmd, options = {})
  command = Command.new
  yield command if block_given?

  ssh.open_channel do |ch|
    ch.request_pty do |ch, ok|
      abort "cannot request pty" unless ok
    end

    command.channel = ch

    options[:env] ||= {}
    options[:sudo] ||= false
    options[:cwd] ||= ""

    unless options[:env].empty?
      values = options[:env].map { |k, v| "#{k}='#{v}'" }.join " "
      cmd = "#{values} #{cmd}"
    end

    if options[:sudo]
      cmd = "sudo #{cmd}"
    end

    if options[:cwd] != ""
      cmd = "cd #{options[:cwd]} && #{cmd}"
    end

    print_cmd! "run", cmd, :green, :bold

    ch.exec cmd do |ch, ok|
      abort "cannot exec command" unless ok

      ch.on_data do |ch, data|
        command.handle_stdout data
      end

      ch.on_extended_data do |ch, type, data|
        command.handle_stderr data if type == 1
      end

      ch.on_request("exit-status") do |ch, data|
        command.exit = data.read_long
      end

      ch.on_close do |ch|
        command.handle_close
      end
    end
  end

  ssh.loop
  return command.result
end
upload(from, to, options = {}) click to toggle source
# File lib/mybot/node.rb, line 75
def upload(from, to, options = {})
  print_cmd! "upload", "#{from} -> #{to}", :green, :bold
  sftp.upload!(from, to) do |event, uploader, *args|
    case event
    when :put
      n = (args[1].to_f * 100 / args[0].size.to_f).to_i
      print_progress(n)
    when :finish
      print_progress(100)
    end
  end
end

Private Instance Methods

sftp() click to toggle source
# File lib/mybot/node.rb, line 113
def sftp
  @sftp ||= Net::SFTP.start @host, @user, @options
end
ssh() click to toggle source
# File lib/mybot/node.rb, line 109
def ssh
  @ssh ||= Net::SSH.start @host, @user, @options
end