config.go 15 KB

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