From 30ad943b2820a054179f2738073d5ed5865a34e3 Mon Sep 17 00:00:00 2001 From: 0xFEEDC0DE64 Date: Fri, 6 Feb 2026 23:25:25 +0100 Subject: [PATCH] Introduce new perf-collector and split up scripts --- README.md | 6 + _not_finished/bcachefs_time_stats.sh | 84 +++++++++++ .../bcachefs_homeassistant.sh | 51 +++++++ bcachefs.sh | 98 ++++++------- bcachefs_options.sh | 21 +++ bcachefs_perf.sh | 17 +++ perf-collector/.gitignore | 82 +++++++++++ perf-collector/main.cpp | 130 ++++++++++++++++++ perf-collector/perf-collector.pro | 8 ++ 9 files changed, 451 insertions(+), 46 deletions(-) create mode 100755 _not_finished/bcachefs_time_stats.sh create mode 100755 _not_maintained_anymore/bcachefs_homeassistant.sh mode change 100644 => 100755 bcachefs.sh create mode 100755 bcachefs_options.sh create mode 100755 bcachefs_perf.sh create mode 100644 perf-collector/.gitignore create mode 100644 perf-collector/main.cpp create mode 100644 perf-collector/perf-collector.pro diff --git a/README.md b/README.md index ab7355a..e1d68dc 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,12 @@ Add the following config section to your telegraf.yml: [[inputs.exec]] commands = ["/etc/telegraf/bcachefs.sh"] data_format = "influx" +[[inputs.exec]] + commands = ["/etc/telegraf/bcachefs_options.sh"] + data_format = "influx" +[[inputs.exec]] + commands = ["/etc/telegraf/bcachefs_perf.sh"] + data_format = "influx" ``` ![example disks table](disks-table.png) diff --git a/_not_finished/bcachefs_time_stats.sh b/_not_finished/bcachefs_time_stats.sh new file mode 100755 index 0000000..7e45e69 --- /dev/null +++ b/_not_finished/bcachefs_time_stats.sh @@ -0,0 +1,84 @@ +#!/bin/bash +set -euo pipefail + +cd /sys/fs/bcachefs + +printf "%-36s %-43s %10s %12s %12s %12s %14s %14s %16s %16s\n" \ + "UUID" "STAT" "COUNT" \ + "DUR_MIN" "DUR_MAX" "DUR_TOTAL" \ + "MEAN_SINCE" "MEAN_RECENT" \ + "STDDEV_SINCE" "STDDEV_RECENT" + +for uuid in *; do + cd "$uuid" + + for stat in time_stats/* dev-*/*latency_stats* ; do + count="" + dur_min="" + dur_max="" + dur_total="" + + mean_since="" + mean_recent="" + stddev_since="" + stddev_recent="" + + in_duration=0 + + while IFS= read -r line; do + # trim leading whitespace + line="${line#"${line%%[![:space:]]*}"}" + + case "$line" in + count:*) + count="${line#count:}" + count="${count//[[:space:]]/}" + ;; + "duration of events") + in_duration=1 + ;; + "time between events") + in_duration=0 + ;; + min:*) + (( in_duration )) && dur_min="${line#min:}" + ;; + max:*) + (( in_duration )) && dur_max="${line#max:}" + ;; + total:*) + (( in_duration )) && dur_total="${line#total:}" + ;; + mean:*) + if (( in_duration )); then + rest="${line#mean:}" + read -r ms_val ms_unit mr_val mr_unit <<< "$rest" + mean_since="$ms_val $ms_unit" + mean_recent="$mr_val $mr_unit" + fi + ;; + stddev:*) + if (( in_duration )); then + rest="${line#stddev:}" + read -r ss_val ss_unit sr_val sr_unit <<< "$rest" + stddev_since="$ss_val $ss_unit" + stddev_recent="$sr_val $sr_unit" + fi + ;; + esac + done < "$stat" + + # trim leading whitespace + for v in dur_min dur_max dur_total mean_since mean_recent stddev_since stddev_recent; do + eval "$v=\"\${$v#\"\${$v%%[![:space:]]*}\"}\"" + done + + printf "%-36s %-43s %10s %12s %12s %12s %14s %14s %16s %16s\n" \ + "$uuid" "$stat" "$count" \ + "$dur_min" "$dur_max" "$dur_total" \ + "$mean_since" "$mean_recent" \ + "$stddev_since" "$stddev_recent" + done + + cd .. +done diff --git a/_not_maintained_anymore/bcachefs_homeassistant.sh b/_not_maintained_anymore/bcachefs_homeassistant.sh new file mode 100755 index 0000000..b49b12b --- /dev/null +++ b/_not_maintained_anymore/bcachefs_homeassistant.sh @@ -0,0 +1,51 @@ +#!/bin/sh + +alias pub='mosquitto_pub -h 192.168.0.11' +categories=(replicas checksum erasure_code compression target high_priority pending) + +for category in "${categories[@]}" +do + for type in data metadata + do + pub -t "homeassistant/sensor/bcachefs_${category}_${type}/config" -m "{ + \"name\": \"${category} ${type}\", + \"state_class\": \"measurement\", + \"state_topic\": \"bcachefs/${category}/${type}\", + \"unique_id\": \"bcachefs_${category}_${type}\", + \"device\": { + \"identifiers\": [\"bcachefs /mnt\"], + \"name\": \"BCacheFs /mnt\", + \"manufacturer\": \"BCacheFs\", + \"model\": \"BCacheFs\", + \"sw_version\": \"1.0\" + } + }" -r + done +done + +while sleep 5 +do + RECONCILE_STATUS="$(cat /sys/fs/bcachefs/3d3a0763-4dfe-41e6-93c1-8c791ec98176/reconcile_status)" + + post_result() { + local val="$(echo "$RECONCILE_STATUS" | grep -Po "$2")" + local num unit + num=$(echo "$val" | grep -Po '^[0-9.]+') + unit=$(echo "$val" | grep -Po '[KMGT]$') + + case "$unit" in + K) val="$(echo "$num*1024/1" | bc)" ;; + M) val="$(echo "$num*1024*1024/1" | bc)" ;; + G) val="$(echo "$num*1024*1024*1024/1" | bc)" ;; + T) val="$(echo "$num*1024*1024*1024*1024/1" | bc)" ;; + *) val="$num" ;; + esac + + pub -t bcachefs/$1 -m "$val" + } + for category in "${categories[@]}" + do + post_result "$category/data" "^ *$category: +\\K[^ ]+" + post_result "$category/metadata" "^ *$category: +[^ ]+ +\\K[^ ]+$" + done +done diff --git a/bcachefs.sh b/bcachefs.sh old mode 100644 new mode 100755 index 9ad8c43..ad4baec --- a/bcachefs.sh +++ b/bcachefs.sh @@ -1,21 +1,50 @@ #!/bin/bash -function convert_to_bytes() { - awk ' - { - val=$0 - num=val - sub(/[KMGT]$/, "", num) +convert_to_bytes() { + local val="$1" + local num unit int frac mul result - unit=substr(val, length(val), 1) - mul=1 - if (unit=="K") mul=1024 - else if (unit=="M") mul=1024^2 - else if (unit=="G") mul=1024^3 - else if (unit=="T") mul=1024^4 + # trim whitespace + val="${val#"${val%%[![:space:]]*}"}" + val="${val%"${val##*[![:space:]]}"}" - printf "%.0f\n", num * mul - }' <<< "$1" + # empty input -> 0 + [[ -z "$val" ]] && echo 0 && return + + # check if numeric (optional decimal + unit) + if [[ ! $val =~ ^[0-9]+([.][0-9]+)?[KMGTkmgT]?$ ]]; then + echo 0 + return + fi + + # separate number and unit + num="${val%[KMGTkmgT]}" + unit="${val#$num}" + + # handle decimals + if [[ "$num" == *.* ]]; then + int="${num%%.*}" + frac="${num#*.}" + frac="${frac}000" + frac="${frac:0:3}" + else + int="$num" + frac="0" + fi + + # multiplier + case "${unit^^}" in + K) mul=1024 ;; + M) mul=$((1024*1024)) ;; + G) mul=$((1024*1024*1024)) ;; + T) mul=$((1024*1024*1024*1024)) ;; + *) mul=1 ;; + esac + + # use base 10 for all arithmetic to avoid octal errors + result=$((10#$int * mul + 10#$frac * mul / 1000)) + + echo "$result" } function ensure_comma() { @@ -41,29 +70,23 @@ while IFS= read -r line; do PARSER_STATE=1 elif [[ $line == "Compression:" ]] then - echo -n "bcachefs_compression,fspath=\"$FSPATH\",uuid=\"$uuid\" " + #echo -n "bcachefs_compression,fspath=$FSPATH,uuid=$uuid " FIRST=1 PARSER_STATE=2 elif [[ $line == "Btree usage:" ]] then - echo -n "bcachefs_btree_usage,fspath=\"$FSPATH\",uuid=\"$uuid\" " + echo -n "bcachefs_btree_usage,fspath=$FSPATH,uuid=$uuid " FIRST=1 PARSER_STATE=3 elif [[ $line =~ ^Pending\ reconcile: ]] then - echo -n "bcachefs_reconcile,fspath=\"$FSPATH\",uuid=\"$uuid\" " + echo -n "bcachefs_reconcile,fspath=$FSPATH,uuid=$uuid " FIRST=1 PARSER_STATE=4 REMAINING=(replicas checksum erasure_code compression target high_priority pending) elif [[ $line =~ ^([^ ]+)\ \(device\ ([0-9]+)\):[[:space:]]+([^[:space:]]+)[[:space:]]+([^[:space:]]+)[[:space:]]+([0-9]+)%$ ]] then - blockdev="${BASH_REMATCH[3]}" - if [[ ! $blockdev == /dev/* ]] - then - blockdev="/dev/$blockdev" - fi - echo -n "bcachefs_devices,fspath=\"$FSPATH\",uuid=\"$uuid\",devlabel=\"${BASH_REMATCH[1]}\",devid=${BASH_REMATCH[2]},blockdev=\"$blockdev\" mode=\"${BASH_REMATCH[4]}\",usage=${BASH_REMATCH[5]}" - + echo -n "bcachefs_devices,fspath=$FSPATH,uuid=$uuid,label=${BASH_REMATCH[1]},devid=${BASH_REMATCH[2]},device=${BASH_REMATCH[3]} mode=\"${BASH_REMATCH[4]}\",usage=${BASH_REMATCH[5]}" PARSER_STATE=5 #else #echo unknown? @@ -78,7 +101,7 @@ while IFS= read -r line; do 2) if [[ "$line" == "" ]] then - echo + #echo PARSER_STATE=0 elif [[ $line =~ ^([^[:space:]]+)[[:space:]]*(.*)$ ]] then @@ -88,18 +111,18 @@ while IFS= read -r line; do read -r val1 val2 val3 <<<"$rest" val1="$(convert_to_bytes "$val1")" - ensure_comma + #ensure_comma - echo -n "${field}_compressed=$val1" + #echo -n "${field}_compressed=$val1" if [[ ! -z "$val2" ]] then val2="$(convert_to_bytes "$val2")" - echo -n ",${field}_uncompressed=$val2" + #echo -n ",${field}_uncompressed=$val2" fi if [[ ! -z "$val3" ]] then val3="$(convert_to_bytes "$val3")" - echo -n ",${field}_avgextsize=$val3" + #echo -n ",${field}_avgextsize=$val3" fi #else #echo unknown? @@ -186,20 +209,3 @@ while IFS= read -r line; do # echo "Got line: $line" #fi done < <(sudo bcachefs fs usage -a "$FSPATH") - -cd "/sys/fs/bcachefs/${uuid}/options" || exit 1 -echo -n "bcachefs_options,fspath=\"$FSPATH\",uuid=\"$uuid\" " -FIRST=1 -for i in * -do - if [[ $FIRST == 1 ]] - then - FIRST= - else - echo -n , - fi - - echo -n "${i}=\"$(cat "$i")\"" -done - -echo diff --git a/bcachefs_options.sh b/bcachefs_options.sh new file mode 100755 index 0000000..cb691a5 --- /dev/null +++ b/bcachefs_options.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +FSPATH="/mnt" +uuid=3d3a0763-4dfe-41e6-93c1-8c791ec98176 + +cd "/sys/fs/bcachefs/${uuid}/options" || exit 1 +echo -n "bcachefs_options,fspath=$FSPATH,uuid=$uuid " +FIRST=1 +for i in * +do + if [[ $FIRST == 1 ]] + then + FIRST= + else + echo -n , + fi + + echo -n "${i}=\"$(cat "$i")\"" +done + +echo diff --git a/bcachefs_perf.sh b/bcachefs_perf.sh new file mode 100755 index 0000000..aa1e8e7 --- /dev/null +++ b/bcachefs_perf.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +curl localhost:8000/perf_json | jq -r ' + to_entries[] as $fs | + $fs.value + | to_entries[] + | . as $func + | ( + $func.value + | to_entries + | map( + (.key | gsub("[^A-Za-z0-9_]"; "_")) + "=" + (.value|tostring) + "i" + ) + | join(",") + ) as $fields + | "bcachefs_perf,function=\($func.key),uuid=\($fs.key) \($fields)" +' diff --git a/perf-collector/.gitignore b/perf-collector/.gitignore new file mode 100644 index 0000000..aa3808c --- /dev/null +++ b/perf-collector/.gitignore @@ -0,0 +1,82 @@ +# This file is used to ignore files which are generated +# ---------------------------------------------------------------------------- + +*~ +*.autosave +*.a +*.core +*.moc +*.o +*.obj +*.orig +*.rej +*.so +*.so.* +*_pch.h.cpp +*_resource.rc +*.qm +.#* +*.*# +core +!core/ +tags +.DS_Store +.directory +*.debug +Makefile* +*.prl +*.app +moc_*.cpp +ui_*.h +qrc_*.cpp +Thumbs.db +*.res +*.rc +/.qmake.cache +/.qmake.stash + +# qtcreator generated files +*.pro.user* +*.qbs.user* +CMakeLists.txt.user* + +# xemacs temporary files +*.flc + +# Vim temporary files +.*.swp + +# Visual Studio generated files +*.ib_pdb_index +*.idb +*.ilk +*.pdb +*.sln +*.suo +*.vcproj +*vcproj.*.*.user +*.ncb +*.sdf +*.opensdf +*.vcxproj +*vcxproj.* + +# MinGW generated files +*.Debug +*.Release + +# Python byte code +*.pyc + +# Binaries +# -------- +*.dll +*.exe + +# Directories with generated files +.moc/ +.obj/ +.pch/ +.rcc/ +.uic/ +/build*/ diff --git a/perf-collector/main.cpp b/perf-collector/main.cpp new file mode 100644 index 0000000..9725142 --- /dev/null +++ b/perf-collector/main.cpp @@ -0,0 +1,130 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QHash>> counters; + +int main(int argc, char *argv[]) +{ + QCoreApplication app{argc, argv}; + + auto tcpServer = std::make_unique(); + + QHttpServer server; + + if (!tcpServer->listen(QHostAddress::LocalHost, 8000)) + return -1; + + if (!server.bind(tcpServer.get())) + return -2; + + tcpServer.release(); + + server.route("/perf_json", [](){ + auto filesystems = QJsonObject{}; + + for (auto iter = std::cbegin(counters); iter != std::cend(counters); iter++) + { + auto functions = QJsonObject{}; + + for (auto iter2 = std::cbegin(iter.value()); iter2 != std::cend(iter.value()); iter2++) + { + auto strs = QJsonObject{}; + + for (auto iter3 = std::cbegin(iter2.value()); iter3 != std::cend(iter2.value()); iter3++) + strs[iter3.key()] = iter3.value(); + + functions[iter2.key()] = std::move(strs); + } + + filesystems[iter.key()] = std::move(functions); + } + + return filesystems; + }); + + QProcess process; + + process.setProcessChannelMode(QProcess::MergedChannels); + + process.setChildProcessModifier([] { + prctl(PR_SET_PDEATHSIG, SIGKILL); + }); + + QObject::connect(&process, &QProcess::started, [](){ + qDebug() << "started"; + }); + + QObject::connect(&process, &QProcess::finished, [&](int exitCode, QProcess::ExitStatus exitStatus){ + qDebug() << "finished exitCode =" << exitCode << "exitStatus =" << exitStatus; + app.exit(exitCode); + }); + + QObject::connect(&process, &QProcess::readyRead, [&](){ + while (process.canReadLine()) + { + auto lineStr = process.readLine(); + + QByteArrayView line = lineStr; + line = line.trimmed(); + + //qDebug() << "received" << line; + + qsizetype tsEnd = line.indexOf(' '); + QByteArrayView timestamp = line.left(tsEnd); + + qsizetype lparen = line.indexOf('(', tsEnd + 1); + + qsizetype funcStart = line.lastIndexOf(' ', lparen); + QByteArrayView function = line.mid(funcStart + 1, lparen - funcStart - 1); + + QByteArrayView thread = line.mid(tsEnd + 1, funcStart - tsEnd - 1); + + qsizetype rparen = line.lastIndexOf(')'); + QByteArrayView args = line.mid(lparen + 1, rparen - lparen - 1); + + //qDebug() << "timestamp =" << timestamp; + //qDebug() << "thread =" << thread; + //qDebug() << "function =" << function; + //qDebug() << "args =" << args; + + QByteArrayView fs, str; + while (!args.isEmpty()) + { + qsizetype colon = args.indexOf(':'); + qsizetype quote1 = args.indexOf('"', colon); + qsizetype quote2 = args.indexOf('"', quote1 + 1); + + QByteArrayView key = args.left(colon).trimmed(); + QByteArrayView value = args.mid(quote1 + 1, quote2 - quote1 - 1); + + //qDebug() << "key =" << key << "value =" << value; + + if (key == "fs") + fs = value; + else if (key == "str") + str = value; + + qsizetype next = args.indexOf(',', quote2); + if (next == -1) break; + args = args.mid(next + 1).trimmed(); + } + + if (fs.isEmpty()) + continue; + + counters[fs][function][str]++; + } + }); + + process.start("sudo", {"perf", "trace", "-e", "bcachefs:error_throw", "-e", "bcachefs:write_super"}); + + return app.exec(); +} diff --git a/perf-collector/perf-collector.pro b/perf-collector/perf-collector.pro new file mode 100644 index 0000000..1282e91 --- /dev/null +++ b/perf-collector/perf-collector.pro @@ -0,0 +1,8 @@ +QT = core network httpserver + +CONFIG += c++17 cmdline + +DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +SOURCES += \ + main.cpp