#!/bin/bash

FILE_PREFIX="sys_host_ovs_datapath_perf.sh"
TMP_DIR="$(cd "$(dirname "$0")" && pwd)/tmp"

DATA_FILE="${TMP_DIR}/${FILE_PREFIX}_data"
OUTPUT_FILE="${TMP_DIR}/${FILE_PREFIX}_output.json"

# 获取转发核CPU使用率
sar -P ALL 1 1 | grep -E " 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 " | grep Average | awk '{print "{\"tags\":\"cpu="$2"_idle\",\"value\":"int($8)"}"}' > "$DATA_FILE"

# 获取datapath flow总数
ovs-appctl upcall/show | grep keys | awk '{print $3}' | awk -F ')' '{print $1}' | awk '{sum += $1} END {print sum}' | awk '{print "{\"tags\":\"datapath=flow_number\",\"value\":"int($1)"}"}' >> "$DATA_FILE"

# 获取datapath flow新创建速率、datapath flow删除速率、upcall action执行
ovs-appctl coverage/show | grep -Ew "dpif_flow_put|dpif_flow_del|dpif_execute" | awk '{print $1,$3}' | sed 's/\/sec//' | awk '{print "{\"tags\":\"operation="$1"\",\"value\":"int($2)"}"}'  >> "$DATA_FILE"

echo "[" > "$OUTPUT_FILE"
while IFS= read -r line; do
    echo "  $line," >> "$OUTPUT_FILE"
done < "$DATA_FILE"
sed -i '$ s/,$//' "$OUTPUT_FILE"
echo "]" >> "$OUTPUT_FILE"

cat "$OUTPUT_FILE"
