config.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // Copyright (c) 2017-2018 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 config
  15. import (
  16. "errors"
  17. "fmt"
  18. "io"
  19. "strings"
  20. "time"
  21. "github.com/opentracing/opentracing-go"
  22. "github.com/uber/jaeger-client-go"
  23. "github.com/uber/jaeger-client-go/internal/baggage/remote"
  24. throttler "github.com/uber/jaeger-client-go/internal/throttler/remote"
  25. "github.com/uber/jaeger-client-go/rpcmetrics"
  26. )
  27. const defaultSamplingProbability = 0.001
  28. // Configuration configures and creates Jaeger Tracer
  29. type Configuration struct {
  30. // ServiceName specifies the service name to use on the tracer.
  31. // Can be provided via environment variable named JAEGER_SERVICE_NAME
  32. ServiceName string `yaml:"serviceName"`
  33. // Disabled can be provided via environment variable named JAEGER_DISABLED
  34. Disabled bool `yaml:"disabled"`
  35. // RPCMetrics can be provided via environment variable named JAEGER_RPC_METRICS
  36. RPCMetrics bool `yaml:"rpc_metrics"`
  37. // Tags can be provided via environment variable named JAEGER_TAGS
  38. Tags []opentracing.Tag `yaml:"tags"`
  39. Sampler *SamplerConfig `yaml:"sampler"`
  40. Reporter *ReporterConfig `yaml:"reporter"`
  41. Headers *jaeger.HeadersConfig `yaml:"headers"`
  42. BaggageRestrictions *BaggageRestrictionsConfig `yaml:"baggage_restrictions"`
  43. Throttler *ThrottlerConfig `yaml:"throttler"`
  44. }
  45. // SamplerConfig allows initializing a non-default sampler. All fields are optional.
  46. type SamplerConfig struct {
  47. // Type specifies the type of the sampler: const, probabilistic, rateLimiting, or remote
  48. // Can be set by exporting an environment variable named JAEGER_SAMPLER_TYPE
  49. Type string `yaml:"type"`
  50. // Param is a value passed to the sampler.
  51. // Valid values for Param field are:
  52. // - for "const" sampler, 0 or 1 for always false/true respectively
  53. // - for "probabilistic" sampler, a probability between 0 and 1
  54. // - for "rateLimiting" sampler, the number of spans per second
  55. // - for "remote" sampler, param is the same as for "probabilistic"
  56. // and indicates the initial sampling rate before the actual one
  57. // is received from the mothership.
  58. // Can be set by exporting an environment variable named JAEGER_SAMPLER_PARAM
  59. Param float64 `yaml:"param"`
  60. // SamplingServerURL is the address of jaeger-agent's HTTP sampling server
  61. // Can be set by exporting an environment variable named JAEGER_SAMPLER_MANAGER_HOST_PORT
  62. SamplingServerURL string `yaml:"samplingServerURL"`
  63. // MaxOperations is the maximum number of operations that the sampler
  64. // will keep track of. If an operation is not tracked, a default probabilistic
  65. // sampler will be used rather than the per operation specific sampler.
  66. // Can be set by exporting an environment variable named JAEGER_SAMPLER_MAX_OPERATIONS
  67. MaxOperations int `yaml:"maxOperations"`
  68. // SamplingRefreshInterval controls how often the remotely controlled sampler will poll
  69. // jaeger-agent for the appropriate sampling strategy.
  70. // Can be set by exporting an environment variable named JAEGER_SAMPLER_REFRESH_INTERVAL
  71. SamplingRefreshInterval time.Duration `yaml:"samplingRefreshInterval"`
  72. }
  73. // ReporterConfig configures the reporter. All fields are optional.
  74. type ReporterConfig struct {
  75. // QueueSize controls how many spans the reporter can keep in memory before it starts dropping
  76. // new spans. The queue is continuously drained by a background go-routine, as fast as spans
  77. // can be sent out of process.
  78. // Can be set by exporting an environment variable named JAEGER_REPORTER_MAX_QUEUE_SIZE
  79. QueueSize int `yaml:"queueSize"`
  80. // BufferFlushInterval controls how often the buffer is force-flushed, even if it's not full.
  81. // It is generally not useful, as it only matters for very low traffic services.
  82. // Can be set by exporting an environment variable named JAEGER_REPORTER_FLUSH_INTERVAL
  83. BufferFlushInterval time.Duration
  84. // LogSpans, when true, enables LoggingReporter that runs in parallel with the main reporter
  85. // and logs all submitted spans. Main Configuration.Logger must be initialized in the code
  86. // for this option to have any effect.
  87. // Can be set by exporting an environment variable named JAEGER_REPORTER_LOG_SPANS
  88. LogSpans bool `yaml:"logSpans"`
  89. // LocalAgentHostPort instructs reporter to send spans to jaeger-agent at this address
  90. // Can be set by exporting an environment variable named JAEGER_AGENT_HOST / JAEGER_AGENT_PORT
  91. LocalAgentHostPort string `yaml:"localAgentHostPort"`
  92. }
  93. // BaggageRestrictionsConfig configures the baggage restrictions manager which can be used to whitelist
  94. // certain baggage keys. All fields are optional.
  95. type BaggageRestrictionsConfig struct {
  96. // DenyBaggageOnInitializationFailure controls the startup failure mode of the baggage restriction
  97. // manager. If true, the manager will not allow any baggage to be written until baggage restrictions have
  98. // been retrieved from jaeger-agent. If false, the manager wil allow any baggage to be written until baggage
  99. // restrictions have been retrieved from jaeger-agent.
  100. DenyBaggageOnInitializationFailure bool `yaml:"denyBaggageOnInitializationFailure"`
  101. // HostPort is the hostPort of jaeger-agent's baggage restrictions server
  102. HostPort string `yaml:"hostPort"`
  103. // RefreshInterval controls how often the baggage restriction manager will poll
  104. // jaeger-agent for the most recent baggage restrictions.
  105. RefreshInterval time.Duration `yaml:"refreshInterval"`
  106. }
  107. // ThrottlerConfig configures the throttler which can be used to throttle the
  108. // rate at which the client may send debug requests.
  109. type ThrottlerConfig struct {
  110. // HostPort of jaeger-agent's credit server.
  111. HostPort string `yaml:"hostPort"`
  112. // RefreshInterval controls how often the throttler will poll jaeger-agent
  113. // for more throttling credits.
  114. RefreshInterval time.Duration `yaml:"refreshInterval"`
  115. // SynchronousInitialization determines whether or not the throttler should
  116. // synchronously fetch credits from the agent when an operation is seen for
  117. // the first time. This should be set to true if the client will be used by
  118. // a short lived service that needs to ensure that credits are fetched
  119. // upfront such that sampling or throttling occurs.
  120. SynchronousInitialization bool `yaml:"synchronousInitialization"`
  121. }
  122. type nullCloser struct{}
  123. func (*nullCloser) Close() error { return nil }
  124. // New creates a new Jaeger Tracer, and a closer func that can be used to flush buffers
  125. // before shutdown.
  126. //
  127. // Deprecated: use NewTracer() function
  128. func (c Configuration) New(
  129. serviceName string,
  130. options ...Option,
  131. ) (opentracing.Tracer, io.Closer, error) {
  132. if serviceName != "" {
  133. c.ServiceName = serviceName
  134. }
  135. return c.NewTracer(options...)
  136. }
  137. // NewTracer returns a new tracer based on the current configuration, using the given options,
  138. // and a closer func that can be used to flush buffers before shutdown.
  139. func (c Configuration) NewTracer(options ...Option) (opentracing.Tracer, io.Closer, error) {
  140. if c.ServiceName == "" {
  141. return nil, nil, errors.New("no service name provided")
  142. }
  143. if c.Disabled {
  144. return &opentracing.NoopTracer{}, &nullCloser{}, nil
  145. }
  146. opts := applyOptions(options...)
  147. tracerMetrics := jaeger.NewMetrics(opts.metrics, nil)
  148. if c.RPCMetrics {
  149. Observer(
  150. rpcmetrics.NewObserver(
  151. opts.metrics.Namespace("jaeger-rpc", map[string]string{"component": "jaeger"}),
  152. rpcmetrics.DefaultNameNormalizer,
  153. ),
  154. )(&opts) // adds to c.observers
  155. }
  156. if c.Sampler == nil {
  157. c.Sampler = &SamplerConfig{
  158. Type: jaeger.SamplerTypeRemote,
  159. Param: defaultSamplingProbability,
  160. }
  161. }
  162. if c.Reporter == nil {
  163. c.Reporter = &ReporterConfig{}
  164. }
  165. sampler := opts.sampler
  166. if sampler == nil {
  167. s, err := c.Sampler.NewSampler(c.ServiceName, tracerMetrics)
  168. if err != nil {
  169. return nil, nil, err
  170. }
  171. sampler = s
  172. }
  173. reporter := opts.reporter
  174. if reporter == nil {
  175. r, err := c.Reporter.NewReporter(c.ServiceName, tracerMetrics, opts.logger)
  176. if err != nil {
  177. return nil, nil, err
  178. }
  179. reporter = r
  180. }
  181. tracerOptions := []jaeger.TracerOption{
  182. jaeger.TracerOptions.Metrics(tracerMetrics),
  183. jaeger.TracerOptions.Logger(opts.logger),
  184. jaeger.TracerOptions.CustomHeaderKeys(c.Headers),
  185. jaeger.TracerOptions.Gen128Bit(opts.gen128Bit),
  186. jaeger.TracerOptions.ZipkinSharedRPCSpan(opts.zipkinSharedRPCSpan),
  187. jaeger.TracerOptions.MaxTagValueLength(opts.maxTagValueLength),
  188. }
  189. for _, tag := range opts.tags {
  190. tracerOptions = append(tracerOptions, jaeger.TracerOptions.Tag(tag.Key, tag.Value))
  191. }
  192. for _, tag := range c.Tags {
  193. tracerOptions = append(tracerOptions, jaeger.TracerOptions.Tag(tag.Key, tag.Value))
  194. }
  195. for _, obs := range opts.observers {
  196. tracerOptions = append(tracerOptions, jaeger.TracerOptions.Observer(obs))
  197. }
  198. for _, cobs := range opts.contribObservers {
  199. tracerOptions = append(tracerOptions, jaeger.TracerOptions.ContribObserver(cobs))
  200. }
  201. for format, injector := range opts.injectors {
  202. tracerOptions = append(tracerOptions, jaeger.TracerOptions.Injector(format, injector))
  203. }
  204. for format, extractor := range opts.extractors {
  205. tracerOptions = append(tracerOptions, jaeger.TracerOptions.Extractor(format, extractor))
  206. }
  207. if c.BaggageRestrictions != nil {
  208. mgr := remote.NewRestrictionManager(
  209. c.ServiceName,
  210. remote.Options.Metrics(tracerMetrics),
  211. remote.Options.Logger(opts.logger),
  212. remote.Options.HostPort(c.BaggageRestrictions.HostPort),
  213. remote.Options.RefreshInterval(c.BaggageRestrictions.RefreshInterval),
  214. remote.Options.DenyBaggageOnInitializationFailure(
  215. c.BaggageRestrictions.DenyBaggageOnInitializationFailure,
  216. ),
  217. )
  218. tracerOptions = append(tracerOptions, jaeger.TracerOptions.BaggageRestrictionManager(mgr))
  219. }
  220. if c.Throttler != nil {
  221. debugThrottler := throttler.NewThrottler(
  222. c.ServiceName,
  223. throttler.Options.Metrics(tracerMetrics),
  224. throttler.Options.Logger(opts.logger),
  225. throttler.Options.HostPort(c.Throttler.HostPort),
  226. throttler.Options.RefreshInterval(c.Throttler.RefreshInterval),
  227. throttler.Options.SynchronousInitialization(
  228. c.Throttler.SynchronousInitialization,
  229. ),
  230. )
  231. tracerOptions = append(tracerOptions, jaeger.TracerOptions.DebugThrottler(debugThrottler))
  232. }
  233. tracer, closer := jaeger.NewTracer(
  234. c.ServiceName,
  235. sampler,
  236. reporter,
  237. tracerOptions...,
  238. )
  239. return tracer, closer, nil
  240. }
  241. // InitGlobalTracer creates a new Jaeger Tracer, and sets it as global OpenTracing Tracer.
  242. // It returns a closer func that can be used to flush buffers before shutdown.
  243. func (c Configuration) InitGlobalTracer(
  244. serviceName string,
  245. options ...Option,
  246. ) (io.Closer, error) {
  247. if c.Disabled {
  248. return &nullCloser{}, nil
  249. }
  250. tracer, closer, err := c.New(serviceName, options...)
  251. if err != nil {
  252. return nil, err
  253. }
  254. opentracing.SetGlobalTracer(tracer)
  255. return closer, nil
  256. }
  257. // NewSampler creates a new sampler based on the configuration
  258. func (sc *SamplerConfig) NewSampler(
  259. serviceName string,
  260. metrics *jaeger.Metrics,
  261. ) (jaeger.Sampler, error) {
  262. samplerType := strings.ToLower(sc.Type)
  263. if samplerType == jaeger.SamplerTypeConst {
  264. return jaeger.NewConstSampler(sc.Param != 0), nil
  265. }
  266. if samplerType == jaeger.SamplerTypeProbabilistic {
  267. if sc.Param >= 0 && sc.Param <= 1.0 {
  268. return jaeger.NewProbabilisticSampler(sc.Param)
  269. }
  270. return nil, fmt.Errorf(
  271. "Invalid Param for probabilistic sampler: %v. Expecting value between 0 and 1",
  272. sc.Param,
  273. )
  274. }
  275. if samplerType == jaeger.SamplerTypeRateLimiting {
  276. return jaeger.NewRateLimitingSampler(sc.Param), nil
  277. }
  278. if samplerType == jaeger.SamplerTypeRemote || sc.Type == "" {
  279. sc2 := *sc
  280. sc2.Type = jaeger.SamplerTypeProbabilistic
  281. initSampler, err := sc2.NewSampler(serviceName, nil)
  282. if err != nil {
  283. return nil, err
  284. }
  285. options := []jaeger.SamplerOption{
  286. jaeger.SamplerOptions.Metrics(metrics),
  287. jaeger.SamplerOptions.InitialSampler(initSampler),
  288. jaeger.SamplerOptions.SamplingServerURL(sc.SamplingServerURL),
  289. }
  290. if sc.MaxOperations != 0 {
  291. options = append(options, jaeger.SamplerOptions.MaxOperations(sc.MaxOperations))
  292. }
  293. if sc.SamplingRefreshInterval != 0 {
  294. options = append(options, jaeger.SamplerOptions.SamplingRefreshInterval(sc.SamplingRefreshInterval))
  295. }
  296. return jaeger.NewRemotelyControlledSampler(serviceName, options...), nil
  297. }
  298. return nil, fmt.Errorf("Unknown sampler type %v", sc.Type)
  299. }
  300. // NewReporter instantiates a new reporter that submits spans to tcollector
  301. func (rc *ReporterConfig) NewReporter(
  302. serviceName string,
  303. metrics *jaeger.Metrics,
  304. logger jaeger.Logger,
  305. ) (jaeger.Reporter, error) {
  306. sender, err := rc.newTransport()
  307. if err != nil {
  308. return nil, err
  309. }
  310. reporter := jaeger.NewRemoteReporter(
  311. sender,
  312. jaeger.ReporterOptions.QueueSize(rc.QueueSize),
  313. jaeger.ReporterOptions.BufferFlushInterval(rc.BufferFlushInterval),
  314. jaeger.ReporterOptions.Logger(logger),
  315. jaeger.ReporterOptions.Metrics(metrics))
  316. if rc.LogSpans && logger != nil {
  317. logger.Infof("Initializing logging reporter\n")
  318. reporter = jaeger.NewCompositeReporter(jaeger.NewLoggingReporter(logger), reporter)
  319. }
  320. return reporter, err
  321. }
  322. func (rc *ReporterConfig) newTransport() (jaeger.Transport, error) {
  323. return jaeger.NewUDPTransport(rc.LocalAgentHostPort, 0)
  324. }