Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# REQUIRED
# Kind can be one of:
# - breaking-change: a change to previously-documented behavior
# - deprecation: functionality that is being removed in a later release
# - bug-fix: fixes a problem in a previous version
# - enhancement: extends functionality but does not break or fix existing behavior
# - feature: new functionality
# - known-issue: problems that we are aware of in a given version
# - security: impacts on the security of a product or a user’s deployment.
# - upgrade: important information for someone upgrading from a prior version
# - other: does not fit into any of the other categories
kind: enhancement

# REQUIRED for all kinds
# Change summary; a 80ish characters long description of the change.
summary: Allocate output send-latency reservoirs lazily to reduce per-instance memory.

# REQUIRED for breaking-change, deprecation, known-issue
# Long description; in case the summary is not enough to describe the change
# this field accommodate a description without length limits.
description: >-
The write.latency and write.latency_delta reservoirs are now allocated on the
first reported latency instead of when the output stats are created.

# REQUIRED for breaking-change, deprecation, known-issue
# impact:

# REQUIRED for breaking-change, deprecation, known-issue
# action:

# REQUIRED for all kinds
# Affected component; usually one of "elastic-agent", "fleet-server", "filebeat", "metricbeat", "auditbeat", "all", etc.
component: all

# AUTOMATED
# OPTIONAL to manually add other PR URLs
# PR URL: A link the PR that added the changeset.
# If not present is automatically filled by the tooling finding the PR where this changelog fragment has been added.
# NOTE: the tooling supports backports, so it's able to fill the original PR number instead of the backport PR number.
# Please provide it if you are adding a fragment for a different PR.
# pr: https://github.com/owner/repo/1234

# AUTOMATED
# OPTIONAL to manually add other issue URLs
# Issue URL; optional; the GitHub issue related to this changeset (either closes or is part of).
# If not present is automatically filled by the tooling with the issue linked to the PR number.
# issue: https://github.com/owner/repo/1234
101 changes: 101 additions & 0 deletions libbeat/outputs/lazy_sample.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package outputs

import (
"sync"

"github.com/rcrowley/go-metrics"
)

// lazySample is a uniform sample whose reservoir is only allocated on the
// first Update. A uniform sample reserves its full size up front, and a Beat
// that never reports send latency (every Beat running as an OTel receiver)
// would otherwise hold that memory for nothing.
type lazySample struct {
reservoirSize int

mu sync.Mutex
sample metrics.Sample // nil until the first Update
}

func newLazySample(reservoirSize int) *lazySample {
return &lazySample{reservoirSize: reservoirSize}
}

// get returns the backing sample, or nil if nothing was recorded yet.
func (s *lazySample) get() metrics.Sample {
s.mu.Lock()
defer s.mu.Unlock()
return s.sample
}

func (s *lazySample) Update(v int64) {
s.mu.Lock()
if s.sample == nil {
s.sample = metrics.NewUniformSample(s.reservoirSize)
}
sample := s.sample
s.mu.Unlock()
sample.Update(v)
}

func (s *lazySample) Clear() {
if sample := s.get(); sample != nil {
sample.Clear()
}
}

func (s *lazySample) Snapshot() metrics.Sample {
if sample := s.get(); sample != nil {
return sample.Snapshot()
}
return metrics.NewSampleSnapshot(0, nil)
}

func (s *lazySample) Size() int { return s.snapshot().Size() }

func (s *lazySample) Count() int64 { return s.snapshot().Count() }

func (s *lazySample) Max() int64 { return s.snapshot().Max() }

func (s *lazySample) Min() int64 { return s.snapshot().Min() }

func (s *lazySample) Sum() int64 { return s.snapshot().Sum() }

func (s *lazySample) Mean() float64 { return s.snapshot().Mean() }

func (s *lazySample) StdDev() float64 { return s.snapshot().StdDev() }

func (s *lazySample) Variance() float64 { return s.snapshot().Variance() }

func (s *lazySample) Values() []int64 { return s.snapshot().Values() }

func (s *lazySample) Percentile(p float64) float64 { return s.snapshot().Percentile(p) }

func (s *lazySample) Percentiles(ps []float64) []float64 { return s.snapshot().Percentiles(ps) }

// snapshot is the Sample the read-only accessors delegate to.
func (s *lazySample) snapshot() metrics.Sample {
if sample := s.get(); sample != nil {
return sample
}
return emptySample
}

var emptySample = metrics.NewSampleSnapshot(0, nil)
178 changes: 178 additions & 0 deletions libbeat/outputs/lazy_sample_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package outputs

import (
"maps"
"strings"
"sync"
"testing"
"time"

"github.com/rcrowley/go-metrics"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/elastic/beats/v7/pkg/logp/logptest"
"github.com/elastic/beats/v7/pkg/monitoring"
"github.com/elastic/beats/v7/pkg/monitoring/adapter"
)

func TestLazySampleEmpty(t *testing.T) {
s := newLazySample(16)

assert.Nil(t, s.get(), "reservoir must not be allocated before the first Update")
assert.Zero(t, s.Count(), "empty sample count")
assert.Zero(t, s.Size(), "empty sample size")
assert.Zero(t, s.Max(), "empty sample max")
assert.Zero(t, s.Min(), "empty sample min")
assert.Zero(t, s.Sum(), "empty sample sum")
assert.Zero(t, s.Mean(), "empty sample mean")
assert.Zero(t, s.StdDev(), "empty sample standard deviation")
assert.Zero(t, s.Variance(), "empty sample variance")
assert.Empty(t, s.Values(), "empty sample values")
assert.Equal(t, []float64{0, 0}, s.Percentiles([]float64{0.5, 0.99}), "empty sample percentiles")
assert.Zero(t, s.Percentile(0.5), "empty sample percentile")
assert.Zero(t, s.Snapshot().Count(), "empty snapshot count")

s.Clear()
assert.Nil(t, s.get(), "Clear on an empty sample must not allocate the reservoir")
}

func TestLazySampleRecords(t *testing.T) {
s := newLazySample(16)
for _, v := range []int64{1, 2, 3, 4} {
s.Update(v)
}

assert.NotNil(t, s.get(), "reservoir must exist after Update")
assert.Equal(t, int64(4), s.Count(), "count")
assert.Equal(t, int64(4), s.Max(), "max")
assert.Equal(t, int64(1), s.Min(), "min")
assert.Equal(t, int64(10), s.Sum(), "sum")
assert.InDelta(t, 2.5, s.Mean(), 0.0001, "mean")
assert.Equal(t, int64(4), s.Snapshot().Count(), "snapshot count")

s.Clear()
assert.Zero(t, s.Count(), "count after Clear")
}

// A lazy sample must report exactly what an eagerly allocated one does.
func TestLazySampleMatchesUniformSample(t *testing.T) {
lazy := newLazySample(8)
eager := metrics.NewUniformSample(8)

same := func(stage string) {
assert.Equal(t, eager.Count(), lazy.Count(), "%s: count", stage)
assert.Equal(t, eager.Size(), lazy.Size(), "%s: size", stage)
assert.Equal(t, eager.Max(), lazy.Max(), "%s: max", stage)
assert.Equal(t, eager.Min(), lazy.Min(), "%s: min", stage)
assert.Equal(t, eager.Sum(), lazy.Sum(), "%s: sum", stage)
assert.InDelta(t, eager.Mean(), lazy.Mean(), 0.0001, "%s: mean", stage)
assert.InDelta(t, eager.StdDev(), lazy.StdDev(), 0.0001, "%s: standard deviation", stage)
assert.InDelta(t, eager.Variance(), lazy.Variance(), 0.0001, "%s: variance", stage)
}

same("empty")
for _, v := range []int64{5, 1, 9, 3} { // fewer values than the reservoir, so sampling is deterministic
lazy.Update(v)
eager.Update(v)
}
same("after updates")
lazy.Clear()
eager.Clear()
same("after clear")
}

func TestLazySampleConcurrent(t *testing.T) {
s := newLazySample(64)

var wg sync.WaitGroup
for range 8 {
wg.Go(func() {
for i := range 200 {
s.Update(int64(i))
_ = s.Snapshot().Count()
_ = s.Count()
}
})
}
wg.Wait()

assert.Equal(t, int64(8*200), s.Count(), "every update must be counted")
}

// The write.latency histograms must stay in the registry, with the same keys
// and values, whether or not anything reported a latency.
func TestStatsLatencyMetricsUnchanged(t *testing.T) {
logger := logptest.NewTestingLogger(t, "")

flatten := func(reg *monitoring.Registry) map[string]float64 {
snap := monitoring.CollectFlatSnapshot(reg, monitoring.Full, false)
out := map[string]float64{}
for k, v := range snap.Ints {
out[k] = float64(v)
}
maps.Copy(out, snap.Floats)
return out
}

got := func(report bool) map[string]float64 {
reg := monitoring.NewRegistry()
stats := NewStats(reg, logger)
if report {
stats.ReportLatency(5 * time.Millisecond)
stats.ReportLatency(15 * time.Millisecond)
}
return flatten(reg)
}

// What an eagerly allocated sample would have reported.
want := func(report bool) map[string]float64 {
reg := monitoring.NewRegistry()
lifetime, delta := metrics.NewUniformSample(1024), metrics.NewUniformSample(1024)
require.NoError(t, adapter.NewGoMetrics(reg, "write.latency", logger, adapter.Accept).Register("histogram", metrics.NewHistogram(lifetime)))
require.NoError(t, adapter.NewGoMetrics(reg, "write.latency_delta", logger, adapter.Accept).Register("histogram", adapter.NewClearOnVisitHistogram(delta)))
if report {
for _, v := range []int64{5, 15} {
lifetime.Update(v)
delta.Update(v)
}
}
return flatten(reg)
}

for _, report := range []bool{false, true} {
g := got(report)
for k, v := range want(report) {
if !strings.HasPrefix(k, "write.latency") {
continue
}
assert.Contains(t, g, k, "report=%v: metric %s must still exist", report, k)
assert.InDelta(t, v, g[k], 0.0001, "report=%v: metric %s", report, k)
}
}
}

func BenchmarkNewStats(b *testing.B) {
logger := logptest.NewTestingLogger(b, "")
b.ReportAllocs()
for b.Loop() {
_ = NewStats(monitoring.NewRegistry(), logger)
}
}
4 changes: 2 additions & 2 deletions libbeat/outputs/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ func NewStats(reg *monitoring.Registry, logger *logp.Logger) *Stats {
readBytes: monitoring.NewUint(reg, "read.bytes"),
readErrors: monitoring.NewUint(reg, "read.errors"),

sendLatencyLifetimeMillis: metrics.NewUniformSample(1024),
sendLatencyDeltaMillis: metrics.NewUniformSample(1024),
sendLatencyLifetimeMillis: newLazySample(1024),
sendLatencyDeltaMillis: newLazySample(1024),
}
_ = adapter.NewGoMetrics(reg, "write.latency", logger, adapter.Accept).Register("histogram", metrics.NewHistogram(obj.sendLatencyLifetimeMillis))
_ = adapter.NewGoMetrics(reg, "write.latency_delta", logger, adapter.Accept).Register("histogram", adapter.NewClearOnVisitHistogram(obj.sendLatencyDeltaMillis))
Expand Down
Loading