373 lines
11 KiB
Go
373 lines
11 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"math"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/Nwflower/reims-go/internal/qmp"
|
|
)
|
|
|
|
type Snapshot struct {
|
|
Timestamp string `json:"timestamp"`
|
|
Device string `json:"device"`
|
|
Entry *qmp.BlockStats `json:"entry,omitempty"`
|
|
Entries []qmp.BlockStats `json:"entries"`
|
|
}
|
|
|
|
type HistogramDelta struct {
|
|
BoundariesNS []uint64 `json:"boundaries_ns"`
|
|
Bins []uint64 `json:"bins"`
|
|
Samples uint64 `json:"samples"`
|
|
P50LeUS float64 `json:"p50_le_us,omitempty"`
|
|
P99LeUS float64 `json:"p99_le_us,omitempty"`
|
|
}
|
|
|
|
type LayerDelta struct {
|
|
NodeName string `json:"node_name,omitempty"`
|
|
RdOps uint64 `json:"rd_ops"`
|
|
WrOps uint64 `json:"wr_ops"`
|
|
FlushOps uint64 `json:"flush_ops"`
|
|
UnmapOps uint64 `json:"unmap_ops"`
|
|
RdBytes uint64 `json:"rd_bytes"`
|
|
WrBytes uint64 `json:"wr_bytes"`
|
|
UnmapBytes uint64 `json:"unmap_bytes"`
|
|
RdTimeMS float64 `json:"rd_time_ms"`
|
|
WrTimeMS float64 `json:"wr_time_ms"`
|
|
FlushTimeMS float64 `json:"flush_time_ms"`
|
|
TotalTimeMS float64 `json:"total_time_ms"`
|
|
RdAvgUS float64 `json:"rd_avg_us"`
|
|
WrAvgUS float64 `json:"wr_avg_us"`
|
|
FlushAvgUS float64 `json:"flush_avg_us"`
|
|
FlushTimeSharePct float64 `json:"flush_time_share_pct"`
|
|
RdHist *HistogramDelta `json:"rd_hist,omitempty"`
|
|
WrHist *HistogramDelta `json:"wr_hist,omitempty"`
|
|
FlushHist *HistogramDelta `json:"flush_hist,omitempty"`
|
|
}
|
|
|
|
type DiffOutput struct {
|
|
Device string `json:"device"`
|
|
BeforeTime string `json:"before_time"`
|
|
AfterTime string `json:"after_time"`
|
|
Disk LayerDelta `json:"disk"`
|
|
Parent *LayerDelta `json:"parent,omitempty"`
|
|
ReadOpsAmp float64 `json:"read_ops_amp,omitempty"`
|
|
WriteOpsAmp float64 `json:"write_ops_amp,omitempty"`
|
|
FlushOpsAmp float64 `json:"flush_ops_amp,omitempty"`
|
|
WriteBytesAmp float64 `json:"write_bytes_amp,omitempty"`
|
|
}
|
|
|
|
func main() {
|
|
if len(os.Args) < 2 {
|
|
fatalf("usage: qmp-blockstats <snapshot|histogram|diff> [flags]")
|
|
}
|
|
sub := os.Args[1]
|
|
args := os.Args[2:]
|
|
var err error
|
|
switch sub {
|
|
case "snapshot":
|
|
err = cmdSnapshot(args)
|
|
case "histogram":
|
|
err = cmdHistogram(args)
|
|
case "diff":
|
|
err = cmdDiff(args)
|
|
default:
|
|
err = fmt.Errorf("unknown subcommand %q (expected snapshot|histogram|diff)", sub)
|
|
}
|
|
if err != nil {
|
|
fatalf("%v", err)
|
|
}
|
|
}
|
|
|
|
func fatalf(format string, args ...any) {
|
|
fmt.Fprintf(os.Stderr, "qmp-blockstats: "+format+"\n", args...)
|
|
os.Exit(1)
|
|
}
|
|
|
|
func dialQMP(ctx context.Context, vmDir, sockPath string) (*qmp.Conn, error) {
|
|
target := sockPath
|
|
if target == "" {
|
|
if vmDir == "" {
|
|
return nil, fmt.Errorf("either -vm-dir or -socket is required")
|
|
}
|
|
target = qmp.SocketPath(vmDir)
|
|
}
|
|
return qmp.Dial(ctx, "unix", target)
|
|
}
|
|
|
|
func cmdSnapshot(args []string) error {
|
|
fs := flag.NewFlagSet("snapshot", flag.ContinueOnError)
|
|
vmDir := fs.String("vm-dir", "", "VM directory containing qmp.sock")
|
|
sockPath := fs.String("socket", "", "explicit QMP unix socket path")
|
|
device := fs.String("device", "disk", "target block device id")
|
|
outPath := fs.String("out", "", "optional output JSON file path (default stdout)")
|
|
if err := fs.Parse(args); err != nil {
|
|
return err
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
c, err := dialQMP(ctx, *vmDir, *sockPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer c.Close()
|
|
|
|
entries, err := c.QueryBlockStats()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
snap := Snapshot{
|
|
Timestamp: time.Now().UTC().Format(time.RFC3339Nano),
|
|
Device: *device,
|
|
Entries: entries,
|
|
}
|
|
if entry, ok := qmp.FindBlockStats(entries, *device); ok {
|
|
snap.Entry = &entry
|
|
}
|
|
return writeJSON(*outPath, snap)
|
|
}
|
|
|
|
func cmdHistogram(args []string) error {
|
|
fs := flag.NewFlagSet("histogram", flag.ContinueOnError)
|
|
vmDir := fs.String("vm-dir", "", "VM directory containing qmp.sock")
|
|
sockPath := fs.String("socket", "", "explicit QMP unix socket path")
|
|
device := fs.String("device", "disk", "target block device id")
|
|
clear := fs.Bool("clear", false, "disable/clear latency histograms")
|
|
if err := fs.Parse(args); err != nil {
|
|
return err
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
c, err := dialQMP(ctx, *vmDir, *sockPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer c.Close()
|
|
|
|
targetID := *device
|
|
// QEMU 11's block-latency-histogram-set expects the qdev path (e.g.
|
|
// "/machine/peripheral-anon/device[3]") rather than the legacy drive id
|
|
// ("disk"). Resolve device -> qdev via query-blockstats automatically.
|
|
if entries, qerr := c.QueryBlockStats(); qerr == nil {
|
|
if entry, ok := qmp.FindBlockStats(entries, *device); ok && entry.QDev != "" {
|
|
targetID = entry.QDev
|
|
}
|
|
}
|
|
|
|
var boundaries []uint64
|
|
if !*clear {
|
|
boundaries = qmp.DefaultLatencyHistogramBoundariesNS
|
|
}
|
|
if err := c.SetBlockLatencyHistogram(targetID, boundaries); err != nil {
|
|
return err
|
|
}
|
|
return writeJSON("", map[string]any{
|
|
"device": *device,
|
|
"qdev": targetID,
|
|
"enabled": !*clear,
|
|
"boundaries": boundaries,
|
|
})
|
|
}
|
|
|
|
func cmdDiff(args []string) error {
|
|
fs := flag.NewFlagSet("diff", flag.ContinueOnError)
|
|
beforePath := fs.String("before", "", "before snapshot JSON path")
|
|
afterPath := fs.String("after", "", "after snapshot JSON path")
|
|
device := fs.String("device", "disk", "target block device id")
|
|
outPath := fs.String("out", "", "optional output JSON file path (default stdout)")
|
|
if err := fs.Parse(args); err != nil {
|
|
return err
|
|
}
|
|
if *beforePath == "" || *afterPath == "" {
|
|
return fmt.Errorf("-before and -after are required")
|
|
}
|
|
|
|
before, err := readSnapshot(*beforePath)
|
|
if err != nil {
|
|
return fmt.Errorf("read before: %w", err)
|
|
}
|
|
after, err := readSnapshot(*afterPath)
|
|
if err != nil {
|
|
return fmt.Errorf("read after: %w", err)
|
|
}
|
|
diff, err := computeDiff(before, after, *device)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return writeJSON(*outPath, diff)
|
|
}
|
|
|
|
func readSnapshot(path string) (Snapshot, error) {
|
|
b, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return Snapshot{}, err
|
|
}
|
|
var s Snapshot
|
|
if err := json.Unmarshal(b, &s); err != nil {
|
|
return Snapshot{}, err
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
func findInSnapshot(s Snapshot, device string) (qmp.BlockStats, bool) {
|
|
if s.Entry != nil && (s.Entry.Device == device || s.Entry.QDev == device || s.Entry.NodeName == device) {
|
|
return *s.Entry, true
|
|
}
|
|
return qmp.FindBlockStats(s.Entries, device)
|
|
}
|
|
|
|
func computeDiff(before, after Snapshot, device string) (DiffOutput, error) {
|
|
bEntry, ok := findInSnapshot(before, device)
|
|
if !ok {
|
|
return DiffOutput{}, fmt.Errorf("device %q not found in before snapshot", device)
|
|
}
|
|
aEntry, ok := findInSnapshot(after, device)
|
|
if !ok {
|
|
return DiffOutput{}, fmt.Errorf("device %q not found in after snapshot", device)
|
|
}
|
|
|
|
out := DiffOutput{
|
|
Device: device,
|
|
BeforeTime: before.Timestamp,
|
|
AfterTime: after.Timestamp,
|
|
Disk: diffLayer(bEntry, aEntry),
|
|
}
|
|
if bEntry.Parent != nil && aEntry.Parent != nil {
|
|
p := diffLayer(*bEntry.Parent, *aEntry.Parent)
|
|
out.Parent = &p
|
|
if out.Disk.RdOps > 0 {
|
|
out.ReadOpsAmp = round3(float64(p.RdOps) / float64(out.Disk.RdOps))
|
|
}
|
|
if out.Disk.WrOps > 0 {
|
|
out.WriteOpsAmp = round3(float64(p.WrOps) / float64(out.Disk.WrOps))
|
|
}
|
|
if out.Disk.FlushOps > 0 {
|
|
out.FlushOpsAmp = round3(float64(p.FlushOps) / float64(out.Disk.FlushOps))
|
|
}
|
|
if out.Disk.WrBytes > 0 {
|
|
out.WriteBytesAmp = round3(float64(p.WrBytes) / float64(out.Disk.WrBytes))
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func subU64(after, before uint64) uint64 {
|
|
if after < before {
|
|
return 0
|
|
}
|
|
return after - before
|
|
}
|
|
|
|
func diffLayer(b, a qmp.BlockStats) LayerDelta {
|
|
rdOps := subU64(a.Stats.RdOperations, b.Stats.RdOperations)
|
|
wrOps := subU64(a.Stats.WrOperations, b.Stats.WrOperations)
|
|
flOps := subU64(a.Stats.FlushOperations, b.Stats.FlushOperations)
|
|
unmapOps := subU64(a.Stats.UnmapOperations, b.Stats.UnmapOperations)
|
|
|
|
rdNS := subU64(a.Stats.RdTotalTimeNS, b.Stats.RdTotalTimeNS)
|
|
wrNS := subU64(a.Stats.WrTotalTimeNS, b.Stats.WrTotalTimeNS)
|
|
flNS := subU64(a.Stats.FlushTotalTimeNS, b.Stats.FlushTotalTimeNS)
|
|
totNS := rdNS + wrNS + flNS
|
|
|
|
d := LayerDelta{
|
|
NodeName: a.NodeName,
|
|
RdOps: rdOps,
|
|
WrOps: wrOps,
|
|
FlushOps: flOps,
|
|
UnmapOps: unmapOps,
|
|
RdBytes: subU64(a.Stats.RdBytes, b.Stats.RdBytes),
|
|
WrBytes: subU64(a.Stats.WrBytes, b.Stats.WrBytes),
|
|
UnmapBytes: subU64(a.Stats.UnmapBytes, b.Stats.UnmapBytes),
|
|
RdTimeMS: round3(float64(rdNS) / 1e6),
|
|
WrTimeMS: round3(float64(wrNS) / 1e6),
|
|
FlushTimeMS: round3(float64(flNS) / 1e6),
|
|
TotalTimeMS: round3(float64(totNS) / 1e6),
|
|
RdHist: diffHistogram(b.Stats.RdLatencyHistogram, a.Stats.RdLatencyHistogram),
|
|
WrHist: diffHistogram(b.Stats.WrLatencyHistogram, a.Stats.WrLatencyHistogram),
|
|
FlushHist: diffHistogram(b.Stats.FlushLatencyHistogram, a.Stats.FlushLatencyHistogram),
|
|
}
|
|
if rdOps > 0 {
|
|
d.RdAvgUS = round3(float64(rdNS) / float64(rdOps) / 1e3)
|
|
}
|
|
if wrOps > 0 {
|
|
d.WrAvgUS = round3(float64(wrNS) / float64(wrOps) / 1e3)
|
|
}
|
|
if flOps > 0 {
|
|
d.FlushAvgUS = round3(float64(flNS) / float64(flOps) / 1e3)
|
|
}
|
|
if totNS > 0 {
|
|
d.FlushTimeSharePct = round3(float64(flNS) * 100.0 / float64(totNS))
|
|
}
|
|
return d
|
|
}
|
|
|
|
func diffHistogram(b, a *qmp.BlockLatencyHistogram) *HistogramDelta {
|
|
if a == nil || len(a.Bins) == 0 {
|
|
return nil
|
|
}
|
|
bins := make([]uint64, len(a.Bins))
|
|
var samples uint64
|
|
sameLayout := b != nil && len(b.Bins) == len(a.Bins) && len(b.Boundaries) == len(a.Boundaries)
|
|
for i := range a.Bins {
|
|
var prev uint64
|
|
if sameLayout {
|
|
prev = b.Bins[i]
|
|
}
|
|
bins[i] = subU64(a.Bins[i], prev)
|
|
samples += bins[i]
|
|
}
|
|
hd := &HistogramDelta{
|
|
BoundariesNS: a.Boundaries,
|
|
Bins: bins,
|
|
Samples: samples,
|
|
}
|
|
if samples > 0 {
|
|
hd.P50LeUS = round3(histPercentileUpperUS(a.Boundaries, bins, samples, 0.50))
|
|
hd.P99LeUS = round3(histPercentileUpperUS(a.Boundaries, bins, samples, 0.99))
|
|
}
|
|
return hd
|
|
}
|
|
|
|
// histPercentileUpperUS returns the upper boundary in microseconds of the bin
|
|
// containing quantile p (or the highest boundary if it falls in the overflow bin).
|
|
func histPercentileUpperUS(boundaries, bins []uint64, total uint64, p float64) float64 {
|
|
if total == 0 || len(boundaries) == 0 {
|
|
return 0
|
|
}
|
|
target := uint64(math.Ceil(float64(total) * p))
|
|
var acc uint64
|
|
for i, c := range bins {
|
|
acc += c
|
|
if acc >= target {
|
|
if i < len(boundaries) {
|
|
return float64(boundaries[i]) / 1e3
|
|
}
|
|
return float64(boundaries[len(boundaries)-1]) / 1e3
|
|
}
|
|
}
|
|
return float64(boundaries[len(boundaries)-1]) / 1e3
|
|
}
|
|
|
|
func writeJSON(outPath string, v any) error {
|
|
b, err := json.MarshalIndent(v, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
b = append(b, '\n')
|
|
if outPath != "" {
|
|
return os.WriteFile(outPath, b, 0o644)
|
|
}
|
|
_, err = os.Stdout.Write(b)
|
|
return err
|
|
}
|
|
|
|
func round3(v float64) float64 {
|
|
return math.Round(v*1000) / 1000
|
|
}
|