Setting Connection to "close" in Sinatra - ruby

I have this simple sinatra web app:
require 'sinatra'
get '/' do
"Success."
end
get '/app' do
"done"
response["Connection"] = "Close"
`sudo pkill blink`
`gpio write 0 0`
`sudo ./blink #{params["func"]}`
end
./blink is a program that runs forever and does not terminate, so when I access http://127.0.0.1/app?func=2 in a browser, I just get a loading loop and "done" is not shown as the result, however the program I am trying to run in the /app block is running.
I thought maybe setting the Connection header to Close would solve the problem, but using the code above, which I thought would set the header, still has the Connection header to Keep-Alive
Any help? Thanks!

Referencing this SO question Spawn a background process in Ruby and with some help from #andrykonchin, I was able to resolve my issue using this:
pid = fork do
`sudo ./blink #{params["func"]}`
end
Process.detach(pid)

Related

Manage a Thin server through a Ruby script

I have a project where I have a sinatra app and I want to launch it with thin through a admin ruby script file. I want to be able to start, stop and restart it, also being able to daemonize it if asked to. This is, I want to have something like this in my script:
bin/myscript
require 'MyCLI'
MyCLI.new(ARGV).run
lib/mycli.rb
class MyCLI
# instantiate and other methods (inspired by thin runner)
...
def run
# parse commands and options
...
# then process command
case #command
when 'start'
#server = Thin::Server.new(host, port, MyModule::MyAppClass)
#server.start
when 'stop'
# ?
when 'restart'
# ?
else
raise "Unknown command"
end
end
end
But I'm struggling with some problems,
I need to daemonize it or not, depending on some command option and cant find if this is possible to do passing some parameter to #new after reading docs and digging in some of the code.
Stopping would be as easy as #server.stop, but as my script instantiates a mycli object at each command line request, I do not have a single object so #server vanishes after the start request, so I think that the only solution would be to control the PID (right??), but cant find how thin manages that. Also, running it in foreground would not work with this pid approach I presume.
What would be the proper way to restart it?
Has anyone a best solution for this?
I end up using Rack::Server.start(app, host, port, env, daemonize(Y/N), pid_file).
It works great, and it will pick up the thin handler if available.

Thin doesn't respond to SIGINT or SIGTERM

bundle exec thin start -p 3111 gives the following output:
Using rack adapter
Thin web server (v1.2.11 codename Bat-Shit Crazy)
Maximum connections set to 1024
Listening on 0.0.0.0:3111, CTRL+C to stop
^C
Ctrl-C doesn't do anything (SIGINT). Neither does kill (SIGTERM).
I've found a few references to this behavior, but no solutions. The problem seems to be either in eventmachine (bundled with latest thin), in ruby 1.9.2-r290, or in the linux kernel (Ubuntu 10.4 LTS, 2.6.38.3-linode32).
It happens with my project, but not with a brand new rails project.
References:
http://groups.google.com/group/thin-ruby/browse_thread/thread/4b7c28e8964b5001?fwc=2
My guess is that either something's tying up the EventMachine reactor loop preventing it from exiting, or something's trapping SIGINT.
As a simple example of the former, put this into config.ru and run with thin -p 4567 start:
require 'thin'
require 'sinatra'
require 'eventmachine'
get '/' do
"hello world"
end
run Sinatra::Application
EventMachine.schedule do
trap("INT") do
puts "Caught SIGINT"
EventMachine.stop # this is useless
# exit # this stops the EventMachine
end
i = 0
while i < 10
puts "EM Running"
i += 1
sleep 1
end
end
Without trapping the SIGINT, you get the same behavior as when trapping it and calling EM.stop. EM.stop (at least in the pure ruby version, which you can run with EVENTMACHINE_LIBRARY="pure_ruby" thin start) sets a flag that a stop has been requested, which is picked up inside the reactor loop. If the reactor loop is stuck on a step (as in the above case), then it won't exit.
So a couple options:
use the workaround above of trapping SIGINT and forcing an exit. This could leave connections in an unclean state, but they don't call it quick & dirty for nothing ;)
you could put the blocking code inside a Thread or a Fiber, which will allow the reactor to keep running.
look for long-running tasks or loops inside your code, and convert these to be EventMachine aware. em-http-request is a great library for external http requests, and em-synchrony has several other protocols (for database connections, tcp connection pools, etc.). In the above example, this is straightforward: EventMachine.add_periodic_timer(1) { puts "EM Running" }
In your actual code, this might be harder to track down, but look for any places where you spawn threads and join them, or large loops. A profiling tool can help show what code is running when you try to exit, and lastly you can try disabling various parts of the system and libraries to figure out where the culprit is.

Troubles with parallel processes in IRB on Mac

I am working with a database via IRB, and I would like to make periodic changes in the database (e.g., every 10 sec) showing the log in STDOUT.
Also, I would like to have manual control being able to change the database and to stop the first process.
So far I came up to the following
def start
stop
#running = Thread.new do
loop do
fork do
puts 'change the database'
end
sleep 10
end
end
nil
end
def stop
#running.kill if #running
end
However, this is not running every 10 sec unless I enter something in the main IRB thread.
How to make it working?
Some versions of readline on OSX are blocking. If one experiences the behavior you described, they can disable readline by putting
IRB.conf[:USE_READLINE] = false
in .irbrc
Works fine for me (tested in irb with ruby 1.9.2-p180 and 1.8.7-p334).

run_later with rackup fails to exit with ctrl-c - Ruby

I'm running a Sinatra application with rackup using this run_later https://github.com/elecklider/sinatra_run_later module (my own fork of https://github.com/pmamediagroup/sinatra_run_later). I can't, however, seem to get it to exit cleanly when I send ctrl-c to rackup. It kicks back with the error ERROR SystemExit: exit on line 38. How can I get it to exit nicely when I close the rackup process?
EDIT:
I've been screwing around with this and the error is raised here:
trap :INT do
RunLater::Worker.shutdown
exit # here.
end
And it seems that commenting out the whole trap block gets it to clean up nicely. In essence, this answers the question of how to get it to clean up nicely but I have no idea why so if anyone can offer some clarification I'd really appreciate it.

How can I create a daemon with Thor (ruby)?

I would like to use the popular Thor gem to create a daemonized task. My Thor class looks like this:
require 'rubygems'
require 'daemons'
require 'thor'
class CLI < Thor
desc "start", "Startup the App"
method_option :daemonize, :aliases => "-d", :default => false, :type => :boolean, :banner => "Run as daemon"
def start
run_app(options[:daemonize])
end
desc "stop", "Stop the daemon"
def stop
stop_app
end
no_tasks {
def run_app(run_as_daemon)
# Run the application code
Daemons.daemonize if run_as_daemon
# loop until stopped or interrupted
# ...
end
def stop_app
#stop the app
end
}
end
So here I've setup a basic thor class with two tasks, start and stop. I'm also, currently using the Daemons gem, but that isn't required. The part that I'm struggling with is that when this app runs as "run_thor_app.rb start" everything runs just fine. Obviously the stop task isn't needed in this instance. But when I run "run_thor_app.rb start -d" the app runs until Daemons.daemonize runs and then it quits. Checking the running processes shows that nothing is running in the background.
Even if something were running, I wouldn't know how to approach the stop task. For example, how do you detect that the app is running as a daemon and stop it. I've looked at Daemons::Monitor, but the documentation isn't clear on how that works and when I tried it, it didn't work.
It seems to me that this would be a good use case for something that is built into Thor, but searching through the code on github hasn't revealed anything to me. Maybe I just missed it somewhere. In any case, I think it would be good to document a best practice or a pattern for handling daemons with Thor for others to reference.
The way you usually manage daemon processes is by having them write their PID in a file. This makes it possible for another process to discover the daemon's PID, and kill it (or send some other signal).
Your code should work. I tried a bare bones script that used the deamons gem, and it took me a few tries until I found the deamonized process. I figured it would get the same name as the parent process, or something similar, but instead it's name was "self". Remember that the daemonized process will no longer write to STDOUT.
Anyway, try this:
# set up everything
# then daemonize
Daemons.daemonize
# and write a pid file
File.open('/tmp/mydaemon.pid', 'w') { |f| f.puts(Process.pid) }
loop do
# do something
# this loop is important, if the script ends the daemon dies
end
and check the /tmp/mydaemon.pid file for the PID. Then run ps ax | grep x where x is the PID. Run cat /tmp/mydaemon.pid | xargs kill` to kill the daemon.
I think the daemons' gem has some helpers for managing PidFiles, check out PidFile in http://rubydoc.info/gems/daemons/1.1.0/frames

Resources