Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongrel_rails - programatically report which port it's running on

On my local machine, i run rails with mongrel. I have some stuff which runs when it starts, via a file in config/initializers, which uses puts to tell me which database it's using, what is being used to send emails, and a few other bits of info.

When I run a cluster of mongrels, on ports 3000, 3001 and 3002, I only want to do this reporting stuff for the mongrel on port 3000. So, I need to wrap it in an if block which tests which port the currently running mongrel is using. Can anyone tell me how I can get this in my code?

like image 910
Max Williams Avatar asked May 13 '15 09:05

Max Williams


2 Answers

in an initializer,

puts Rails::Server.new.options[:Port]

can report your port.

like image 114
Alper Karapınar Avatar answered Sep 26 '22 19:09

Alper Karapınar


Ok, i'm answering my own question as i just figured it out after setting a bounty!

I can get the pid of the currently running process with Process.pid. Then i can do ps afx | grep mongrel which gives me a result like this

 pid                                                                                 port
  |                                                                                    |
  V                                                                                    V
10761 pts/1    S      0:20  |   \_/usr/local/bin/ruby /path/to/mongrel_rails start -p 3000
10762 pts/1    S      0:18  |   \_/usr/local/bin/ruby /path/to/mongrel_rails start -p 3001
10763 pts/1    S+     0:23  |   \_/usr/local/bin/ruby /path/to/mongrel_rails start -p 3002

which i can then grep for the pid, and read the port number out of the matching line, and see if it's 3000.

So, my code is

if `ps afx | grep mongrel_rails`.split("\n").detect{|line| line =~ /^#{Process.pid}.+\-p\s3000/}
  #this is a mongrel running on port 3000 - do the extra stuff
  ....
end

BTW, if someone can tell me how to directly get the port of the running mongrel, without going via ps afx and Process.pid i'll still give you the bounty :)

like image 24
Max Williams Avatar answered Sep 25 '22 19:09

Max Williams