theKindOfMe

February 23, 2011

Custom Server Density Plugin to Watch Processes on a *nix Server

Filed under: Uncategorized — Tags: , — yasi8h @ 3:42 am

Wrote this down recently to keep a watch on some processors. You can look at a list of running processes in SD without the need for any additional pulgins. However if you need to be alerted when a process goes down you would need to (as David has pointed out in the comments section, you don’t need a custom plugin to do this. However i am keeping this post here… as a sample of a plugin or just because i wrote it :D) write something custom. This plugin will be sending a value of 80 or 0 for a given process. 80 indicates that its running while 0 indicates that its not running.

Source

import sys
import os
import subprocess
import re

class ProcessWatch:
  def __init__(self, agentConfig, checksLogger, rawConfig):
    self.agentConfig = agentConfig
    self.checksLogger = checksLogger
    self.rawConfig = rawConfig

  def run(self):
    data = {}
    for p in ["delayed_job", "thin"]: # put whatever process names you wish to monitor here
      if self.isThisRunning(p) == False:
        data[p] = 0 # not running
      else:
        data[p] = 80 # running!

    return data

  def findThisProcess(self, process_name):
    ps = subprocess.Popen("ps -eaf | grep "+process_name+" | grep -v grep", shell=True, stdout=subprocess.PIPE)
    output = ps.stdout.read()
    ps.stdout.close()
    ps.wait()

    return output

  # This is the function you can use
  def isThisRunning(self, process_name):
    output = self.findThisProcess(process_name)

    if re.search(''+process_name, output) is None:
      return False
    else:
      return True

You can grab the plugin from github at https://github.com/thekindofme/Custom-Server-Density-Plugins/blob/master/ProcessWatch.py

The return output looks like the following. So you can set this up to watch as many processes as you want. Internally it just executes a ps and grep the output. So just keep that it mind.

data = {‘delayed_job’: 80, ‘thin’: 80}

The above output is when the plugin is watching two processes (thin and delayed_job).

Customize the array in the 14th line of the plugin to include whatever processes you need to watch

["delayed_job", "thin"] # for watching delayed_job and thin

Just keep in mind that this is the first time i am writing something in Python :D. Hope this helps someone.

Blog at WordPress.com.