Unable to connect to remote db using ssh tunnel and activerecord

I am having problems with the following script:

require 'rubygems'
require 'active_record'
require 'net/ssh/gateway'

gateway = Net::SSH::Gateway.new('myserver.com', 'myuser', :password => "mypass")
puts "true" if gateway.active?
p = gateway.open('127.0.0.1', 3306, 3307)

class MyClass < ActiveRecord::Base
  establish_connection(
    :adapter  => "mysql",
    :host     => "127.0.0.1",
    :username => "db_user",
    :password => "db_pass",
    :database => "mydb_production",
    :port     => 3307
  )
end

puts MyClass.all.size

gateway.shutdown!

When I run the script, it just hangs unless I delete the activerecord request. I know that I can connect using tunneling, because I can create a tunnel from a command, for example:

ssh -f myuser@myserver.com -L 3307/127.0.0.1/3306 -N

Then if I run:

require 'rubygems'
require 'active_record'

class MyClass < ActiveRecord::Base
  establish_connection(
    :adapter  => "mysql",
    :host     => "127.0.0.1",
    :username => "db_user",
    :password => "db_pass",
    :database => "mydb_production",
    :port     => 3307
  )
end

puts MyClass.all.size

It works great. What am I doing wrong?

Thank.

+3
source share
2 answers

I managed to get this to work without a plug using mysql2 stone

require 'rubygems'
require 'active_record'
require 'mysql2'
require 'net/ssh/gateway'

gateway = Net::SSH::Gateway.new(
  'remotehost.com',
  'username'
)
port = gateway.open('127.0.0.1', 3306, 3307)

class Company < ActiveRecord::Base
  establish_connection(
    :adapter  => "mysql2",
    :host     => "127.0.0.1",
    :username => "dbuser",
    :password => "dbpass",
    :database => "dbname",
    :port     => 3307
  )
end
puts Company.all.size
+8
source

I think the comment is right - the database contradicts the event loop in the ssh code.

Try the following:

  require 'rubygems'
  require 'active_record'
  require 'net/ssh/gateway'

  gateway = Net::SSH::Gateway.new('myserver.com', 'myuser', :password => "mypass")
  puts "true" if gateway.active?
  port = gateway.open('127.0.0.1', 3306, 3307)
  fork.do
    class MyClass < ActiveRecord::Base
      establish_connection(
        :adapter  => "mysql",
        :host     => "127.0.0.1",
        :username => "db_user",
        :password => "db_pass",
        :database => "mydb_production",
        :port     => 3307
      )
    end

    puts MyClass.all.size
  end  

  Process.wait

  gateway.shutdown!
+2
source

Source: https://habr.com/ru/post/1779503/


All Articles