baggage_setter.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright (c) 2017 Uber Technologies, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jaeger
  15. import (
  16. "github.com/opentracing/opentracing-go/log"
  17. "github.com/uber/jaeger-client-go/internal/baggage"
  18. )
  19. // baggageSetter is an actor that can set a baggage value on a Span given certain
  20. // restrictions (eg. maxValueLength).
  21. type baggageSetter struct {
  22. restrictionManager baggage.RestrictionManager
  23. metrics *Metrics
  24. }
  25. func newBaggageSetter(restrictionManager baggage.RestrictionManager, metrics *Metrics) *baggageSetter {
  26. return &baggageSetter{
  27. restrictionManager: restrictionManager,
  28. metrics: metrics,
  29. }
  30. }
  31. // (NB) span should hold the lock before making this call
  32. func (s *baggageSetter) setBaggage(span *Span, key, value string) {
  33. var truncated bool
  34. var prevItem string
  35. restriction := s.restrictionManager.GetRestriction(span.serviceName(), key)
  36. if !restriction.KeyAllowed() {
  37. s.logFields(span, key, value, prevItem, truncated, restriction.KeyAllowed())
  38. s.metrics.BaggageUpdateFailure.Inc(1)
  39. return
  40. }
  41. if len(value) > restriction.MaxValueLength() {
  42. truncated = true
  43. value = value[:restriction.MaxValueLength()]
  44. s.metrics.BaggageTruncate.Inc(1)
  45. }
  46. prevItem = span.context.baggage[key]
  47. s.logFields(span, key, value, prevItem, truncated, restriction.KeyAllowed())
  48. span.context = span.context.WithBaggageItem(key, value)
  49. s.metrics.BaggageUpdateSuccess.Inc(1)
  50. }
  51. func (s *baggageSetter) logFields(span *Span, key, value, prevItem string, truncated, valid bool) {
  52. if !span.context.IsSampled() {
  53. return
  54. }
  55. fields := []log.Field{
  56. log.String("event", "baggage"),
  57. log.String("key", key),
  58. log.String("value", value),
  59. }
  60. if prevItem != "" {
  61. fields = append(fields, log.String("override", "true"))
  62. }
  63. if truncated {
  64. fields = append(fields, log.String("truncated", "true"))
  65. }
  66. if !valid {
  67. fields = append(fields, log.String("invalid", "true"))
  68. }
  69. span.logFieldsNoLocking(fields...)
  70. }