2011-11-24 178 views
1

我正在开发一个Rails v2.3应用程序。与MySQL v5.1数据库上的Ubuntu机器。启动与停止Nginx,MySQL服务器

我知道启动命令,在命令行上停止NginxMySQL

但现在,我需要有以下过程在我的Rails应用程序:我rake任务的一个定义

stop Nginx --> stop(shut down) MySQL --> ... --> start MySQL --> start Nginx 

这意味着所有这些需要在Ruby脚本在定义耙任务我的Rails应用程序。

我不确定如何在我的rake任务上使ruby代码运行上述过程(执行命令)?

回答

1

退房Ruby's Kernel module(它是内置的)。使用反引号,你可以运行命令来停止/启动nginx和MySQL,甚至检查它们的退出代码,以确保它们正确执行(如果你的停止/启动脚本支持退出代码)。

例子:

# In your Rakefile 
namespace :servers do 
    task :stop do 
    nginx_stop_output = `service nginx stop` 
    if $?.exitstatus != 0 
     # handle shutdown failure 
    end 

    mysql_stop_output = `service mysql stop` 
    if $?.exitstatus != 0 
     # handle shutdown failure 
    end 
    end 

    task :start do 
    nginx_start_output = `service nginx start` 
    if $?.exitstatus != 0 
     # handle startup failure 
    end 

    mysql_start_output = `service mysql start` 
    if $?.exitstatus != 0 
     # handle startup failure 
    end 
    end 
end 

替换在自己的停止/启动反引号中的命令。

然后,您可以使用rake servers:stoprake servers:start运行这些任务。

0

除非nginx不在端口80上运行,否则可能使用sudo。在这种情况下,你的选择是:

  1. 修改/etc/sudoers允许用户没有被要求输入密码nginx的工作。

  2. 使用Open3#popen3代替“或”运行shell命令“system()”。如果Open3提示您输入其他信息,则可以使用Open3与命令交互,以便在您的rake任务尝试执行命令时键入sudo密码。

0

使用gem systemu来执行命令。它比任何内置的Ruby命令行工具都要好。为了照顾您的服务器环境,您可以查看像vlad这样的部署框架。