Store ssh connections in rails
I have a rails app that needs to communicate with a couple of servers through ssh. I'm using the Net::SSH library and it works great. I would like however to be able to cache/store the ssh connections somehow between requests (something like OpenSSH multiplexing).
So, i can't store them in a key-value store like Memcached or Redis (because ssh connections are not serializable).
I don't want to store them in a session because they are meant to be used by all users 开发者_Go百科(and besides i think it needs to be serializable also).
I managed to get this working with class variables and initiliazer constants. I know that class variables don't replicate between servers (in production), and i'm pretty certain initializer constants also don't. Something like:
initializer:
SSH = {}
model:
class Server
def connection
require 'net/ssh'
SSH[name] ||= Net::SSH.start(ip, "root", :password => password)
end
end
OpenSSH multiplexing would be great but i'm not sure if i could do that through the Net::SSH ruby library (i'm back to storing the master connection somewhere).
Are there any other solutions? Or if not, which one is the least evil of them all?
Perhaps rather than trying to share sockets across requests which is bound to end up causing pain and suffering you could delegate to a background processor of some kind? You could set up an ssh tunnel and use DRb to talk across it as if it was just a local network daemon, or any of the large number of networked asynchronous job handling daemons.
http://ruby-toolbox.com/categories/queueing.html
To keep the SSH connection up between requests, you'll need to spawn off a background process. The background process can open up a pipe or some other sort of interprocess communication method, the handle to which you can store in a serializable way.
Note that this is a non-trivial exercise, which is why I've only described it at high-level detail.
精彩评论