AWS Linux CloudWatch - Metric for Top 5 processes and memory consumed

I am trying to publish a custom metric (cloudwatch) to get the top 5 processes and their memory consumption in Linux machines.

Currently for Windows I am using the following powershell script:

$Processes = get-process | Sort-Object CPU -desc | Group-Object -Property 

ProcessName | Select-Object -first 5
#$Processes = get-process | Group-Object -Property ProcessName

foreach($Process in $Processes)
{
    $mem = ($Process.Group|Measure-Object WorkingSet -Sum).Sum
    $memMB = $mem/1MB
    $Obj = New-Object psobject
    $Obj | Add-Member -MemberType NoteProperty -Name Name -Value $Process.Name
    $Obj | Add-Member -MemberType NoteProperty -Name Mem -Value $memMB
    $Obj

    #Write-Host $Process.Name
    aws cloudwatch put-metric-data --metric-name $Process.Name --namespace TopProcesses --value $memMB
}

At the moment this is working fine for Windows, but I am having a lot of trouble porting a similar concept on Linux machines, if anyone can give me some help on this issue, it would be greatly appreciated.

Edit: If this information could be retrieved through lambda I would be able to find a solution, however, I am unsure as to how I should go about grabbing the linux instance information through python.

2 answers

  • answered 2018-06-19 19:33 Alex Chyrkov

    I really think that would be better use for that some metrics aggregator. For example Telegraf or Collectd. Both solutions support Windows and Linux distros.

    Telegraf has nice yaml config. You just put cloudwatch in output and that's it. Ready solutions help you avoid of development/support custom code.

    As for shell script you could obtain top 5 processes by memory like that:

    PIDS=$(ps aux --sort -rss | tail -n +2 | head -n 5 | awk '{print $2}')

    Above script grabs pids of processes. There are a lot of methods how grab memory utilization by PID. For example you could do:

    cat /proc/$pid/status

  • answered 2018-06-19 20:06 T. Morrison

    In Linux I like to use

    top -i
    

    or for more definitive updates:

    watch "ps aux | sort -nrk 3,3 | head -n 5"
    

    Which will give you an output that looks something like this

    terminal after watch command