Stream console output through HTTP (with Ruby)

女生的网名这么多〃 提交于 2019-11-30 11:37:24

问题


I am trying to run some commands remotely and SSH'ing in to the machine is not an option. What I am trying to do is setup a Sinatra app that runs some specific commands and streams the output through HTTP.

The sample action looks like this:

get "/log" do
  `tail -f some.log`
end

1 As far as I've read, I need to use Unicorn (or Mongrel) because Thin does not support streaming data 2 I think I need to pipe the commands output through some kind of IO ruby object

I almost know how to do (1) but have no idea how to achieve (2).


回答1:


If you're on a synchronous server (i.e. Mongrel, Unicorn, not Thin), you can just return an IO object:

require 'sinatra'

get '/log' do
  content_type :txt
  IO.popen('tail -f some.log')
end

If that doesn't work (if you're on Thin, for instance), you can use the new streaming API:

require 'sinatra'

get '/log' do
  content_type :txt
  IO.popen('tail -f some.log') do |io|
    stream do |out|
      io.each { |s| out << s }
    end
  end
end

You can also use the bcat gem, which will colorize your output, if it contains ANSI color codes:

require 'sinatra'
require 'bcat'

get '/log' do
  command = %[tail -f some.log]
  bcat = Bcat.new(command, :command => true)
  bcat.to_app.call(env)
end

Note: For infinitely running process you'll have to take care of killing the process yourself if someone closes the connection. With the first solution some servers might take care of that for you.



来源:https://stackoverflow.com/questions/7684784/stream-console-output-through-http-with-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!