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
Expand Up @@ -2610,15 +2610,14 @@ var _ = Describe("Container Store", func() {

err = containerStore.Initialize(logger, runReq)
Expect(err).NotTo(HaveOccurred())

_, err = containerStore.Create(logger, "some-trace-id", containerGuid)
Expect(err).NotTo(HaveOccurred())
})

Context("when the container exists", func() {
JustBeforeEach(func() {
_, err := containerStore.Create(logger, "some-trace-id", containerGuid)
Expect(err).NotTo(HaveOccurred())

err := containerStore.Run(logger, "some-trace-id", containerGuid)
err = containerStore.Run(logger, "some-trace-id", containerGuid)
Expect(err).NotTo(HaveOccurred())
})

Expand Down Expand Up @@ -2810,6 +2809,79 @@ var _ = Describe("Container Store", func() {

})

Context("when the container has been created but not yet run", func() {
BeforeEach(func() {
updateReq.InternalRoutes = nil
})

JustBeforeEach(func() {
_, err := containerStore.Create(logger, "some-trace-id", containerGuid)
Expect(err).NotTo(HaveOccurred())
})

It("does not panic and the log streamer picks up the new tags on Run", func() {
Expect(func() {
err := containerStore.Update(logger, updateReq)
Expect(err).NotTo(HaveOccurred())
}).NotTo(Panic())

Expect(logStreamer.UpdateTagsCallCount()).To(Equal(0))
Expect(gardenContainer.SetPropertyCallCount()).To(Equal(1))

err := containerStore.Run(logger, "some-trace-id", containerGuid)
Expect(err).NotTo(HaveOccurred())

Expect(logManager.NewLogStreamerCallCount()).To(Equal(1))
logConfig, _, _, _, _ := logManager.NewLogStreamerArgsForCall(0)
Expect(logConfig.Tags).To(Equal(metricTags))
})
})

Context("when the container has been initialized but not yet created", func() {
BeforeEach(func() {
updateReq.InternalRoutes = nil
})

It("does not panic and the container is created with the new tags in its log config", func() {
Expect(func() {
err := containerStore.Update(logger, updateReq)
Expect(err).NotTo(HaveOccurred())
}).NotTo(Panic())

Expect(logStreamer.UpdateTagsCallCount()).To(Equal(0))
Expect(gardenContainer.SetPropertyCallCount()).To(Equal(0))

_, err := containerStore.Create(logger, "some-trace-id", containerGuid)
Expect(err).NotTo(HaveOccurred())

Expect(gardenClient.CreateCallCount()).To(Equal(1))
containerSpec := gardenClient.CreateArgsForCall(0)
var logConfig models.LogConfig
Expect(json.Unmarshal([]byte(containerSpec.Properties["log_config"]), &logConfig)).To(Succeed())
Expect(logConfig.Tags).To(Equal(metricTags))
})
})

Context("when the container has been reserved but not yet initialized", func() {
BeforeEach(func() {
updateReq.Guid = "reserved-guid"
updateReq.InternalRoutes = nil
})

It("does not panic", func() {
_, err := containerStore.Reserve(logger, "some-trace-id", &executor.AllocationRequest{Guid: "reserved-guid"})
Expect(err).NotTo(HaveOccurred())

Expect(func() {
err := containerStore.Update(logger, updateReq)
Expect(err).NotTo(HaveOccurred())
}).NotTo(Panic())

Expect(logStreamer.UpdateTagsCallCount()).To(Equal(0))
Expect(gardenContainer.SetPropertyCallCount()).To(Equal(0))
})
})

Context("when the container does not exist", func() {
It("returns an ErrContainerNotFound", func() {
updateReq.Guid = "unknown-guid"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -750,12 +750,18 @@ func (n *storeNode) Update(logger lager.Logger, req *executor.UpdateRequest) err
}

if req.MetricTags != nil {
n.logStreamer.UpdateTags(req.MetricTags)
// logStreamer is only set once the container runs and gardenContainer once
// it is created; earlier states pick up n.info.LogConfig when they get there.
if n.logStreamer != nil {
n.logStreamer.UpdateTags(req.MetricTags)
}

err := n.gardenContainer.SetProperty("log_config", string(logConfigJSON))
if err != nil {
logger.Error("failed-to-set-log-config-property", err, lager.Data{"guid": req.Guid})
return err
if n.gardenContainer != nil {
err := n.gardenContainer.SetProperty("log_config", string(logConfigJSON))
if err != nil {
logger.Error("failed-to-set-log-config-property", err, lager.Data{"guid": req.Guid})
return err
}
}
}
return nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ type logRateLimiter struct {
logMetricsEmitInterval time.Duration
lastOverage time.Time
bytesEmittedLastInterval uint64
tags map[string]string
tags *tagStore
}

func NewLogRateLimiter(
Expand All @@ -40,6 +40,17 @@ func NewLogRateLimiter(
maxLogLinesPerSecond int,
maxLogBytesPerSecond int64,
logMetricsEmitInterval time.Duration,
) *logRateLimiter {
return newLogRateLimiter(ctx, metronClient, newTagStore(tags), maxLogLinesPerSecond, maxLogBytesPerSecond, logMetricsEmitInterval)
}

func newLogRateLimiter(
ctx context.Context,
metronClient loggingclient.IngressClient,
tags *tagStore,
maxLogLinesPerSecond int,
maxLogBytesPerSecond int64,
logMetricsEmitInterval time.Duration,
) *logRateLimiter {
limiter := &logRateLimiter{
ctx: ctx,
Expand Down Expand Up @@ -106,7 +117,7 @@ func (r *logRateLimiter) emitMetrics() {
lastIntervalEmitted := atomic.SwapUint64(&r.bytesEmittedLastInterval, 0)
perSecondValue := float64(lastIntervalEmitted) / intervalDivider
// #nosec G104 - ignore error returned by sending metric here
r.metronClient.SendAppLogRate(perSecondValue, float64(r.maxLogBytesPerSecond), r.tags)
r.metronClient.SendAppLogRate(perSecondValue, float64(r.maxLogBytesPerSecond), r.tags.Load())
case <-r.ctx.Done():
return
}
Expand All @@ -123,5 +134,5 @@ func (r *logRateLimiter) reportLogRateLimitExceededMetric() {
}

func (r *logRateLimiter) reportLogRateLimitExceededLog(sourceName string, reportMessage string) {
_ = r.metronClient.SendAppLog(reportMessage, sourceName, r.tags)
_ = r.metronClient.SendAppLog(reportMessage, sourceName, r.tags.Load())
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ type LogStreamer interface {
type logStreamer struct {
ctx context.Context
cancelFunc context.CancelFunc
tags *tagStore
stdout *streamDestination
stderr *streamDestination
}
Expand All @@ -42,14 +43,16 @@ func New(config models.LogConfig, metronClient loggingclient.IngressClient, maxL
return noopStreamer{}
}

sourceName, tags := config.GetSourceNameAndTagsForLogging()
sourceName, tagMap := config.GetSourceNameAndTagsForLogging()
tags := newTagStore(tagMap)

ctx, cancelFunc := context.WithCancel(context.Background())
logRateLimiter := NewLogRateLimiter(ctx, metronClient, tags, maxLogLinesPerSecond, maxLogBytesPerSecond, metricReportInterval)
logRateLimiter := newLogRateLimiter(ctx, metronClient, tags, maxLogLinesPerSecond, maxLogBytesPerSecond, metricReportInterval)

return &logStreamer{
ctx: ctx,
cancelFunc: cancelFunc,
tags: tags,
stdout: newStreamDestination(
ctx,
sourceName,
Expand Down Expand Up @@ -79,8 +82,7 @@ func (e *logStreamer) Stderr() io.Writer {
}

func (e *logStreamer) UpdateTags(tags map[string]string) {
e.stdout.updateTags(tags)
e.stderr.updateTags(tags)
e.tags.Store(tags)
}

func (e *logStreamer) Flush() {
Expand All @@ -98,6 +100,7 @@ func (e *logStreamer) WithSource(sourceName string) LogStreamer {
return &logStreamer{
ctx: ctx,
cancelFunc: cancelFunc,
tags: e.tags,
stdout: e.stdout.withSource(ctx, sourceName),
stderr: e.stderr.withSource(ctx, sourceName),
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package log_streamer_test

import (
"fmt"
"io"
"runtime"
"strings"
"sync"
Expand All @@ -10,6 +11,8 @@ import (
"code.cloudfoundry.org/bbs/models"
mfakes "code.cloudfoundry.org/diego-logging-client/testhelpers"
"code.cloudfoundry.org/executor/depot/log_streamer"
loggregator "code.cloudfoundry.org/go-loggregator/v9"
"code.cloudfoundry.org/go-loggregator/v9/rpc/loggregator_v2"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/types"
Expand Down Expand Up @@ -738,6 +741,51 @@ var _ = Describe("LogStreamer", func() {
})
})

Context("when tags are updated while stdout, stderr, child streamers and log rate metrics are emitting", func() {
var tagReadingClient tagReadingIngressClient

BeforeEach(func() {
tagReadingClient = tagReadingIngressClient{FakeIngressClient: fakeClient}
streamer = log_streamer.New(logConfig, tagReadingClient, maxLogLinesPerSecond, maxLogBytesPerSecond, time.Millisecond)
})

AfterEach(func() {
streamer.Stop()
})

It("does not trigger data races on the shared tags", func() {
child := streamer.WithSource("CELL")
writers := []io.Writer{streamer.Stdout(), streamer.Stderr(), child.Stdout(), child.Stderr()}

wg := new(sync.WaitGroup)
for _, w := range writers {
wg.Add(1)
go func(w io.Writer) {
defer GinkgoRecover()
defer wg.Done()
for i := 0; i < 1000; i++ {
_, _ = fmt.Fprintln(w, "this is a log")
}
}(w)
}

wg.Add(1)
go func() {
defer GinkgoRecover()
defer wg.Done()
for i := 0; i < 1000; i++ {
streamer.UpdateTags(map[string]string{"source_id": guid, "instance_id": "11", "iteration": fmt.Sprint(i)})
}
}()
wg.Wait()

streamer.UpdateTags(map[string]string{"final": "tags"})
_, _ = fmt.Fprintln(child.Stdout(), "this is a log")
_, _, tags := fakeClient.SendAppLogArgsForCall(fakeClient.SendAppLogCallCount() - 1)
Expect(tags).To(Equal(map[string]string{"final": "tags"}))
})
})

})

Describe("Stop", func() {
Expand Down Expand Up @@ -794,3 +842,31 @@ var _ = Describe("LogStreamer", func() {
})
})
})

// tagReadingIngressClient reads the tags map the same way the real
// diego-logging-client/go-loggregator do (index lookups plus
// WithEnvelopeTags iteration), so the race detector can see concurrent
// access. The counterfeiter fake alone only stores the map reference.
type tagReadingIngressClient struct {
*mfakes.FakeIngressClient
}

func readTags(tags map[string]string) {
_ = tags["source_id"]
loggregator.WithEnvelopeTags(tags)(&loggregator_v2.Envelope{Tags: map[string]string{}})
}

func (c tagReadingIngressClient) SendAppLog(message, sourceName string, tags map[string]string) error {
readTags(tags)
return c.FakeIngressClient.SendAppLog(message, sourceName, tags)
}

func (c tagReadingIngressClient) SendAppErrorLog(message, sourceName string, tags map[string]string) error {
readTags(tags)
return c.FakeIngressClient.SendAppErrorLog(message, sourceName, tags)
}

func (c tagReadingIngressClient) SendAppLogRate(rate, rateLimit float64, tags map[string]string) error {
readTags(tags)
return c.FakeIngressClient.SendAppLogRate(rate, rateLimit, tags)
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
type streamDestination struct {
ctx context.Context
sourceName string
tags map[string]string
tags *tagStore
messageType loggregator_v2.Log_Type
buffer []byte
processLock sync.Mutex
Expand All @@ -23,7 +23,7 @@ type streamDestination struct {
func newStreamDestination(
ctx context.Context,
sourceName string,
tags map[string]string,
tags *tagStore,
messageType loggregator_v2.Log_Type,
metronClient loggingclient.IngressClient,
limiter *logRateLimiter,
Expand All @@ -39,19 +39,6 @@ func newStreamDestination(
}
}

func (destination *streamDestination) updateTags(tags map[string]string) {
destination.processLock.Lock()
defer destination.processLock.Unlock()

for k := range destination.tags {
delete(destination.tags, k)
}

for k, v := range tags {
destination.tags[k] = v
}
}

func (destination *streamDestination) lockAndFlush() {
destination.processLock.Lock()
defer destination.processLock.Unlock()
Expand All @@ -70,11 +57,12 @@ func (destination *streamDestination) flush() {
if destination.logRateLimiter.Limit(destination.sourceName, len(msg)) != nil {
return
}
tags := destination.tags.Load()
switch destination.messageType {
case loggregator_v2.Log_OUT:
_ = destination.metronClient.SendAppLog(string(msg), destination.sourceName, destination.tags)
_ = destination.metronClient.SendAppLog(string(msg), destination.sourceName, tags)
case loggregator_v2.Log_ERR:
_ = destination.metronClient.SendAppErrorLog(string(msg), destination.sourceName, destination.tags)
_ = destination.metronClient.SendAppErrorLog(string(msg), destination.sourceName, tags)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package log_streamer

import "sync/atomic"

// tagStore holds the tags shared by every streamDestination (stdout, stderr
// and all WithSource children) and the logRateLimiter of a single container.
// Each of those has its own lock (or none), so the map must never be mutated
// in place: Store swaps in a fresh copy and readers get an immutable snapshot.
type tagStore struct {
tags atomic.Pointer[map[string]string]
}

func newTagStore(tags map[string]string) *tagStore {
s := &tagStore{}
s.Store(tags)
return s
}

// Load returns a snapshot that must not be modified.
func (s *tagStore) Load() map[string]string {
return *s.tags.Load()
}

func (s *tagStore) Store(tags map[string]string) {
snapshot := make(map[string]string, len(tags))
for k, v := range tags {
snapshot[k] = v
}
s.tags.Store(&snapshot)
}
Loading
Loading