diff --git a/src/code.cloudfoundry.org/executor/depot/containerstore/containerstore_test.go b/src/code.cloudfoundry.org/executor/depot/containerstore/containerstore_test.go index c077b56d91..5b4a254d4b 100644 --- a/src/code.cloudfoundry.org/executor/depot/containerstore/containerstore_test.go +++ b/src/code.cloudfoundry.org/executor/depot/containerstore/containerstore_test.go @@ -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()) }) @@ -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" diff --git a/src/code.cloudfoundry.org/executor/depot/containerstore/storenode.go b/src/code.cloudfoundry.org/executor/depot/containerstore/storenode.go index a39e8f972e..68a85f638a 100644 --- a/src/code.cloudfoundry.org/executor/depot/containerstore/storenode.go +++ b/src/code.cloudfoundry.org/executor/depot/containerstore/storenode.go @@ -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 diff --git a/src/code.cloudfoundry.org/executor/depot/log_streamer/log_rate_limiter.go b/src/code.cloudfoundry.org/executor/depot/log_streamer/log_rate_limiter.go index 1465f62c6e..70da0857e7 100644 --- a/src/code.cloudfoundry.org/executor/depot/log_streamer/log_rate_limiter.go +++ b/src/code.cloudfoundry.org/executor/depot/log_streamer/log_rate_limiter.go @@ -30,7 +30,7 @@ type logRateLimiter struct { logMetricsEmitInterval time.Duration lastOverage time.Time bytesEmittedLastInterval uint64 - tags map[string]string + tags *tagStore } func NewLogRateLimiter( @@ -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, @@ -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 } @@ -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()) } diff --git a/src/code.cloudfoundry.org/executor/depot/log_streamer/log_streamer.go b/src/code.cloudfoundry.org/executor/depot/log_streamer/log_streamer.go index 252b095efb..807e6a9401 100644 --- a/src/code.cloudfoundry.org/executor/depot/log_streamer/log_streamer.go +++ b/src/code.cloudfoundry.org/executor/depot/log_streamer/log_streamer.go @@ -33,6 +33,7 @@ type LogStreamer interface { type logStreamer struct { ctx context.Context cancelFunc context.CancelFunc + tags *tagStore stdout *streamDestination stderr *streamDestination } @@ -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, @@ -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() { @@ -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), } diff --git a/src/code.cloudfoundry.org/executor/depot/log_streamer/log_streamer_test.go b/src/code.cloudfoundry.org/executor/depot/log_streamer/log_streamer_test.go index 19c1a1b84c..b20a117945 100644 --- a/src/code.cloudfoundry.org/executor/depot/log_streamer/log_streamer_test.go +++ b/src/code.cloudfoundry.org/executor/depot/log_streamer/log_streamer_test.go @@ -2,6 +2,7 @@ package log_streamer_test import ( "fmt" + "io" "runtime" "strings" "sync" @@ -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" @@ -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() { @@ -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) +} diff --git a/src/code.cloudfoundry.org/executor/depot/log_streamer/stream_destination.go b/src/code.cloudfoundry.org/executor/depot/log_streamer/stream_destination.go index 396cd95bd5..e560f411d7 100644 --- a/src/code.cloudfoundry.org/executor/depot/log_streamer/stream_destination.go +++ b/src/code.cloudfoundry.org/executor/depot/log_streamer/stream_destination.go @@ -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 @@ -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, @@ -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() @@ -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) } } } diff --git a/src/code.cloudfoundry.org/executor/depot/log_streamer/tag_store.go b/src/code.cloudfoundry.org/executor/depot/log_streamer/tag_store.go new file mode 100644 index 0000000000..c349cc61be --- /dev/null +++ b/src/code.cloudfoundry.org/executor/depot/log_streamer/tag_store.go @@ -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) +} diff --git a/src/code.cloudfoundry.org/executor/depot/log_streamer/tag_store_test.go b/src/code.cloudfoundry.org/executor/depot/log_streamer/tag_store_test.go new file mode 100644 index 0000000000..c319ac81ff --- /dev/null +++ b/src/code.cloudfoundry.org/executor/depot/log_streamer/tag_store_test.go @@ -0,0 +1,56 @@ +package log_streamer + +import ( + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("tagStore", func() { + It("returns the stored tags", func() { + store := newTagStore(map[string]string{"app_name": "some-app"}) + Expect(store.Load()).To(Equal(map[string]string{"app_name": "some-app"})) + + store.Store(map[string]string{"app_name": "other-app"}) + Expect(store.Load()).To(Equal(map[string]string{"app_name": "other-app"})) + }) + + Context("when nil is stored", func() { + It("returns an empty map", func() { + store := newTagStore(nil) + Expect(store.Load()).NotTo(BeNil()) + Expect(store.Load()).To(BeEmpty()) + + store = newTagStore(map[string]string{"app_name": "some-app"}) + store.Store(nil) + Expect(store.Load()).NotTo(BeNil()) + Expect(store.Load()).To(BeEmpty()) + }) + }) + + Context("when the caller modifies its map after storing it", func() { + It("does not affect the stored tags", func() { + tags := map[string]string{"app_name": "some-app"} + store := newTagStore(tags) + tags["app_name"] = "modified" + tags["extra"] = "value" + Expect(store.Load()).To(Equal(map[string]string{"app_name": "some-app"})) + + tags = map[string]string{"app_name": "other-app"} + store.Store(tags) + delete(tags, "app_name") + Expect(store.Load()).To(Equal(map[string]string{"app_name": "other-app"})) + }) + }) + + Context("when new tags are stored", func() { + It("does not modify a previously loaded snapshot", func() { + store := newTagStore(map[string]string{"app_name": "some-app"}) + snapshot := store.Load() + + store.Store(map[string]string{"app_name": "other-app"}) + + Expect(snapshot).To(Equal(map[string]string{"app_name": "some-app"})) + Expect(store.Load()).To(Equal(map[string]string{"app_name": "other-app"})) + }) + }) +})