#!/usr/bin/python -OO


"""
Add up (rss - shared) from all httpd2 processes

(on Linux; see: man 5 proc)

"""

__version__ = '1.0'
__author__ = 'Peter Poeml <poeml@cmdline.net>'
__copyright__ = 'Peter Poeml <poeml@cmdline.net>'
__license__ = 'GPL'
__url__ = 'http://www.cmdline.net/misc/httpd2-memusage.py'



import os

os.chdir('/proc')
total = 0

ppid = open('/var/run/httpd2.pid').read().strip()

for pid in os.listdir('.'):

    try:
        exe = os.readlink(os.path.join(pid, 'exe'))
    except:
        continue

    if exe.startswith('/usr/sbin/httpd2'):

        stat = open(os.path.join(pid, 'stat')).read().split()
        if pid != ppid and stat[3] != ppid:
            # different httpd process group
            continue

        statm = open(os.path.join(pid, 'statm')).read().split()
        rss = float(statm[1]) * 4
        shared = float(statm[2]) * 4
        real = rss - shared
        real = real / 1000 # KB -> MB
        total += real

        print 'pid %-6s %8.3f MB' % (pid, real),
        if pid == ppid:
            print '(parent)'
        else:
            print

print
print 'TOTAL: %.3f MB' % total
