#!/bin/bash
# ------------------------------------------------------------------
# top_procs - list top CPU users
#
# Nov 2011, Vishal gupta
#
# Copyright (c) 2010-2011, 2013 by Cisco Systems, Inc.
# All rights reserved.
# ------------------------------------------------------------------

# Check if a PID is inside current chroot
proc_in_chroot() {
    local pid="$1"
    if [ ! -d "/proc/$pid" ]; then
        return 1
    fi
    if [ "`readlink /proc/$pid/root`" = "/" ]; then
        return 0
    fi
    return 1
}

function get_proc_memory
{
    ps -opid,rss,size,cmd | sort -k2 -n
}

# Interpret command-line arguments
CMD=(top)
while [ "$#" -gt 0 ]; do
    case "$1" in
        -d) CMD=(top -b)
            ;;
        -M) CMD=(get_proc_memory)
            ;;
    esac
    shift
done

# Run "top" and filter for processes inside the current node's chroot
"${CMD[@]}" | while read LINE; do
    PID=`echo "$LINE" | awk '{if (0+$1>0) { print $1; }}'`
    if [ -n "$PID" ]; then
        if proc_in_chroot "$PID"; then
            echo "$LINE"
        fi
    else
        echo "$LINE"
    fi
done

