Skip to content

Commit

Permalink
[extension/jaegerremotesampling] Support reload_interval option in re…
Browse files Browse the repository at this point in the history
…mote mode of usage (open-telemetry#24981)

Updates the jaegerremotesampling extension's `remote` mode of usage to
support the `reload_interval` caching option already supported in `file`
mode of usage.

Co-authored-by: Anthony Mirabella <[email protected]>
  • Loading branch information
zcross and Aneurysm9 committed Aug 14, 2023
1 parent 6ebf905 commit bba1b43
Show file tree
Hide file tree
Showing 9 changed files with 499 additions and 25 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Use this changelog template to create an entry for release notes.
# If your change doesn't affect end users, such as a test fix or a tooling change,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: extension/jaegerremotesampling

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: gRPC remote source usage in jaegerremotesampling extension supports optional caching via existing `reload_interval` config

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [24840]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:
3 changes: 2 additions & 1 deletion extension/jaegerremotesampling/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Note that the port `14250` will clash with the Jaeger Receiver. When both are us

Although this extension is derived from Jaeger, it can be used by any clients who can consume this standard, such as the [OpenTelemetry Java SDK](https://github.com/open-telemetry/opentelemetry-java/tree/v1.9.1/sdk-extensions/jaeger-remote-sampler).

At this moment, the `reload_interval` option is only effective for the `file` source. In the future, this property will be used to control a local cache for a `remote` source.
The `reload_interval` option is used to poll a file when using the `file` source. It is used to control a local cache for a `remote` source.

The `file` source can be used to load files from the local file system or from remote HTTP/S sources. The `remote` source must be used with a gRPC server that provides a Jaeger remote sampling service.

Expand All @@ -34,6 +34,7 @@ The `file` source can be used to load files from the local file system or from r
extensions:
jaegerremotesampling:
source:
reload_interval: 30s
remote:
endpoint: jaeger-collector:14250
jaegerremotesampling/1:
Expand Down
8 changes: 7 additions & 1 deletion extension/jaegerremotesampling/extension.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,13 @@ func (jrse *jrsExtension) Start(ctx context.Context, host component.Host) error
return fmt.Errorf("failed to create the remote strategy store: %w", err)
}
jrse.closers = append(jrse.closers, conn.Close)
jrse.samplingStore = internal.NewRemoteStrategyStore(conn, jrse.cfg.Source.Remote)
remoteStore, closer := internal.NewRemoteStrategyStore(
conn,
jrse.cfg.Source.Remote,
jrse.cfg.Source.ReloadInterval,
)
jrse.closers = append(jrse.closers, closer.Close)
jrse.samplingStore = remoteStore
}

if jrse.cfg.HTTPServerSettings != nil {
Expand Down
58 changes: 39 additions & 19 deletions extension/jaegerremotesampling/extension_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net/http"
"path/filepath"
"testing"
"time"

"github.com/jaegertracing/jaeger/proto-gen/api_v2"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -45,24 +46,39 @@ func TestStartAndShutdownLocalFile(t *testing.T) {
assert.NoError(t, e.Shutdown(context.Background()))
}

func TestStartAndCallAndShutdownRemote(t *testing.T) {
func TestRemote(t *testing.T) {
for _, tc := range []struct {
name string
remoteClientHeaderConfig map[string]configopaque.String
name string
remoteClientHeaderConfig map[string]configopaque.String
performedClientCallCount int
expectedOutboundGrpcCallCount int
reloadInterval time.Duration
}{
{
name: "no configured header additions",
name: "no configured header additions and no configured reload_interval",
performedClientCallCount: 3,
expectedOutboundGrpcCallCount: 3,
},
{
name: "configured header additions",
name: "configured header additions",
performedClientCallCount: 3,
expectedOutboundGrpcCallCount: 3,
remoteClientHeaderConfig: map[string]configopaque.String{
"testheadername": "testheadervalue",
"anotherheadername": "anotherheadervalue",
},
},
{
name: "reload_interval set to nonzero value caching outbound same-service gRPC calls",
reloadInterval: time.Minute * 5,
performedClientCallCount: 3,
expectedOutboundGrpcCallCount: 1,
remoteClientHeaderConfig: map[string]configopaque.String{
"somecoolheader": "some-more-coverage-whynot",
},
},
} {
t.Run(tc.name, func(t *testing.T) {

// prepare the socket the mock server will listen at
lis, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
Expand All @@ -82,6 +98,7 @@ func TestStartAndCallAndShutdownRemote(t *testing.T) {
// create the config, pointing to the mock server
cfg := testConfig()
cfg.GRPCServerSettings.NetAddr.Endpoint = "127.0.0.1:0"
cfg.Source.ReloadInterval = tc.reloadInterval
cfg.Source.Remote = &configgrpc.GRPCClientSettings{
Endpoint: fmt.Sprintf("127.0.0.1:%d", lis.Addr().(*net.TCPAddr).Port),
TLSSetting: configtls.TLSClientSetting{
Expand All @@ -98,24 +115,27 @@ func TestStartAndCallAndShutdownRemote(t *testing.T) {
// start the server
assert.NoError(t, e.Start(context.Background(), componenttest.NewNopHost()))

// make a call
resp, err := http.Get("https://127.0.0.1:5778/sampling?service=foo")
assert.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
// make test case defined number of calls
for i := 0; i < tc.performedClientCallCount; i++ {
resp, err := http.Get("https://127.0.0.1:5778/sampling?service=foo")
assert.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
}

// shut down the server
assert.NoError(t, e.Shutdown(context.Background()))

// verify observed calls
assert.Len(t, mockServer.observedCalls, 1)
singleCall := mockServer.observedCalls[0]
assert.Equal(t, &api_v2.SamplingStrategyParameters{
ServiceName: "foo",
}, singleCall.params)
md, ok := metadata.FromIncomingContext(singleCall.ctx)
assert.True(t, ok)
for expectedHeaderName, expectedHeaderValue := range tc.remoteClientHeaderConfig {
assert.Equal(t, []string{string(expectedHeaderValue)}, md.Get(expectedHeaderName))
assert.Len(t, mockServer.observedCalls, tc.expectedOutboundGrpcCallCount)
for _, singleCall := range mockServer.observedCalls {
assert.Equal(t, &api_v2.SamplingStrategyParameters{
ServiceName: "foo",
}, singleCall.params)
md, ok := metadata.FromIncomingContext(singleCall.ctx)
assert.True(t, ok)
for expectedHeaderName, expectedHeaderValue := range tc.remoteClientHeaderConfig {
assert.Equal(t, []string{string(expectedHeaderValue)}, md.Get(expectedHeaderName))
}
}
})
}
Expand Down
2 changes: 2 additions & 0 deletions extension/jaegerremotesampling/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ module github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaege
go 1.20

require (
github.com/fortytw2/leaktest v1.3.0
github.com/jaegertracing/jaeger v1.41.0
github.com/stretchr/testify v1.8.4
github.com/tilinna/clock v1.1.0
go.opentelemetry.io/collector/component v0.82.0
go.opentelemetry.io/collector/config/configgrpc v0.82.0
go.opentelemetry.io/collector/config/confighttp v0.82.0
Expand Down
4 changes: 4 additions & 0 deletions extension/jaegerremotesampling/go.sum

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

136 changes: 136 additions & 0 deletions extension/jaegerremotesampling/internal/remote_strategy_cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package internal // import "github.com/open-telemetry/opentelemetry-collector-contrib/extension/jaegerremotesampling/internal"

import (
"context"
"sync"
"time"

"github.com/jaegertracing/jaeger/thrift-gen/sampling"
"github.com/tilinna/clock"
)

type serviceStrategyCache interface {
get(ctx context.Context, serviceName string) (*sampling.SamplingStrategyResponse, bool)
put(ctx context.Context, serviceName string, response *sampling.SamplingStrategyResponse)
Close() error
}

// serviceStrategyCacheEntry is a timestamped sampling strategy response
type serviceStrategyCacheEntry struct {
retrievedAt time.Time
strategyResponse *sampling.SamplingStrategyResponse
}

// serviceStrategyTTLCache is a naive in-memory TTL serviceStrategyTTLCache of service-specific sampling strategies
// returned from the remote source. Each cached item has its own TTL used to determine whether it is valid for read
// usage (based on the time of write).
type serviceStrategyTTLCache struct {
itemTTL time.Duration

stopCh chan struct{}
rw sync.RWMutex
items map[string]serviceStrategyCacheEntry
}

// Initial size of cache's underlying map
const initialRemoteResponseCacheSize = 32

func newServiceStrategyCache(itemTTL time.Duration) serviceStrategyCache {
result := &serviceStrategyTTLCache{
itemTTL: itemTTL,
items: make(map[string]serviceStrategyCacheEntry, initialRemoteResponseCacheSize),
stopCh: make(chan struct{}),
}

// Launches a "cleaner" goroutine that naively blows away stale items with a frequency equal to the item TTL.
// Note that this is for memory usage and not for correctness (the get() function checks item validity).
go result.periodicallyClearCache(context.Background(), itemTTL)
return result
}

// get returns a cached sampling strategy if one is present and is no older than the serviceStrategyTTLCache's per-item TTL.
func (c *serviceStrategyTTLCache) get(
ctx context.Context,
serviceName string,
) (*sampling.SamplingStrategyResponse, bool) {
c.rw.RLock()
defer c.rw.RUnlock()
found, ok := c.items[serviceName]
if !ok {
return nil, false
}
if c.staleItem(ctx, found) {
return nil, false
}
return found.strategyResponse, true
}

// put unconditionally overwrites the given service's serviceStrategyTTLCache item entry and resets its timestamp used for TTL checks.
func (c *serviceStrategyTTLCache) put(
ctx context.Context,
serviceName string,
response *sampling.SamplingStrategyResponse,
) {
c.rw.Lock()
defer c.rw.Unlock()
c.items[serviceName] = serviceStrategyCacheEntry{
strategyResponse: response,
retrievedAt: clock.Now(ctx),
}
}

// periodicallyClearCache periodically clears expired items from the cache and replaces the backing map with only
// valid (fresh) items. Note that this is not necessary for correctness, just preferred for memory usage hygiene.
// Client request activity drives the replacement of stale items with fresh items upon cache misses for any service.
func (c *serviceStrategyTTLCache) periodicallyClearCache(
ctx context.Context,
schedulingPeriod time.Duration,
) {
ticker := clock.NewTicker(ctx, schedulingPeriod)
for {
select {
case <-ticker.C:
c.rw.Lock()
newItems := make(map[string]serviceStrategyCacheEntry, initialRemoteResponseCacheSize)
for serviceName, item := range c.items {
if !c.staleItem(ctx, item) {
newItems[serviceName] = item
}
}
// Notice that we swap the map rather than using map's delete (which doesn't reduce its allocated size).
c.items = newItems
c.rw.Unlock()
case <-c.stopCh:
return
}
}
}

func (c *serviceStrategyTTLCache) Close() error {
close(c.stopCh)
return nil
}

func (c *serviceStrategyTTLCache) staleItem(ctx context.Context, item serviceStrategyCacheEntry) bool {
return clock.Now(ctx).After(item.retrievedAt.Add(c.itemTTL))
}

type noopStrategyCache struct{}

func (n *noopStrategyCache) get(_ context.Context, _ string) (*sampling.SamplingStrategyResponse, bool) {
return nil, false
}

func (n *noopStrategyCache) put(_ context.Context, _ string, _ *sampling.SamplingStrategyResponse) {
}

func (n *noopStrategyCache) Close() error {
return nil
}

func newNoopStrategyCache() serviceStrategyCache {
return &noopStrategyCache{}
}
Loading

0 comments on commit bba1b43

Please sign in to comment.