1
0
mirror of https://github.com/ossrs/srs.git synced 2026-10-28 22:59:37 +03:00
Files
srs/cmd/perf/smoke.go
Winlin 7b737e64df Perf: Load and profile tools, and the first SRS and Go proxy fixes. v8.0.63 (#4785)
SRS gets performance tools that load and profile SRS in Docker for every
protocol: a lean load tool, an internal skill that runs an improvement
round, and a measurement method that holds up to a 10% verdict. The same
tools then measure the Go proxy. The first runs found one SRS fix and
three Go proxy fixes.

The load tool, a standalone Go module in cmd/perf (bin/srs-perf):

- Per-core worker processes shard the clients and report counters each
second. Lean clients for every protocol: RTMP publish and play,
HTTP-FLV, HTTP-TS, HLS, DASH, RTSP, SRT, WHIP and WHEP. No decode;
frames and lag come from timestamps.
- 17 scenarios: each protocol's fan-out, publishers (rtmp-pub,
whip-pub), many-streams, cross-protocol bridges (srt-rtmp, srt-whep,
whip-rtmp, whip-flv), and delay probes for the RTMP pause, forward and
edge.
- run ramps by doubling to a capacity, then holds at 50% and 90% of it.
compare checks that the setups match and reports capacity and CPU per
client at the 10% line.
- make perf-image builds an optimized SRS with symbols and frame
pointers, with perf, FlameGraph and FFmpeg. SRS runs on one pinned core
and is configured only by env files, one per scenario.

The measurement method:

- A flat CBR source, checked to ±3% per second, since SRS CPU follows
the bitrate.
- SRS CPU from its cgroup once a second. Holds have no profiler in the
measuring window; each count gets its own separate profile hold.
- perf-ab.sh builds two revisions and runs them side by side on separate
cpusets. compare gives the 95% CI of the paired per-second difference.
- perf-verify.sh checks every run: capacity, healthy steps, profiles and
symbols, noise, and what bound the run.

The internal-perf-for-srs skill:

- SKILL.md holds the rules, the shared tools and the round workflow. A
Target Router loads references/cpp-server.md for the C++ media server or
references/go-server.md for the Go proxy.
- Each reference covers its tools, topology, scenarios, measuring, how
to read its profiles (Linux perf, or Go pprof and trace), A/B, the
verified scenarios with their capacity and top bottleneck, and how to
start a round.
- srs-develop routes performance, benchmark, load test and profile tasks
to it. perf-skill-test.sh checks the text against the scenario registry.
- Reports are git-ignored, since their numbers hold only for the machine
that made them.
- The skills now name each server by its job: the C++ media server and
the Go proxy, with no "generation".

C++ media server, one core, Linux arm64 in Docker:

- Fix: an empty SrsSharedPtr holds no reference count, so each fan-out
copy of a message does one malloc instead of three. Covered by
srs_utest_ai05.cpp.
- Capacity: rtmp-rtmp, rtmp-flv, rtmp-hls, whip-rtmp and whip-flv
12,800; rtmp-dash and srt-rtmp 6,400; rtmp-ts and rtmp-rtsp 3,200;
whip-whep 2,000 (cap); rtmp-whep, srt-whep, srt-srt and rtmp-pub 1,280;
whip-pub 1,000 (cap); many-streams 640 streams.
- Top bottlenecks found, not fixed: the RTMP fan-out copy,
_st_epoll_dispatch with EAGAIN reads, 4 KB reads and writes for HLS and
DASH segments, one write per message for HTTP-TS and two per packet for
RTSP, the SRTP replay window in libsrtp, and libsrt for SRT.
- Delays: the paused RTMP player's 500 ms sleep, and the forward's and
edge publish's 500 ms receive timeout, each adding about 220 ms of lag.

The Go proxy, cmd/proxy, on one core in front of 1 to 4 SRS origins:

- perf-up.sh -target proxy, run -target proxy, which samples the proxy
and each origin, Go profiles in each profile hold (CPU, allocations,
mutex, block, trace, GC), and proxy A/B.
- Fix: HTTP-FLV, HTTP-TS and HLS relay the origin's error status,
headers and body, rather than a 500 with the origin's address.
- Fix: a WebRTC STUN binding routes by its ufrag, not a cached client
address. WHIP and WHEP failed from 160 clients on three origins.
- Capacity on three origins: rtmp-flv and rtmp-hls 12,800; rtmp-rtmp and
rtmp-ts 6,400; whip-whep 2,000 (cap); srt-srt and rtmp-pub 1,280;
whip-pub 1,000 (cap); many-streams 1,280 streams.

---------

Co-authored-by: chatgpt-codex-connector[bot] <199175422+chatgpt-codex-connector[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 18:46:30 -04:00

221 lines
7.2 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io"
"sync"
"time"
)
// runSmoke publishes the source with the scenario's publisher and plays it
// with 100 players of the scenario's protocol for 10s, or for three segment
// durations, by the scenario's gap and lag rules.
func runSmoke(output io.Writer, cmd command) error {
const clients = 100
s := scenarios[cmd.scenario]
if s.Unit == "probes" {
return runDelaySmoke(output, cmd)
}
if s.Unit != "clients" {
return runPublisherSmoke(output, cmd, clients)
}
dial, err := playerDialer(s.Player)
if err != nil {
return err
}
tags, flatness, err := loadSource(cmd.media)
if err != nil {
return err
}
// SRS, or the proxy with its origins beside it, is pid 1 of the load
// container's pid namespace.
measured, origins, err := targetSetup(withSource(setup{}, cmd.media, flatness), cmd.target, proxyAPI, "/proc", 1)
if err != nil {
return err
}
// One stream on SRS, or one on each origin behind the proxy, with the
// players split over them.
apis := originAPIs(origins)
published, err := startStepStreams(scenarios[cmd.scenario].Publisher, "perf-smoke", cmd.media, tags, apis)
if err != nil {
return err
}
stop := make(chan struct{})
var stopOnce sync.Once
var stopErr error
stopAll := func() { stopOnce.Do(func() { close(stop); stopErr = stopStreams(published) }) }
// A publisher that does not stop must not hold up an error's return.
defer func() { go stopAll() }()
if measured.Shares, err = targetShares(s, apis, published, "perf-smoke", clients); err != nil {
return err
}
names := streamNames(published)
timeline, err := lagTimeline(cmd.media, tags)
if err != nil {
return err
}
players := newWorkerPlayers(clients, timeline)
players.gap = s.gap()
players.streams = playerStreamIndex(0, clients, len(names))
errors := make(chan error, clients)
var wg sync.WaitGroup
for i := 0; i < clients; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
c, err := dial()
if err != nil {
errors <- fmt.Errorf("player %d dial: %w", id, err)
return
}
report := make(chan rtmpMessage, 128)
go func() {
for m := range report {
players.received(id, m)
}
}()
if err := c.play(names[players.streams[id]], stop, report); err != nil {
select {
case <-stop:
default:
errors <- fmt.Errorf("player %d: %w", id, err)
}
}
close(report)
}(i)
}
// SRS shares the load container's pid namespace as pid 1.
ticks, err := clockTicks()
if err != nil {
return err
}
sampler := newProcSampler("/proc", "/sys/fs/cgroup", 1, nil, ticks).withOrigins(origins)
if _, err := sampler.sampleAt(time.Now()); err != nil {
return err
}
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var samples []sample
var maxLag int64
for len(samples) < s.smokeSeconds() {
select {
case err := <-errors:
return err
case now := <-ticker.C:
counters := players.sample(streamTimestamps(published), false)
usage, err := sampler.sampleAt(now)
if err != nil {
return err
}
second := sample{Second: len(samples) + 1, Frames: counters.Frames, Segments: counters.Segments, Bytes: counters.Bytes, LagMillis: counters.LagMillis}
second.SRSCPUPercent, second.SRSCPUUsageUsec, second.SRSRSSBytes = usage.srsCPUPercent, usage.srsCPUUsageUsec, usage.srsRSSBytes
second.OriginCPUPercent, second.OriginCPUUsageUsec = usage.originCPUPercent, usage.originCPUUsageUsec
samples = append(samples, second)
if counters.LagMillis > maxLag {
maxLag = counters.LagMillis
}
}
}
for i := range players.last {
at := players.last[i].Load()
if at == 0 || time.Since(time.Unix(0, at)) > s.gap() {
return fmt.Errorf("player %d has no recent frame", i)
}
}
if limit := s.lagLimit(); limit > 0 && maxLag > limit {
return fmt.Errorf("player lag %dms exceeds %dms", maxLag, limit)
}
stopped := make(chan struct{})
go func() { stopAll(); close(stopped) }()
select {
case <-stopped:
if stopErr != nil {
return stopErr
}
case <-time.After(3 * time.Second):
return fmt.Errorf("publisher did not stop")
}
done := make(chan struct{})
go func() { wg.Wait(); close(done) }()
select {
case <-time.After(3 * time.Second):
return fmt.Errorf("players did not stop")
case <-done:
}
r := result{Setup: measured, Scenario: scenarios[cmd.scenario], Steps: []step{{Mode: "smoke", Clients: clients, SettleSeconds: 2, Samples: samples, Health: health{Healthy: true}, Validity: validity{Valid: true}}}, Health: health{Healthy: true}, Validity: validity{Valid: true}}
return json.NewEncoder(output).Encode(summarizeResult(r, "smoke"))
}
// runPublisherSmoke runs a publisher or many-streams scenario's clients in
// this process, as a worker runs them, for 10s: every publisher keeps its
// pace, every player gets frames within the lag limit, and none fails, the
// last second judging a client that never sent or got anything.
func runPublisherSmoke(output io.Writer, cmd command, clients int) error {
s := scenarios[cmd.scenario]
tags, flatness, err := loadSource(cmd.media)
if err != nil {
return err
}
measured, origins, err := targetSetup(withSource(setup{}, cmd.media, flatness), cmd.target, proxyAPI, "/proc", 1)
if err != nil {
return err
}
timeline, err := lagTimeline(cmd.media, tags)
if err != nil {
return err
}
runtime, err := startClients(s, clients, []string{"perf-smoke"}, 0, cmd.media, tags, timeline)
if err != nil {
return err
}
closed := false
defer func() {
if !closed {
runtime.close()
}
}()
ticks, err := clockTicks()
if err != nil {
return err
}
sampler := newProcSampler("/proc", "/sys/fs/cgroup", 1, nil, ticks).withOrigins(origins)
if _, err := sampler.sampleAt(time.Now()); err != nil {
return err
}
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var samples []sample
for len(samples) < s.smokeSeconds() {
now := <-ticker.C
counters := runtime.sample(nil, len(samples)+1 == s.smokeSeconds())
usage, err := sampler.sampleAt(now)
if err != nil {
return err
}
second := sample{Second: len(samples) + 1, Frames: counters.Frames, Bytes: counters.Bytes, LagMillis: counters.LagMillis, Failures: counters.Failures}
second.SRSCPUPercent, second.SRSCPUUsageUsec, second.SRSRSSBytes = usage.srsCPUPercent, usage.srsCPUUsageUsec, usage.srsRSSBytes
second.OriginCPUPercent, second.OriginCPUUsageUsec = usage.originCPUPercent, usage.originCPUUsageUsec
samples = append(samples, second)
if counters.Failures > 0 {
return fmt.Errorf("second %d: %d %s failed", second.Second, counters.Failures, s.Unit)
}
if limit := s.lagLimit(); limit > 0 && counters.LagMillis > limit {
return fmt.Errorf("second %d: lag %dms exceeds %dms", second.Second, counters.LagMillis, limit)
}
}
if measured.Shares, err = targetShares(s, originAPIs(origins), nil, "perf-smoke", clients); err != nil {
return err
}
done := make(chan struct{})
go func() { runtime.close(); close(done) }()
closed = true
select {
case <-time.After(3 * time.Second):
return fmt.Errorf("%s did not stop", s.Unit)
case <-done:
}
r := result{Setup: measured, Scenario: s, Steps: []step{{Mode: "smoke", Clients: clients, SettleSeconds: 2, Samples: samples, Health: health{Healthy: true}, Validity: validity{Valid: true}}}, Health: health{Healthy: true}, Validity: validity{Valid: true}}
return json.NewEncoder(output).Encode(summarizeResult(r, "smoke"))
}