summaryrefslogtreecommitdiff
path: root/vendor/jonahgeorge/jaeger-client-php/src/Jaeger/Config.php
blob: 28fb972da9d721f4219237f7e022354b924b9836 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
<?php

namespace Jaeger;

use Exception;
use Jaeger\Reporter\CompositeReporter;
use Jaeger\Reporter\LoggingReporter;
use Jaeger\Reporter\ReporterInterface;
use Jaeger\ReporterFactory\JaegerHttpReporterFactory;
use Jaeger\ReporterFactory\JaegerReporterFactory;
use Jaeger\ReporterFactory\ZipkinReporterFactory;
use Jaeger\Sampler\ConstSampler;
use Jaeger\Sampler\ProbabilisticSampler;
use Jaeger\Sampler\RateLimitingSampler;
use Jaeger\Sampler\SamplerInterface;
use Jaeger\Util\RateLimiter;
use OpenTracing\GlobalTracer;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

class Config
{
    const IP_VERSION = "ip_version";

    const ZIPKIN_OVER_COMPACT_UDP   = "zipkin_over_compact_udp";
    const JAEGER_OVER_BINARY_UDP    = "jaeger_over_binary_udp";
    const JAEGER_OVER_BINARY_HTTP   = "jaeger_over_binary_http";

    const IPV6 = "IPv6";
    const IPV4 = "IPv4";

    /**
     * @return string[]
     */
    public static function getAvailableDispatchModes()
    {
        return [self::ZIPKIN_OVER_COMPACT_UDP, self::JAEGER_OVER_BINARY_UDP, self::JAEGER_OVER_BINARY_HTTP];
    }

    /**
     * @var array
     */
    private $config;

    /**
     * @var string
     */
    private $serviceName;

    /**
     * @var bool
     */
    private $initialized = false;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @return LoggerInterface
     */
    public function getLogger()
    {
        return $this->logger;
    }

    /**
     * @var CacheItemPoolInterface
     */
    private $cache;

    /**
     * Config constructor.
     * @param array $config
     * @param string|null $serviceName
     * @param LoggerInterface|null $logger
     * @param CacheItemPoolInterface|null $cache
     * @throws Exception
     */
    public function __construct(
        array $config,
        string $serviceName = null,
        LoggerInterface $logger = null,
        CacheItemPoolInterface $cache = null
    ) {
        $this->config = $config;

        $this->setConfigFromEnv();

        if (empty($this->config["dispatch_mode"])) {
            $this->config["dispatch_mode"] = self::ZIPKIN_OVER_COMPACT_UDP;
        }

        if (empty($this->config[Config::IP_VERSION])) {
            $this->config[Config::IP_VERSION] = self::IPV4;
        }

        $this->serviceName = $this->config['service_name'] ?? $serviceName;

        if ($this->serviceName === null) {
            throw new Exception('service_name required in the config or param.');
        }

        $this->logger = $logger ?: new NullLogger();
        $this->cache = $cache;
    }

    /**
     * @return Tracer|null
     * @throws Exception
     */
    public function initializeTracer()
    {
        if ($this->initialized) {
            $this->logger->warning('Jaeger tracer already initialized, skipping');
            return null;
        }

        $reporter = $this->getReporter();
        $sampler = $this->getSampler();


        $tracer = $this->createTracer($reporter, $sampler);

        $this->initializeGlobalTracer($tracer);

        return $tracer;
    }

    /**
     * @param ReporterInterface $reporter
     * @param SamplerInterface $sampler
     * @return Tracer
     */
    public function createTracer(ReporterInterface $reporter, SamplerInterface $sampler): Tracer
    {
        return new Tracer(
            $this->serviceName,
            $reporter,
            $sampler,
            $this->shouldUseOneSpanPerRpc(),
            $this->logger,
            null,
            $this->getTraceIdHeader(),
            $this->getBaggageHeaderPrefix(),
            $this->getDebugIdHeaderKey(),
            $this->getConfiguredTags()
        );
    }

    /**
     * @return string
     */
    public function getServiceName(): string
    {
        return $this->serviceName;
    }

    /**
     * @param Tracer $tracer
     */
    private function initializeGlobalTracer(Tracer $tracer)
    {
        GlobalTracer::set($tracer);
        $this->logger->debug('OpenTracing\GlobalTracer initialized to ' . $tracer->getServiceName());
    }

    /**
     * @return bool
     */
    private function getLogging(): bool
    {
        return (bool)($this->config['logging'] ?? false);
    }

    /**
     * @return ReporterInterface
     */
    private function getReporter(): ReporterInterface
    {
        switch ($this->config["dispatch_mode"]) {
            case self::JAEGER_OVER_BINARY_UDP:
                $reporter = (new JaegerReporterFactory($this))->createReporter();
                break;
            case self::ZIPKIN_OVER_COMPACT_UDP:
                $reporter = (new ZipkinReporterFactory($this))->createReporter();
                break;
            case self::JAEGER_OVER_BINARY_HTTP:
                $reporter = (new JaegerHttpReporterFactory($this))->createReporter();
                break;
            default:
                throw new \RuntimeException(
                    sprintf(
                        "Unsupported `dispatch_mode` value: %s. Allowed values are: %s",
                        $this->config["dispatch_mode"],
                        implode(", ", Config::getAvailableDispatchModes())
                    )
                );
        }

        if ($this->getLogging()) {
            $reporter = new CompositeReporter($reporter, new LoggingReporter($this->logger));
        }

        return $reporter;
    }

    /**
     * @return SamplerInterface
     * @throws \Psr\Cache\InvalidArgumentException
     * @throws Exception
     */
    private function getSampler(): SamplerInterface
    {
        $samplerConfig = $this->config['sampler'] ?? [];
        $samplerType = $samplerConfig['type'] ?? null;
        $samplerParam = $samplerConfig['param'] ?? null;

        if ($samplerType === null || $samplerType === SAMPLER_TYPE_REMOTE) {
            // todo: implement remote sampling
            return new ProbabilisticSampler((float)$samplerParam);
        } elseif ($samplerType === SAMPLER_TYPE_CONST) {
            return new ConstSampler($samplerParam ?? false);
        } elseif ($samplerType === SAMPLER_TYPE_PROBABILISTIC) {
            return new ProbabilisticSampler((float)$samplerParam);
        } elseif ($samplerType === SAMPLER_TYPE_RATE_LIMITING) {
            if (!$this->cache) {
                throw new Exception('You cannot use RateLimitingSampler without cache component');
            }
            $cacheConfig = $samplerConfig['cache'] ?? [];
            return new RateLimitingSampler(
                $samplerParam ?? 0,
                new RateLimiter(
                    $this->cache,
                    $cacheConfig['currentBalanceKey'] ?? 'rate.currentBalance',
                    $cacheConfig['lastTickKey'] ?? 'rate.lastTick'
                )
            );
        }
        throw new Exception('Unknown sampler type ' . $samplerType);
    }

    /**
     * The UDP max buffer length.
     *
     * @return int
     */
    public function getMaxBufferLength(): int
    {
        return (int)($this->config['max_buffer_length'] ?? 64000);
    }

    /**
     * @return string
     */
    public function getLocalAgentReportingHost(): string
    {
        return $this->getLocalAgentGroup()['reporting_host'] ?? DEFAULT_REPORTING_HOST;
    }

    /**
     * @return int
     */
    public function getLocalAgentReportingPort(): int
    {
        $port = $this->getLocalAgentGroup()['reporting_port'] ?? null;
        if (empty($this->getLocalAgentGroup()['reporting_port'])) {
            switch ($this->config['dispatch_mode']) {
                case self::JAEGER_OVER_BINARY_UDP:
                    $port = DEFAULT_JAEGER_UDP_BINARY_REPORTING_PORT;
                    break;
                case self::JAEGER_OVER_BINARY_HTTP:
                    $port = DEFAULT_JAEGER_HTTP_BINARY_REPORTING_PORT;
                    break;
                default:
                    $port = DEFAULT_ZIPKIN_UDP_COMPACT_REPORTING_PORT;
            }
        }
        return (int)$port;
    }

    /**
     * @return array
     */
    private function getLocalAgentGroup(): array
    {
        return $this->config['local_agent'] ?? [];
    }

    /**
     * @return string
     */
    private function getTraceIdHeader(): string
    {
        return $this->config['trace_id_header'] ?? TRACE_ID_HEADER;
    }

    /**
     * @return string
     */
    private function getBaggageHeaderPrefix(): string
    {
        return $this->config['baggage_header_prefix'] ?? BAGGAGE_HEADER_PREFIX;
    }

    /**
     * @return string
     */
    private function getDebugIdHeaderKey(): string
    {
        return $this->config['debug_id_header_key'] ?? DEBUG_ID_HEADER_KEY;
    }

    /**
     * Get a list of user-defined tags to be added to each span created by the tracer initialized by this config.
     * @return string[]
     */
    private function getConfiguredTags(): array
    {
        return $this->config['tags'] ?? [];
    }

    /**
     * Whether to follow the Zipkin model of using one span per RPC,
     * as opposed to the model of using separate spans on the RPC client and server.
     * Defaults to true.
     *
     * @return bool
     */
    private function shouldUseOneSpanPerRpc(): bool
    {
        return $this->config['one_span_per_rpc'] ?? true;
    }

    public function ipProtocolVersion(): string
    {
        return $this->config[self::IP_VERSION] ?? self::IPV4;
    }

    /**
     * Sets values from env vars into config props, unless ones has been already set.
     */
    private function setConfigFromEnv()
    {
        // general
        if (isset($_ENV['JAEGER_SERVICE_NAME']) && !isset($this->config['service_name'])) {
            $this->config['service_name'] = $_ENV['JAEGER_SERVICE_NAME'];
        }

        if (isset($_ENV['JAEGER_TAGS']) && !isset($this->config["tags"])) {
            $this->config['tags'] = $_ENV['JAEGER_TAGS'];
        }

        if (isset($_ENV['JAEGER_DISPATCH_MODE']) && !isset($this->config['dispatch_mode'])) {
            $this->config['dispatch_mode'] = $_ENV['JAEGER_DISPATCH_MODE'];
        }

        // reporting
        if (isset($_ENV['JAEGER_AGENT_HOST']) && !isset($this->config['local_agent']['reporting_host'])) {
            $this->config['local_agent']['reporting_host'] = $_ENV['JAEGER_AGENT_HOST'];
        }

        if (isset($_ENV['JAEGER_AGENT_PORT']) && !isset($this->config['local_agent']['reporting_port'])) {
            $this->config['local_agent']['reporting_port'] = intval($_ENV['JAEGER_AGENT_PORT']);
        }

        if (isset($_ENV['JAEGER_REPORTER_LOG_SPANS']) && !isset($this->config['logging'])) {
            $this->config['logging'] = filter_var($_ENV['JAEGER_REPORTER_LOG_SPANS'], FILTER_VALIDATE_BOOLEAN);
        }

        if (isset($_ENV['JAEGER_REPORTER_MAX_QUEUE_SIZE']) && !isset($this->config['max_buffer_length'])) {
            $this->config['max_buffer_length'] = intval($_ENV['JAEGER_REPORTER_MAX_QUEUE_SIZE']);
        }

        // sampling
        if (isset($_ENV['JAEGER_SAMPLER_TYPE']) && !isset($this->config['sampler']['type'])) {
            $this->config['sampler']['type'] = $_ENV['JAEGER_SAMPLER_TYPE'];
        }

        if (isset($_ENV['JAEGER_SAMPLER_PARAM']) && !isset($this->config['sampler']['param'])) {
            $this->config['sampler']['param'] = $_ENV['JAEGER_SAMPLER_PARAM'];
        }

        if (isset($_ENV['IP_VERSION']) && !isset($this->config[Config::IP_VERSION])) {
            $this->config[Config::IP_VERSION] = $_ENV['IP_VERSION'];
        }
    }
}