1. 程式人生 > >如何給指令碼寫一個守護程序?

如何給指令碼寫一個守護程序?

在我們日常運維中,寫指令碼監控一個程序是比較常見的操作,比如我要監控mysql程序是否消失,如果消失就重啟mysql,用下面這段程式碼就可以實現:

#!/bin/sh

Date=` date ‘+%c’`

while :

do

if ! ps aux | grep -w mysqld | grep -v grep >/dev/null 2>&1

then

/etc/init.d/mysqld start

echo $Date mysqld was reboot >>/var/log/reboot_mysql.log

fi

done

但如果監控指令碼本身出了問題,就無法按我們要求啟動程式了,這裡這是以mysql為例子,但實際中如果是負責報警的指令碼出了問題,報警沒發出來,那就比較尷尬了,所以為保證我們的檢查指令碼能實時執行,我們有時需要寫一個守護程序(當然不止指令碼,系統中的任何程式都可以靠守護程序啟動),這就是我們今天要說的主題,如何給指令碼寫一個daemon程序,我們先上程式碼:

#!/usr/bin/python

import subprocess

from daemon import runner

cmd = “/root/demo_script/restart_mysql.sh”

class App():

def __init__(self):

self.stdin_path = ‘/dev/null’

self.stdout_path = ‘/dev/tty’

self.stderr_path = ‘/dev/tty’

self.pidfile_path =  ‘/tmp/hello.pid’

self.pidfile_timeout = 5

def start_subprocess(self):

return subprocess.Popen(cmd, shell=True)

def run(self):

p = self.start_subprocess()

while True:

res = p.poll()

if res is not None:

p = self.start_subprocess()

if __name__ == ‘__main__’:

app = App()

daemon_runner = runner.DaemonRunner(app)

daemon_runner.do_action()

指令碼比較簡單,沒什麼特別的邏輯,關於daemon這個模組如何使用,我這裡給出一段官方的解釋,寫的非常明白,注意喲,是英文的,在這我就不翻譯了,如果不理解就查查字典,就當多學幾個單詞了吧。

__init__(self, app)

|      Set up the parameters of a new runner.

|

|      The `app` argument must have the following attributes:

|

|      * `stdin_path`, `stdout_path`, `stderr_path`: Filesystem

|        paths to open and replace the existing `sys.stdin`,

|        `sys.stdout`, `sys.stderr`.

|

|      * `pidfile_path`: Absolute filesystem path to a file that

|        will be used as the PID file for the daemon. If

|        “None“, no PID file will be used.

|

|      * `pidfile_timeout`: Used as the default acquisition

|        timeout value supplied to the runner’s PID lock file.

|

|      * `run`: Callable that will be invoked when the daemon is

|        started.

|

|  do_action(self)

|      Perform the requested action.

|

|  parse_args(self, argv=None)

|      Parse command-line arguments.

這樣就完成了,守護程序的啟動比較高大上,輸入以上程式碼後,可以直接在終端輸入:

#python monitor.py  start

當然還有stop,restart等引數。

這裡我介紹的是其中一個應用場景,實際中可以靈活運用,比如1臺伺服器上啟動的程式過多,環境配置比較複雜,就可以先啟動daemon程序,然後通過daemon來啟動其它所有應用程式,就不用一個一個應用程式啟動了,而且還能起到實時監控的作用,很方便吧,這篇就到這裡,有問題可以給我留言。

文章出處:python運維技術