from fabric.api import run

from cbagent.collectors.libstats.remotestats import (
    RemoteStats, multi_node_task)


class PSStats(RemoteStats):

    METRICS = (
        ("rss", 1024),    # kB -> B
        ("vsize", 1024),
    )

    def __init__(self, hosts, user, password):
        super(PSStats, self).__init__(hosts, user, password)
        self.ps_cmd = "ps -eo pid,rss,vsize,comm | " \
                      "grep {} | grep -v grep | sort -n -k 2 | tail -n 1"
        self.top_cmd = "top -bn2d1 -p {} | grep {}"

    @multi_node_task
    def get_samples(self, process):
        samples = {}
        stdout = run(self.ps_cmd.format(process))
        if stdout:
            for i, value in enumerate(stdout.split()[1:1+len(self.METRICS)]):
                metric, multiplier = self.METRICS[i]
                title = "{}_{}".format(process, metric)
                samples[title] = float(value) * multiplier
            pid = stdout.split()[0]
        else:
            return samples
        stdout = run(self.top_cmd.format(pid, process))
        if stdout:
            title = "{}_cpu".format(process)
            samples[title] = float(stdout.split()[8])
        return samples

from fabric.api import run

from cbagent.collectors.libstats.remotestats import (
    RemoteStats, multi_node_task)


class PSStats(RemoteStats):

    METRICS = (
        ("rss", 1024),    # kB -> B
        ("vsize", 1024),
    )

    def __init__(self, hosts, user, password):
        super(PSStats, self).__init__(hosts, user, password)
        self.ps_cmd = "ps -eo pid,rss,vsize,comm | " \
                      "grep {} | grep -v grep | sort -n -k 2 | tail -n 1"
        self.top_cmd = "top -bn2 -d1 -p {} | grep {}"

    @multi_node_task
    def get_samples(self, process):
        samples = {}
        stdout = run(self.ps_cmd.format(process))
        if stdout:
            for i, value in enumerate(stdout.split()[1:1+len(self.METRICS)]):
                metric, multiplier = self.METRICS[i]
                title = "{}_{}".format(process, metric)
                samples[title] = float(value) * multiplier
            pid = stdout.split()[0]
        else:
            return samples
        stdout = run(self.top_cmd.format(pid, process))
        if stdout:
            title = "{}_cpu".format(process)
            samples[title] = float(stdout.split()[8])
        return samples

Make `top` work on Ubuntu 12.04
MB-13234: Make `top` work on Ubuntu 12.04

The `top` in Ubuntu12.04 seems to do different command line parsing
than the one on CentOS. Separating the parameters should work on
both.

Change-Id: I8f9ec022bcb8e0158316fdaac226acbfb0d9d004
Reviewed-on: http://review.couchbase.org/50126
Reviewed-by: Dave Rigby <a09264da4832c7ff1d3bf1608a19f4b870f93750@couchbase.com>
Reviewed-by: Michael Wiederhold <a17fed27eaa842282862ff7c1b9c8395a26ac320@couchbase.com>
Tested-by: Volker Mische <fb414f8ac0dbbf87663550ae4ef5fc95b1041941@gmail.com>
