Skip to content

Instantly share code, notes, and snippets.

@danhigham
Last active December 29, 2015 02:49
Show Gist options
  • Save danhigham/7602695 to your computer and use it in GitHub Desktop.
Save danhigham/7602695 to your computer and use it in GitHub Desktop.
Rake task to communicate with a faye server and provide connectivity to it's application container
namespace :remote_shell_agent do
module Faye
class Transport::Http < Transport
def request(envelopes)
content = encode(envelopes)
params = build_params(@endpoint, content)
request = create_request(params)
request.callback do
handle_response(request.response, envelopes)
store_cookies(request.response_header['SET_COOKIE'])
end
request.errback do
handle_error(envelopes)
end
end
private
def handle_response(response, envelopes)
message = MultiJson.load(response) rescue nil
if message
receive(envelopes, message)
else
handle_error(envelopes)
end
end
end
end
desc "Listen for tasks to execute"
task :listen => :environment do
require 'eventmachine'
require 'stringio'
require 'zlib'
require 'base64'
require 'json'
EM.run {
def eval_ruby(command)
template = <<-EOS
begin
$stdout = StringIO.new
#{command}
$stdout.string
rescue Exception => e
e.to_s
ensure
$stdout = STDOUT
end
EOS
eval(template)
end
client = Faye::Client.new('https://faye-dh.cfapps.io')
app = JSON.parse(ENV['VCAP_APPLICATION']);
guid = "#{app['application_version']}/#{app['instance_index']}"
client.subscribe("/commands/#{guid}") do |command|
console_type = command['console_type']
command_text = command['command']
result = ''
if (console_type == 'ruby')
result = eval_ruby(command_text)
else
result = `#{command_text} 2>&1`
end
compressed = Zlib::Deflate.deflate(result)
enc = Base64.encode64(compressed)
publication = client.publish("/responses/#{guid}", 'text' => enc)
end
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment