How do I kill a rails webrick server? - windows

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!!

Related

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

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

Starting or restarting Unicorn with Capistrano 3.x

I'm trying to start or restart Unicorn when I do cap production deploy with Capistrano 3.0.1. I have some examples that I got working with Capistrano 2.x using something like:
namespace :unicorn do
desc "Start unicorn for this application"
task :start do
run "cd #{current_path} && bundle exec unicorn -c /etc/unicorn/myapp.conf.rb -D"
end
end
But when I try and use run in the deploy.rb for Capistrano 3.x I get an undefined method error.
Here are a couple of the things I tried:
# within the :deploy I created a task that I called after :finished
namespace :deploy do
...
task :unicorn do
run "cd #{current_path} && bundle exec unicorn -c /etc/unicorn/myapp.conf.rb -D"
end
after :finished, 'deploy:unicorn'
end
I have also tried putting the run within the :restart task
namespace :deploy do
desc 'Restart application'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
# Your restart mechanism here, for example:
# execute :touch, release_path.join('tmp/restart.txt')
execute :run, "cd #{current_path} && bundle exec unicorn -c /etc/unicorn/deployrails.conf.rb -D"
end
end
If I use just run "cd ... " then I'll get awrong number of arguments (1 for 0)` in the local shell.
I can start the unicorn process with unicorn -c /etc/unicorn/deployrails.conf.rb -D from my ssh'd VM shell.
I can kill the master Unicorn process from the VM shell using kill USR2, but even though the process is killed I get an error. I can then start the process again using unicorn -c ...
$ kill USR2 58798
bash: kill: USR2: arguments must be process or job IDs
I'm very new to Ruby, Rails and Deployment in general. I have a VirtualBox setup with Ubuntu, Nginx, RVM and Unicorn, I'm pretty excited so far, but this one is really messing with me, any advice or insight is appreciated.
I'm using following code:
namespace :unicorn do
desc 'Stop Unicorn'
task :stop do
on roles(:app) do
if test("[ -f #{fetch(:unicorn_pid)} ]")
execute :kill, capture(:cat, fetch(:unicorn_pid))
end
end
end
desc 'Start Unicorn'
task :start do
on roles(:app) do
within current_path do
with rails_env: fetch(:rails_env) do
execute :bundle, "exec unicorn -c #{fetch(:unicorn_config)} -D"
end
end
end
end
desc 'Reload Unicorn without killing master process'
task :reload do
on roles(:app) do
if test("[ -f #{fetch(:unicorn_pid)} ]")
execute :kill, '-s USR2', capture(:cat, fetch(:unicorn_pid))
else
error 'Unicorn process not running'
end
end
end
desc 'Restart Unicorn'
task :restart
before :restart, :stop
before :restart, :start
end
Can't say anything specific about capistrano 3(i use 2), but i think this may help: How to run shell commands on server in Capistrano v3?.
Also i can share some unicorn-related experience, hope this helps.
I assume you want 24/7 graceful restart approach.
Let's consult unicorn documentation for this matter. For graceful restart(without downtime) you can use two strategies:
kill -HUP unicorn_master_pid It requires your app to have 'preload_app' directive disabled, increasing starting time of every one of unicorn workers. If you can live with that - go on, it's your call.
kill -USR2 unicorn_master_pid
kill -QUIT unicorn_master_pid
More sophisticated approach, when you're already dealing with performance concerns. Basically it will reexecute unicorn master process, then you should kill it's predecessor. Theoretically you can deal with usr2-sleep-quit approach. Another(and the right one, i may say) way is to use unicorn before_fork hook, it will be executed, when new master process will be spawned and will try to for new children for itself.
You can put something like this in config/unicorn.rb:
# Where to drop a pidfile
pid project_home + '/tmp/pids/unicorn.pid'
before_fork do |server, worker|
server.logger.info("worker=#{worker.nr} spawning in #{Dir.pwd}")
# graceful shutdown.
old_pid_file = project_home + '/tmp/pids/unicorn.pid.oldbin'
if File.exists?(old_pid_file) && server.pid != old_pid_file
begin
old_pid = File.read(old_pid_file).to_i
server.logger.info("sending QUIT to #{old_pid}")
# we're killing old unicorn master right there
Process.kill("QUIT", old_pid)
rescue Errno::ENOENT, Errno::ESRCH
# someone else did our job for us
end
end
end
It's more or less safe to kill old unicorn when the new one is ready to fork workers. You won't get any downtime that way and old unicorn will wait for it's workers to finish.
And one more thing - you may want to put it under runit or init supervision. That way your capistrano tasks will be as simple as sv reload unicorn, restart unicorn or /etc/init.d/unicorn restart. This is good thing.
I'm just going to throw this in the ring: capistrano 3 unicorn gem
However, my issue with the gem (and any approach NOT using an init.d script), is that you may now have two methods of managing your unicorn process. One with this cap task and one with init.d scripts. Things like Monit / God will get confused and you may spend hours debugging why you have two unicorn processes trying to start, and then you may start to hate life.
Currently I'm using the following with capistrano 3 and unicorn:
namespace :unicorn do
desc 'Restart application'
task :restart do
on roles(:app) do
puts "restarting unicorn..."
execute "sudo /etc/init.d/unicorn_#{fetch(:application)} restart"
sleep 5
puts "whats running now, eh unicorn?"
execute "ps aux | grep unicorn"
end
end
end
The above is combined with the preload_app: true and the before_fork and after_fork statements mentioned by #dredozubov
Note I've named my init.d/unicorn script unicorn_application_name.
The new worker that is started should kill off the old one. You can see with ps aux | grep unicorn that the old master hangs around for a few seconds before it disappears.
To view all caps:
cap -T
and it shows:
***
cap unicorn:add_worker # Add a worker (TTIN)
cap unicorn:duplicate # Duplicate Unicorn; alias of unicorn:re...
cap unicorn:legacy_restart # Legacy Restart (USR2 + QUIT); use this...
cap unicorn:reload # Reload Unicorn (HUP); use this when pr...
cap unicorn:remove_worker # Remove a worker (TTOU)
cap unicorn:restart # Restart Unicorn (USR2); use this when ...
cap unicorn:start # Start Unicorn
cap unicorn:stop # Stop Unicorn (QUIT)
***
So, to start unicorn in production:
cap production unicorn:start
and restart:
cap production unicorn:restart
PS do not forget to correct use gem capistrano3-unicorn
https://github.com/tablexi/capistrano3-unicorn
You can try to use native capistrano way as written here:
If preload_app:true and you need capistrano to cleanup your oldbin pid use:
after 'deploy:publishing', 'deploy:restart'
namespace :deploy do
task :restart do
invoke 'unicorn:legacy_restart'
end
end

kill pid started with gem net-ssh

If you start a command in a remote server with the net/ssh gem, and the command is on a deadlock, how do find the pid of the process running in the remote server and kill it?
Does net/ssh gem support this?
Well, if you can ssh into the remote server, you can use this to get the pid of the process:
# Assuming the command you want to kill is a ruby program.
# If the program is something else, say sparrow mail app, you should replace
# ruby with sparrow below.
ps -ax | grep ruby
And then, perhaps:
kill -9 <pid>

Kill a child process that has detached from the shell

I want to control many different Sinatra apps from a central (Sinatra) app.
The problem I have is no matter which way I exec/spawn/fork the call to start it, I cannot get the pid of the Sinatra server so that I can kill (:int) it?
This is due to my shell exec string, which contains a few other commands first, so I get the pid of the first.
My command string is like
command = source ~/.profile; rbenv #{ver}; some_env=1234 ruby app.rb
So I get the pid of the sh process of the sourcing command.
The question is, how can I get the pid of the ruby command launched above?
I am currently using spawn, but have tried most others as well, but I don't think that is the problem!?
pid = Process.spawn(command)
pid # => 1234
The ruby app itself starts
$ ps aux
1234 sh -c . ~/.profile; shell_script
4567 shell_script
I want to know 4567!?
There's no easy way of getting your '4567', but you should be able to make your process have the same pid as Process.spawn returns.
Try ending your command with an exec rather than a straight call to ruby, i.e.:
source ~/.profile; rbenv #{ver}; export some_env=1234; exec ruby app.rb
you can check whether the process "shell_script" is a child of "sh -c . ~/.profile; shell_script".you can check this through "ps -axgf" command.
if it is a parent then u can use the group id of pid 1234 (get it form the output of ps -axgf) to kill the child with pid 4567 using this command .
kill -9 -1234(assumming 1234 is the group id)

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