1

我需要创建一个 rake 任务来通过 ssh 隧道执行一些活动记录操作。

rake 任务在远程 Windows 机器上运行,所以我想把东西保存在 ruby​​ 中。这是我最近的尝试。

  desc "Syncronizes the tablets DB with the Server"
      task(:sync => :environment) do
        require 'rubygems'
        require 'net/ssh'

        begin
        Thread.abort_on_exception = true
        tunnel_thread = Thread.new do
          Thread.current[:ready] = false
          hostname = 'host'
          username = 'tunneluser'

          Net::SSH.start(hostname, username) do|ssh|
            ssh.forward.local(3333, "mysqlhost.com", 3306)
              Thread.current[:ready] = true
              puts "ready thread"
              ssh.loop(0) { true }
        end
        end

        until tunnel_thread[:ready] == true do
        end
        puts "tunnel ready"
        Importer.sync

        rescue StandardError => e    
          puts "The Database Sync Failed."
        end
  end

该任务似乎挂在“隧道就绪”并且从不尝试同步。

首先运行 rake 任务以创建隧道然后在不同的终端中运行 rake 同步时,我取得了成功。但是,我想将这些组合起来,这样如果隧道出现错误,它就不会尝试同步。

这是我第一次使用 ruby​​ Threads 和 Net::SSH 转发,所以我不确定这里有什么问题。

有任何想法吗!?

谢谢

4

3 回答 3

2

The issue is very likely the same as here:

Cannot connect to remote db using ssh tunnel and activerecord

Don't use threads, you need to fork the importer off in another process for it to work, otherwise you will lock up with the ssh event loop.

于 2011-03-12T12:00:22.570 回答
0

Just running the code itself as a ruby script (with Importer.sync disabled) seems to work without any errors. This would suggest to me that the issue is with Import.sync. Would it be possible for you to paste the Import.sync code?

于 2009-12-26T03:21:28.520 回答
0

Just a guess, but could the issue here be that your :sync rake task has the rails environment as a prerequisite? Is there anything happening in your Importer class initialization that would rely on this SSH connection being available at load time in order for it to work correctly?

I wonder what would happen if instead of having environment be a prereq for this task, you tried...

...
Rake::Task["environment"].execute
Importer.sync
...
于 2009-12-31T19:39:00.757 回答