config.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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/utils"
  23. "github.com/uber/jaeger-client-go"
  24. "github.com/uber/jaeger-client-go/internal/baggage/remote"
  25. throttler "github.com/uber/jaeger-client-go/internal/throttler/remote"
  26. "github.com/uber/jaeger-client-go/rpcmetrics"
  27. "github.com/uber/jaeger-client-go/transport"
  28. "github.com/uber/jaeger-lib/metrics"
  29. )
  30. const defaultSamplingProbability = 0.001
  31. // Configuration configures and creates Jaeger Tracer
  32. type Configuration struct {
  33. // ServiceName specifies the service name to use on the tracer.
  34. // Can be provided by FromEnv() via the environment variable named JAEGER_SERVICE_NAME
  35. ServiceName string `yaml:"serviceName"`
  36. // Disabled makes the config return opentracing.NoopTracer.
  37. // Value can be provided by FromEnv() via the environment variable named JAEGER_DISABLED.
  38. Disabled bool `yaml:"disabled"`
  39. // RPCMetrics enables generations of RPC metrics (requires metrics factory to be provided).
  40. // Value can be provided by FromEnv() via the environment variable named JAEGER_RPC_METRICS
  41. RPCMetrics bool `yaml:"rpc_metrics"`
  42. // Gen128Bit instructs the tracer to generate 128-bit wide trace IDs, compatible with W3C Trace Context.
  43. // Value can be provided by FromEnv() via the environment variable named JAEGER_TRACEID_128BIT.
  44. Gen128Bit bool `yaml:"traceid_128bit"`
  45. // Tags can be provided by FromEnv() via the environment variable named JAEGER_TAGS
  46. Tags []opentracing.Tag `yaml:"tags"`
  47. Sampler *SamplerConfig `yaml:"sampler"`
  48. Reporter *ReporterConfig `yaml:"reporter"`
  49. Headers *jaeger.HeadersConfig `yaml:"headers"`
  50. BaggageRestrictions *BaggageRestrictionsConfig `yaml:"baggage_restrictions"`
  51. Throttler *ThrottlerConfig `yaml:"throttler"`
  52. }
  53. // SamplerConfig allows initializing a non-default sampler. All fields are optional.
  54. type SamplerConfig struct {
  55. // Type specifies the type of the sampler: const, probabilistic, rateLimiting, or remote.
  56. // Can be provided by FromEnv() via the environment variable named JAEGER_SAMPLER_TYPE
  57. Type string `yaml:"type"`
  58. // Param is a value passed to the sampler.
  59. // Valid values for Param field are:
  60. // - for "const" sampler, 0 or 1 for always false/true respectively
  61. // - for "probabilistic" sampler, a probability between 0 and 1
  62. // - for "rateLimiting" sampler, the number of spans per second
  63. // - for "remote" sampler, param is the same as for "probabilistic"
  64. // and indicates the initial sampling rate before the actual one
  65. // is received from the mothership.
  66. // Can be provided by FromEnv() via the environment variable named JAEGER_SAMPLER_PARAM
  67. Param float64 `yaml:"param"`
  68. // SamplingServerURL is the URL of sampling manager that can provide
  69. // sampling strategy to this service.
  70. // Can be provided by FromEnv() via the environment variable named JAEGER_SAMPLING_ENDPOINT
  71. SamplingServerURL string `yaml:"samplingServerURL"`
  72. // SamplingRefreshInterval controls how often the remotely controlled sampler will poll
  73. // sampling manager for the appropriate sampling strategy.
  74. // Can be provided by FromEnv() via the environment variable named JAEGER_SAMPLER_REFRESH_INTERVAL
  75. SamplingRefreshInterval time.Duration `yaml:"samplingRefreshInterval"`
  76. // MaxOperations is the maximum number of operations that the PerOperationSampler
  77. // will keep track of. If an operation is not tracked, a default probabilistic
  78. // sampler will be used rather than the per operation specific sampler.
  79. // Can be provided by FromEnv() via the environment variable named JAEGER_SAMPLER_MAX_OPERATIONS.
  80. MaxOperations int `yaml:"maxOperations"`
  81. // Opt-in feature for applications that require late binding of span name via explicit
  82. // call to SetOperationName when using PerOperationSampler. When this feature is enabled,
  83. // the sampler will return retryable=true from OnCreateSpan(), thus leaving the sampling
  84. // decision as non-final (and the span as writeable). This may lead to degraded performance
  85. // in applications that always provide the correct span name on trace creation.
  86. //
  87. // For backwards compatibility this option is off by default.
  88. OperationNameLateBinding bool `yaml:"operationNameLateBinding"`
  89. // Options can be used to programmatically pass additional options to the Remote sampler.
  90. Options []jaeger.SamplerOption
  91. }
  92. // ReporterConfig configures the reporter. All fields are optional.
  93. type ReporterConfig struct {
  94. // QueueSize controls how many spans the reporter can keep in memory before it starts dropping
  95. // new spans. The queue is continuously drained by a background go-routine, as fast as spans
  96. // can be sent out of process.
  97. // Can be provided by FromEnv() via the environment variable named JAEGER_REPORTER_MAX_QUEUE_SIZE
  98. QueueSize int `yaml:"queueSize"`
  99. // BufferFlushInterval controls how often the buffer is force-flushed, even if it's not full.
  100. // It is generally not useful, as it only matters for very low traffic services.
  101. // Can be provided by FromEnv() via the environment variable named JAEGER_REPORTER_FLUSH_INTERVAL
  102. BufferFlushInterval time.Duration
  103. // LogSpans, when true, enables LoggingReporter that runs in parallel with the main reporter
  104. // and logs all submitted spans. Main Configuration.Logger must be initialized in the code
  105. // for this option to have any effect.
  106. // Can be provided by FromEnv() via the environment variable named JAEGER_REPORTER_LOG_SPANS
  107. LogSpans bool `yaml:"logSpans"`
  108. // LocalAgentHostPort instructs reporter to send spans to jaeger-agent at this address.
  109. // Can be provided by FromEnv() via the environment variable named JAEGER_AGENT_HOST / JAEGER_AGENT_PORT
  110. LocalAgentHostPort string `yaml:"localAgentHostPort"`
  111. // DisableAttemptReconnecting when true, disables udp connection helper that periodically re-resolves
  112. // the agent's hostname and reconnects if there was a change. This option only
  113. // applies if LocalAgentHostPort is specified.
  114. // Can be provided by FromEnv() via the environment variable named JAEGER_REPORTER_ATTEMPT_RECONNECTING_DISABLED
  115. DisableAttemptReconnecting bool `yaml:"disableAttemptReconnecting"`
  116. // AttemptReconnectInterval controls how often the agent client re-resolves the provided hostname
  117. // in order to detect address changes. This option only applies if DisableAttemptReconnecting is false.
  118. // Can be provided by FromEnv() via the environment variable named JAEGER_REPORTER_ATTEMPT_RECONNECT_INTERVAL
  119. AttemptReconnectInterval time.Duration
  120. // CollectorEndpoint instructs reporter to send spans to jaeger-collector at this URL.
  121. // Can be provided by FromEnv() via the environment variable named JAEGER_ENDPOINT
  122. CollectorEndpoint string `yaml:"collectorEndpoint"`
  123. // User instructs reporter to include a user for basic http authentication when sending spans to jaeger-collector.
  124. // Can be provided by FromEnv() via the environment variable named JAEGER_USER
  125. User string `yaml:"user"`
  126. // Password instructs reporter to include a password for basic http authentication when sending spans to
  127. // jaeger-collector.
  128. // Can be provided by FromEnv() via the environment variable named JAEGER_PASSWORD
  129. Password string `yaml:"password"`
  130. // HTTPHeaders instructs the reporter to add these headers to the http request when reporting spans.
  131. // This field takes effect only when using HTTPTransport by setting the CollectorEndpoint.
  132. HTTPHeaders map[string]string `yaml:"http_headers"`
  133. }
  134. // BaggageRestrictionsConfig configures the baggage restrictions manager which can be used to whitelist
  135. // certain baggage keys. All fields are optional.
  136. type BaggageRestrictionsConfig struct {
  137. // DenyBaggageOnInitializationFailure controls the startup failure mode of the baggage restriction
  138. // manager. If true, the manager will not allow any baggage to be written until baggage restrictions have
  139. // been retrieved from jaeger-agent. If false, the manager wil allow any baggage to be written until baggage
  140. // restrictions have been retrieved from jaeger-agent.
  141. DenyBaggageOnInitializationFailure bool `yaml:"denyBaggageOnInitializationFailure"`
  142. // HostPort is the hostPort of jaeger-agent's baggage restrictions server
  143. HostPort string `yaml:"hostPort"`
  144. // RefreshInterval controls how often the baggage restriction manager will poll
  145. // jaeger-agent for the most recent baggage restrictions.
  146. RefreshInterval time.Duration `yaml:"refreshInterval"`
  147. }
  148. // ThrottlerConfig configures the throttler which can be used to throttle the
  149. // rate at which the client may send debug requests.
  150. type ThrottlerConfig struct {
  151. // HostPort of jaeger-agent's credit server.
  152. HostPort string `yaml:"hostPort"`
  153. // RefreshInterval controls how often the throttler will poll jaeger-agent
  154. // for more throttling credits.
  155. RefreshInterval time.Duration `yaml:"refreshInterval"`
  156. // SynchronousInitialization determines whether or not the throttler should
  157. // synchronously fetch credits from the agent when an operation is seen for
  158. // the first time. This should be set to true if the client will be used by
  159. // a short lived service that needs to ensure that credits are fetched
  160. // upfront such that sampling or throttling occurs.
  161. SynchronousInitialization bool `yaml:"synchronousInitialization"`
  162. }
  163. type nullCloser struct{}
  164. func (*nullCloser) Close() error { return nil }
  165. // New creates a new Jaeger Tracer, and a closer func that can be used to flush buffers
  166. // before shutdown.
  167. //
  168. // Deprecated: use NewTracer() function
  169. func (c Configuration) New(
  170. serviceName string,
  171. options ...Option,
  172. ) (opentracing.Tracer, io.Closer, error) {
  173. if serviceName != "" {
  174. c.ServiceName = serviceName
  175. }
  176. return c.NewTracer(options...)
  177. }
  178. // NewTracer returns a new tracer based on the current configuration, using the given options,
  179. // and a closer func that can be used to flush buffers before shutdown.
  180. func (c Configuration) NewTracer(options ...Option) (opentracing.Tracer, io.Closer, error) {
  181. if c.Disabled {
  182. return &opentracing.NoopTracer{}, &nullCloser{}, nil
  183. }
  184. if c.ServiceName == "" {
  185. return nil, nil, errors.New("no service name provided")
  186. }
  187. opts := applyOptions(options...)
  188. tracerMetrics := jaeger.NewMetrics(opts.metrics, nil)
  189. if c.RPCMetrics {
  190. Observer(
  191. rpcmetrics.NewObserver(
  192. opts.metrics.Namespace(metrics.NSOptions{Name: "jaeger-rpc", Tags: map[string]string{"component": "jaeger"}}),
  193. rpcmetrics.DefaultNameNormalizer,
  194. ),
  195. )(&opts) // adds to c.observers
  196. }
  197. if c.Sampler == nil {
  198. c.Sampler = &SamplerConfig{
  199. Type: jaeger.SamplerTypeRemote,
  200. Param: defaultSamplingProbability,
  201. }
  202. }
  203. if c.Reporter == nil {
  204. c.Reporter = &ReporterConfig{}
  205. }
  206. sampler := opts.sampler
  207. if sampler == nil {
  208. s, err := c.Sampler.NewSampler(c.ServiceName, tracerMetrics)
  209. if err != nil {
  210. return nil, nil, err
  211. }
  212. sampler = s
  213. }
  214. reporter := opts.reporter
  215. if reporter == nil {
  216. r, err := c.Reporter.NewReporter(c.ServiceName, tracerMetrics, opts.logger)
  217. if err != nil {
  218. return nil, nil, err
  219. }
  220. reporter = r
  221. }
  222. tracerOptions := []jaeger.TracerOption{
  223. jaeger.TracerOptions.Metrics(tracerMetrics),
  224. jaeger.TracerOptions.Logger(opts.logger),
  225. jaeger.TracerOptions.CustomHeaderKeys(c.Headers),
  226. jaeger.TracerOptions.PoolSpans(opts.poolSpans),
  227. jaeger.TracerOptions.ZipkinSharedRPCSpan(opts.zipkinSharedRPCSpan),
  228. jaeger.TracerOptions.MaxTagValueLength(opts.maxTagValueLength),
  229. jaeger.TracerOptions.NoDebugFlagOnForcedSampling(opts.noDebugFlagOnForcedSampling),
  230. }
  231. if c.Gen128Bit || opts.gen128Bit {
  232. tracerOptions = append(tracerOptions, jaeger.TracerOptions.Gen128Bit(true))
  233. }
  234. if opts.randomNumber != nil {
  235. tracerOptions = append(tracerOptions, jaeger.TracerOptions.RandomNumber(opts.randomNumber))
  236. }
  237. for _, tag := range opts.tags {
  238. tracerOptions = append(tracerOptions, jaeger.TracerOptions.Tag(tag.Key, tag.Value))
  239. }
  240. for _, tag := range c.Tags {
  241. tracerOptions = append(tracerOptions, jaeger.TracerOptions.Tag(tag.Key, tag.Value))
  242. }
  243. for _, obs := range opts.observers {
  244. tracerOptions = append(tracerOptions, jaeger.TracerOptions.Observer(obs))
  245. }
  246. for _, cobs := range opts.contribObservers {
  247. tracerOptions = append(tracerOptions, jaeger.TracerOptions.ContribObserver(cobs))
  248. }
  249. for format, injector := range opts.injectors {
  250. tracerOptions = append(tracerOptions, jaeger.TracerOptions.Injector(format, injector))
  251. }
  252. for format, extractor := range opts.extractors {
  253. tracerOptions = append(tracerOptions, jaeger.TracerOptions.Extractor(format, extractor))
  254. }
  255. if c.BaggageRestrictions != nil {
  256. mgr := remote.NewRestrictionManager(
  257. c.ServiceName,
  258. remote.Options.Metrics(tracerMetrics),
  259. remote.Options.Logger(opts.logger),
  260. remote.Options.HostPort(c.BaggageRestrictions.HostPort),
  261. remote.Options.RefreshInterval(c.BaggageRestrictions.RefreshInterval),
  262. remote.Options.DenyBaggageOnInitializationFailure(
  263. c.BaggageRestrictions.DenyBaggageOnInitializationFailure,
  264. ),
  265. )
  266. tracerOptions = append(tracerOptions, jaeger.TracerOptions.BaggageRestrictionManager(mgr))
  267. }
  268. if c.Throttler != nil {
  269. debugThrottler := throttler.NewThrottler(
  270. c.ServiceName,
  271. throttler.Options.Metrics(tracerMetrics),
  272. throttler.Options.Logger(opts.logger),
  273. throttler.Options.HostPort(c.Throttler.HostPort),
  274. throttler.Options.RefreshInterval(c.Throttler.RefreshInterval),
  275. throttler.Options.SynchronousInitialization(
  276. c.Throttler.SynchronousInitialization,
  277. ),
  278. )
  279. tracerOptions = append(tracerOptions, jaeger.TracerOptions.DebugThrottler(debugThrottler))
  280. }
  281. tracer, closer := jaeger.NewTracer(
  282. c.ServiceName,
  283. sampler,
  284. reporter,
  285. tracerOptions...,
  286. )
  287. return tracer, closer, nil
  288. }
  289. // InitGlobalTracer creates a new Jaeger Tracer, and sets it as global OpenTracing Tracer.
  290. // It returns a closer func that can be used to flush buffers before shutdown.
  291. func (c Configuration) InitGlobalTracer(
  292. serviceName string,
  293. options ...Option,
  294. ) (io.Closer, error) {
  295. if c.Disabled {
  296. return &nullCloser{}, nil
  297. }
  298. tracer, closer, err := c.New(serviceName, options...)
  299. if err != nil {
  300. return nil, err
  301. }
  302. opentracing.SetGlobalTracer(tracer)
  303. return closer, nil
  304. }
  305. // NewSampler creates a new sampler based on the configuration
  306. func (sc *SamplerConfig) NewSampler(
  307. serviceName string,
  308. metrics *jaeger.Metrics,
  309. ) (jaeger.Sampler, error) {
  310. samplerType := strings.ToLower(sc.Type)
  311. if samplerType == jaeger.SamplerTypeConst {
  312. return jaeger.NewConstSampler(sc.Param != 0), nil
  313. }
  314. if samplerType == jaeger.SamplerTypeProbabilistic {
  315. if sc.Param >= 0 && sc.Param <= 1.0 {
  316. return jaeger.NewProbabilisticSampler(sc.Param)
  317. }
  318. return nil, fmt.Errorf(
  319. "invalid Param for probabilistic sampler; expecting value between 0 and 1, received %v",
  320. sc.Param,
  321. )
  322. }
  323. if samplerType == jaeger.SamplerTypeRateLimiting {
  324. return jaeger.NewRateLimitingSampler(sc.Param), nil
  325. }
  326. if samplerType == jaeger.SamplerTypeRemote || sc.Type == "" {
  327. sc2 := *sc
  328. sc2.Type = jaeger.SamplerTypeProbabilistic
  329. initSampler, err := sc2.NewSampler(serviceName, nil)
  330. if err != nil {
  331. return nil, err
  332. }
  333. options := []jaeger.SamplerOption{
  334. jaeger.SamplerOptions.Metrics(metrics),
  335. jaeger.SamplerOptions.InitialSampler(initSampler),
  336. jaeger.SamplerOptions.SamplingServerURL(sc.SamplingServerURL),
  337. jaeger.SamplerOptions.MaxOperations(sc.MaxOperations),
  338. jaeger.SamplerOptions.OperationNameLateBinding(sc.OperationNameLateBinding),
  339. jaeger.SamplerOptions.SamplingRefreshInterval(sc.SamplingRefreshInterval),
  340. }
  341. options = append(options, sc.Options...)
  342. return jaeger.NewRemotelyControlledSampler(serviceName, options...), nil
  343. }
  344. return nil, fmt.Errorf("unknown sampler type (%s)", sc.Type)
  345. }
  346. // NewReporter instantiates a new reporter that submits spans to the collector
  347. func (rc *ReporterConfig) NewReporter(
  348. serviceName string,
  349. metrics *jaeger.Metrics,
  350. logger jaeger.Logger,
  351. ) (jaeger.Reporter, error) {
  352. sender, err := rc.newTransport(logger)
  353. if err != nil {
  354. return nil, err
  355. }
  356. reporter := jaeger.NewRemoteReporter(
  357. sender,
  358. jaeger.ReporterOptions.QueueSize(rc.QueueSize),
  359. jaeger.ReporterOptions.BufferFlushInterval(rc.BufferFlushInterval),
  360. jaeger.ReporterOptions.Logger(logger),
  361. jaeger.ReporterOptions.Metrics(metrics))
  362. if rc.LogSpans && logger != nil {
  363. logger.Infof("Initializing logging reporter")
  364. reporter = jaeger.NewCompositeReporter(jaeger.NewLoggingReporter(logger), reporter)
  365. }
  366. return reporter, err
  367. }
  368. func (rc *ReporterConfig) newTransport(logger jaeger.Logger) (jaeger.Transport, error) {
  369. switch {
  370. case rc.CollectorEndpoint != "":
  371. httpOptions := []transport.HTTPOption{transport.HTTPHeaders(rc.HTTPHeaders)}
  372. if rc.User != "" && rc.Password != "" {
  373. httpOptions = append(httpOptions, transport.HTTPBasicAuth(rc.User, rc.Password))
  374. }
  375. return transport.NewHTTPTransport(rc.CollectorEndpoint, httpOptions...), nil
  376. default:
  377. return jaeger.NewUDPTransportWithParams(jaeger.UDPTransportParams{
  378. AgentClientUDPParams: utils.AgentClientUDPParams{
  379. HostPort: rc.LocalAgentHostPort,
  380. Logger: logger,
  381. DisableAttemptReconnecting: rc.DisableAttemptReconnecting,
  382. AttemptReconnectInterval: rc.AttemptReconnectInterval,
  383. },
  384. })
  385. }
  386. }