【问题标题】:Daemonizing an executable in ansible在ansible中守护可执行文件
【发布时间】:2015-06-30 15:34:00
【问题描述】:

我正在尝试在 ansible 中创建一个任务,该任务执行 shell 命令以使用 & 以守护程序模式运行可执行文件。像跟随

-name: Start daemon
  shell: myexeprogram arg1 arg2 &

我看到的是,如果我保持 & 任务立即返回并且进程没有开始。如果我删除 & ansible 任务等待相当长的时间而不返回。

感谢有关通过 ansible 以守护程序模式启动程序的正确方法的建议。请注意,我不想将其作为服务运行,而是基于特定条件的临时后台进程。

【问题讨论】:

    标签: shell daemon ansible


    【解决方案1】:

    使用 '&' 运行程序不会使程序成为守护程序,它只是在后台运行。要制作“真正的守护进程”,您的程序应该执行here 中描述的步骤。

    如果您的程序是用 C 编写的,您可以调用 daemon() 函数,它会为您完成。然后,即使最后没有“&”,您也可以启动程序,它将作为守护程序运行。

    另一种选择是使用daemon 调用您的程序,这也应该可以完成这项工作。

    - name: Start daemon
      shell: daemon -- myexeprogram arg1 arg2
    

    【讨论】:

    • 谢谢!这对我有帮助!
    • 请注意链接步骤are considered an anti-pattern nowadays:For developing a new-style daemon, none of the initialization steps recommended for SysV daemons need to be implemented. New-style init systems such as systemd make all of them redundant. Moreover, since some of these steps interfere with process monitoring, file descriptor passing and other functionality of the init system, it is recommended not to execute them when run as new-style service.
    • 什么是 -- 代表?
    • --,根据 POSIX,是命令的选项之间的分隔符,它们都以破折号-参数开头,其中可能还包含破折号,因此可能会混淆选项解析...例如,要安全地列出文件,您应该执行ls -- $filename - 否则您的命令可能会失败,如果名称文件本身以破折号开头。
    【解决方案2】:

    当您(或 Ansible)注销时,退出信号仍将发送到正在运行的进程,即使它正在后台运行。

    您可以使用nohup 来规避这种情况。

    - name: Start daemon
      shell: nohup myexeprogram arg1 arg2 &
    

    http://en.wikipedia.org/wiki/Nohup

    【讨论】:

    • 这是在非交互式 SSH 会话中运行的,因此该进程将在会话结束后立即终止。
    • 其他人报告说能够使其工作...superuser.com/a/870925/57697 但话虽如此,我无法复制他们的成功。
    • 伙计们,那么实现这一目标的另一种方法是什么。我无法使用守护进程和 nohup 运行它。ansible 脚本仍在等待。如果我终止 ansible 脚本,远程主机上的进程也会终止
    【解决方案3】:

    从您想要实现的目标的简要描述来看,您最好将可执行文件设置为服务(使用 Upstart 或类似工具),然后根据其他条件根据需要启动/停止它要求它运行(或不运行)。

    尝试将其作为进程运行,否则将需要捕获 PID 或类似内容,以便您可以在需要时尝试关闭已启动的守护程序,其复杂性与安装 init 配置几乎相同文件将采用并且没有像 Upstart 这样的系统为您提供诸如启动/停止之类的控件的细节。

    【讨论】:

      【解决方案4】:

      我发现最好的方法是使用“daemonize”包,特别是因为我希望记录输出。如果您使用的是 CentOS/Redhat,如下所示。可能还有一个 apt-package 。

      - name: yum install daemonize
        yum:
          name: daemonize
          state: latest
      
      - name: run in background, log errors and standout to file
        shell:  daemonize -e /var/log/myprocess.log -o /var/log/myprocess.log  /opt/myscripts/myprocess.sh
      

      【讨论】:

        【解决方案5】:

        添加到上面的 daemonize 建议,如果你想在特定目录中启动你的程序,你可以这样做:

        - name: install daemonize package
          package:
            name: daemonize
            state: latest
        - name: start program
          command: daemonize -c /folder/to/run/in /path/to/myexeprogram arg1 arg2
        

        值得注意的是,您可能还希望使用 -e -o 标志来记录输出。

        【讨论】:

          猜你喜欢
          • 2017-01-28
          • 1970-01-01
          • 1970-01-01
          • 2014-11-14
          • 1970-01-01
          • 2015-04-20
          • 1970-01-01
          • 2016-07-16
          • 1970-01-01
          相关资源
          最近更新 更多