Monday, May 20, 2013


Unix Memory Hog Finder

Return all processes memory information
subprocess.Popen("ps -u %s -o rss”)
Save a process class into a Parent/Child Structure
Parent
   -- Child
      --Child
        --Child
   -- Child
The process class has information such as current memory size, users, PID, PPID. I also implemented a timestamp and memory size for every process in case a process “bloated” up
Algorithm:
ParentProcessArray = []
For all processes:
   // IF parent PID is one then this is a parent process
   if process.PPID == 1:
      ParentProcessArray.append(process)
      break
   for all in ParentProcessArray:
     if process.PID == ParentProcessArray[i]
      ParentProcessArray.addchild(process)
             break;

// For Recursive Print Function:
// RETURN ALL CHILDREN FROM A PARENT RECURSIVELY
 def GetChildren(self,lvl=0):
        global ListOfChildren
        global Memcount
        if lvl == 0:
            ListOfChildren = []           
            Memcount = self.GetHighestRSS()
        for child in self.ListOfChildProcesses:
            child.lvl = lvl + 1           
            Memcount = Memcount + child.GetHighestRSS()
            ListOfChildren.append(child)
            if child.HasChild():
               child.GetChildren(lvl + 1)
        if lvl == 0:
            self.ParentProcTotalMem = Memcount
            Memcount = 0
        return ListOfChildren

This script logs all of the processes and how much memory is being used on a box. This is a very useful script and the algorithm of how it works is in the snippet above. It iterates through all processes. If it is a parent it puts it in the global parent array. For all processes that is a child of a parent it gets put into a parent with the recursive add child method.

No comments:

Post a Comment