Capistrano Task to kill a process by port ONLY IF the process is running? - ruby

I pretty much need what my Question statement says, currently I have a Capistrano task that looks like this:
desc "stops private pub"
task :stop_private_pub do
run "kill -9 $(lsof -i:9292 -t)"
end
before 'deploy', 'servers:stop_private_pub'
...And it works well when in fact the process in port 9292 is running, The problem is that when the process Isn't running this task will FAIL! and it Halts the whole Deployment Process!
I'm not a UNIX Shell expert, nor am I a Capistrano master, so.. I really need help improving this Capistrano Task, Is there a way to kill -9 only if the process is running?
How can I do this?
Thanks in advance.

You could use Capistrano's capture command (in V3 at least, probably a V2 equivalent) to grab the output from your lsof command, and then only if you get a PID run the kill command.
pid = capture 'lsof', '-i:9292', '-t'
if pid # ensure it's valid here
run "kill -9 #{pid}" # make darn sure pid is an integer if you embed it
end

You could also do:
run "kill -9 $(lsof -i:9292 -t); true"
or add on error continue:
task :stop_web, :roles => :app, :on_error => :continue do
run "dosomething.sh; true"
end

Related

why rake tasks are not executing using and operator?

I have a rake task :
task :kill_process do
system %q(ps -ef | awk '{if($8~"java" || $8~"glassfish" || $8~"ruby" || $8~"god" || $8~"couch"){printf("Killing : %s \n",$2);{system("kill -9 "$2)};}}')
end
This is basically killing processes. And this task is a part of another rake task :
desc "stop the entire system"
task :stop => [...., :kill_process]
There's another task:
desc "start the entire system"
task :start => [....]
When I am doing rake stop && rake start
stop task is executed successfully. but rake start is not executing.
If i execute both tasks separately, then it works fine. but not in rake stop && rake start
What will be better to use here exec function or system or any other, please suggest me.
My only requirement is to kill these mentioned processes at the end of rake stop. But also it should not effect other things like rake stop && rake start should work fine.
As mentioned in the comments, the exit code is 137 which evaluates to false and therefore the other part of the && does not get executed. The reason for this is probably kill -9.
There are a few options now.
Return 0 from your rake task, something like exit(0)
Don't use kill -9
Create restart command which does execute stop and start but without logically depending on each other (&&).
Exit code 137 indicates that a process has received a SIGKILL signal and was thus killed from the outside.
This happens since a Rake task is also executed by Ruby. As such, your stop task is sending a SIGKILL to its own process too (along with all other Ruby processes on the system). Now, since you have specified that you only want to execute the rake start process if the previous process was successful (i.e. had a exit code of 0), your shell doesn't start the rake task.
To quickly fix this, you can instead run rake stop; rake start, i.e run the two processes regardless of their individual exit codes (by default).
However, a better idea would probably to make your stop task more explicit and only kill the specific processes you need rather than everything in sight which looks slightly like a related process. This will likely result in a more stable system overall too when you don't kill potentially unrelated processes all the time.

How do I cancel a long running Ruby Net::SSH command

If I kick off a long running command like a database dump using exec, how would I go about canceling that command on the remote host if, for example, the user start mashing Control-C to kill the script.
In my testing it seems like even if you Control-C and kill the application the remote command keeps running.
Capture SIGINT and SystemExit and clean up:
rescue SystemExit, Interrupt
# clean up
# net-ssh execute a kill on the pid
# raise error
end

How do I kill a rails webrick server?

When I try to start a server via rails s, I get the following error message:
C:\Users\Frankie\Documents\stocktracker>rails s
=> Booting WEBrick
=> Rails 3.2.8 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
A server is already running. Check C:/Users/Frankie/Documents/stocktracker/tmp/p
ids/server.pid.
Exiting
The number listed in server.pid is 8436.
How do I manually kill this process? How can I easily kill all webrick servers currently running?
You can use the taskkill utility.
taskkill /PID 8436
If you are using iTerm2 on OSX you can open Toolbelt => ShowToolbelt, select ruby pid 8436 then click send signal to kill it. Occasionally task kill doesn't work for me.
Also, you can ps -aux | grep rails to find the pid. and then kill like the other answers recommend.
The following task definition works for me (put it in a *.rake file in your lib\tasks folder):
namespace :server do
# ---------------------------------------------------------------------------
desc "Clear the previous server instance clutter."
task :cleanup => :environment do
pidfile = 'tmp/pids/server.pid'
if File.exists? pidfile
pid = File.read(pidfile).to_i
if RbConfig::CONFIG['host_os'] =~ /mswin32/
sh "taskkill /f /pid #{pid}"
sh "del tmp\\pids\\server.pid"
else
sh "kill #{pid}"
sh "rm #{pidfile}"
end
puts "All cleaned up. Yay!"
else
puts "Already clean. Whew!"
end
end
# ---------------------------------------------------------------------------
desc "Start an instance of the server cleanly."
task :startup => :cleanup do
sh "rails server"
end
# ---------------------------------------------------------------------------
end
Now just run
rake server:startup
It cleans up any leftover processes and pid files on Windoze before trying to run the rails server again.
For Linux/Ubuntu Users, ubuntu has kill command. While running webrick server, in project directory within location APP_DIR/tmp/pids/server.pid there will be all Process Ids saved.
You just need to open the file, you will find the Process Id of currently running server. Now you can use the following command to kill the process
$ kill [pid] # Example kill 8123
Follow these steps:
1.Find 'rails s' process id by: ps -aux | grep rails
2.Use kill command with -9 option as: kill -p [PID]
you will not be disappointed!!

Rake task for running a server in an independent thread then killing the thread when the task is complete?

How do I launch a thread within a rake task then kill the tread when the task is complete.
Essentially I am writing a rake task to test a jekyll site. I would like be able to launch the server, do some other tasks and then destroy the thread when the task is complete. Here is what I have thus far:
task :test_site do
`ejekyll --server`
`git -Xdn`
if agree( "Clean all ignored files?")
git -Xdf
end
end
but unfortunately the only way I know of to stop the jekyll --server is to use ctrl c. I would be happy to hear of a way to stop a jekyll --server in a manor which does not exit the rake task but please just comment as the question is specifically asking about threading and rake tasks.
You want Process.spawn, not a thread. It's a new process, not a thread of execution within an existing process. You get the PID back, so just send Process.kill(:QUIT, pid) or whatever method you want to use to kill the spawned processed.
pid = Process.spawn(
"ejekyll", "--server",
out: "/dev/null",
err: "/dev/null"
)
# you may need to add a short sleep() here
# other stuff
Process.kill(:QUIT, pid) && Process.wait
If ejekyll has a command line option to run in the foreground, it would be better to use that, otherwise if it self-daemonizes you need to know where it stores its PID file, in order to identify and kill the daemon.

how to stop sinatra from running?

If ruby myapp.rb starts sinatra previewing at localhost:4567, how can I programatically stop/halt/kill it? Terminal command (other than Ctrl-C), or Rake tasks would be fine.
I need to incorporate this into a Rake task or terminal.
In myapp.rb, add this before sinatra starts:
puts "This is process #{Process.pid}"
When you want to kill it, do this in a shell:
kill <pid>
Where <pid> is the number outputted by myapp.rb. If you want to do it in ruby:
Process.kill 'TERM', <pid>
Both of these will let sinatra run it's exit routine. If you don't want to type in the pid every time, have myapp.rb open a file and put it's pid in it. Then when you want to stop it, read the file and use that. Example:
# myapp.rb:
File.open('myapp.pid', 'w') {|f| f.write Process.pid }
# shell:
kill `cat myapp.pid`
# ruby:
Process.kill 'TERM', File.read('myapp.pid')
In OS X, from the command line (Terminal.app, or DTerm) just enter:
$ killall ruby
every ruby process will stop. Sinatra too.
In Linux (and other UNIXes), you can:
$ ps aux | grep ruby
$ kill <ruby-process-id>
The simples way to do that:
kill #{Process.pid}
To do this in a simple repeatable way, there's a few methods.
Record the PID as you start your Sinatra server, e.g.
# Run the Sinatra server and send it to background (using &)
ruby my_sinatra_server.rb &
# Record the PID of the last background process (using $!)
MY_SINATRA_SERVER_PID=$!
# Now go ahead and do your stuff...
# When finished, kill the sinatra server (from the same shell)
kill $MY_SINATRA_SERVER_PID
Instead of using an env variable ($MY_SINATRA_SERVER) you can use a temporary file e.g. my_sinatra_server.pid
# Run the Sinatra server and send it to background (using &)
ruby my_sinatra_server.rb &
# Record the PID of the last background process (using $!)
echo $! > my_sinatra_server.pid
# Now go ahead and do your stuff...
# When finished, kill the sinatra server (from the same shell)
kill $(< my_sinatra_server.pid)

Resources