class VpsAdmin::CLI::Commands::VpsRemoteControl

Public Instance Methods

exec(args) click to toggle source
# File lib/vpsadmin/cli/commands/vps_remote_console.rb, line 77
def exec(args)
  if args.empty?
    puts "provide VPS ID as an argument"
    exit(false)
  end

  vps_id = args.first.to_i

  write "Locating VPS.."
  begin
    vps = @api.vps.show(vps_id, meta: { includes: 'node__location' })

  rescue HaveAPI::Client::ActionFailed => e
    puts "  error"
    puts e.message
    exit(false)
  end

  puts "  VPS is on #{vps.node.domain_name}, located in #{vps.node.location.label}."
  puts "Console router URL is #{vps.node.location.remote_console_server}"
  write "Obtaining authentication token..."

  begin
    t = vps.console_token.create

  rescue HaveAPI::Client::ActionFailed => e
    puts "  error"
    puts e.message
    exit(false)
  end

  @token = t.token

  puts
  puts "Connecting to remote console..."
  puts "Press ENTER ESC . to exit"
  puts

  raw_mode do
    EventMachine.run do
      @input = EventMachine.open_keyboard(InputHandler)

      @http = EventMachine::HttpRequest.new(
          "#{vps.node.location.remote_console_server}/console/feed/#{vps_id}"
      )
      communicate
    end
  end
end
options(opts) click to toggle source
# File lib/vpsadmin/cli/commands/vps_remote_console.rb, line 67
def options(opts)
  @opts = {
      rate: 0.05
  }

  opts.on('--refresh-rate MSEC', 'How often send and receive data, defaults to 50 ms') do |r|
    @opts[:rate] = r.to_i / 1000.0
  end
end

Protected Instance Methods

communicate() click to toggle source
# File lib/vpsadmin/cli/commands/vps_remote_console.rb, line 153
def communicate
  post = @http.post(
      body: {
          session: @token,
          keys: @input.buffer,
          width: @size[:width],
          height: @size[:height],
      },
      keepalive: true
  )

  @input.buffer = ''

  post.errback do
    puts "Error: connection to console router failed"
    EventMachine.stop
  end

  post.callback do
    ret = JSON.parse(post.response, symbolize_names: true)
    
    unless ret[:session]
      $stdout.write(ret[:data])
      puts "\nSession closed."
      EM.stop
      next
    end

    $stdout.write(Base64.decode64(ret[:data]))

    EM.add_timer(@opts[:rate]) { communicate }
  end
end
raw_mode() { || ... } click to toggle source
# File lib/vpsadmin/cli/commands/vps_remote_console.rb, line 133
def raw_mode
  state = `stty -g`
  `stty raw -echo -icanon -isig`

  pid = Process.fork do
    @size = Terminal.size!
    
    Signal.trap('WINCH') do
      @size = Terminal.size!
    end

    yield
  end

  Process.wait(pid) 

  `stty #{state}`
  puts
end
write(s) click to toggle source
# File lib/vpsadmin/cli/commands/vps_remote_console.rb, line 128
def write(s)
  $stdout.write(s)
  $stdout.flush
end