Stats data CPU parsing

Hi there,

I’m building an autoscaling tool for our company,

I’m trying to gather the host and container cpu stats for now, I’ve successfully connected to the stats websocket and I’ve seen that even if the CPU usage goes up and down the data in the cpu.usage json field is always increasing and has values like 300070499138, 297139877070 etc.

How should I handle that value to have a percentage value as shown in the UI?

Nevermind, solved it, I’ve seen the rancher python client part about parsing the CPU data.

In case anyone else is wondering, you need two datapoints to compare… subtract the two counters and divide by the time elapsed between the points. Storage and network I/O work similarly.

Thanks @vincent, actually the time elapsed has to be multiplied by 10*9.

This is the node.js code I used if someone needs it:

const calcCpuStats = (stats = []) => {
  if (stats.length < 2) { return null; }

  const stat_latest = stats[stats.length - 1];
  const stat_prev = stats[stats.length - 2];

  const time_diff = ((new Date(stat_latest.timestamp) - new Date(stat_prev.timestamp))/1000) * 1000000000;

  if (time_diff == 0) { return null; }

  const latest_usage = stat_latest.cpu.usage;
  const prev_usage = stat_prev.cpu.usage;

  const cpuCoresPercentages = [];

  latest_usage.per_cpu_usage.forEach((core_usage, idx) => {
    const cpu_usage = parseFloat(core_usage) - prev_usage.per_cpu_usage[idx];
    let percentage = ((cpu_usage/time_diff) * 100).toFixed(3);

    cpuCoresPercentages.push(percentage);
  });

  const systemUsage = parseFloat(((latest_usage.system - prev_usage.system)/time_diff * 100).toFixed(3));
  const userUsage = parseFloat(((latest_usage.user - prev_usage.user)/time_diff * 100).toFixed(3));

  return { cores: cpuCoresPercentages, system: systemUsage, user: userUsage };
}

Yes, they’re in nanoseconds. You probably want to Math.min(percent,100) everything because occasionally they will come out to slightly more than 100%.

Oh ok thanks, during the load tests I’ve never seen those values going more than 100%, will do.