summaryrefslogtreecommitdiff
path: root/vendor/jonahgeorge/jaeger-client-php/src/Jaeger/Sender/UdpSender.php
blob: ff0e4cf3edd94be453642d0d352c57baa1e6ac4a (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
<?php

namespace Jaeger\Sender;

use Exception;
use Jaeger\Thrift\Agent\AgentClient;
use Jaeger\Thrift\Agent\Zipkin\Annotation;
use Jaeger\Thrift\Agent\Zipkin\AnnotationType;
use Jaeger\Thrift\Agent\Zipkin\BinaryAnnotation;
use Jaeger\Thrift\Agent\Zipkin\Endpoint;
use Jaeger\Thrift\Agent\Zipkin\Span as ThriftSpan;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Thrift\Base\TBase;
use Thrift\Protocol\TCompactProtocol;
use Thrift\Transport\TMemoryBuffer;
use Jaeger\Span as JaegerSpan;

use const OpenTracing\Tags\COMPONENT;

class UdpSender
{
    const CLIENT_ADDR = "ca";
    const SERVER_ADDR = "sa";

    /**
     * @var JaegerSpan[]
     */
    private $spans = [];

    /**
     * @var AgentClient
     */
    private $client;

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

    /**
     * The maximum length of the thrift-objects for a zipkin-batch.
     *
     * @var int
     */
    private $maxBufferLength;

    /**
     * The length of the zipkin-batch overhead.
     *
     * @var int
     */
    private $zipkinBatchOverheadLength = 30;

    /**
     * UdpSender constructor.
     *
     * @param AgentClient          $client
     * @param int                  $maxBufferLength
     * @param LoggerInterface|null $logger
     */
    public function __construct(
        AgentClient $client,
        int $maxBufferLength,
        LoggerInterface $logger = null
    ) {
        $this->client = $client;
        $this->maxBufferLength = $maxBufferLength;
        $this->logger = $logger ?? new NullLogger();
    }

    /**
     * @param JaegerSpan $span
     */
    public function append(JaegerSpan $span)
    {
        $this->spans[] = $span;
    }

    /**
     * @return int the number of flushed spans
     */
    public function flush(): int
    {
        $count = count($this->spans);
        if ($count === 0) {
            return 0;
        }

        $zipkinSpans = $this->makeZipkinBatch($this->spans);

        try {
            $this->send($zipkinSpans);
        } catch (Exception $e) {
            $this->logger->warning($e->getMessage());
        }

        $this->spans = [];

        return $count;
    }

    public function close()
    {
    }

    /**
     * Emits the thrift-objects.
     *
     * @param array|ThriftSpan[]|TBase[] $thrifts
     */
    private function send(array $thrifts)
    {
        foreach ($this->chunkSplit($thrifts) as $chunk) {
            /* @var $chunk ThriftSpan[] */
            $this->client->emitZipkinBatch($chunk);
        }
    }

    /**
     * @param JaegerSpan[] $spans
     * @return ThriftSpan[]
     */
    private function makeZipkinBatch(array $spans): array
    {
        /** @var ThriftSpan[] */
        $zipkinSpans = [];

        foreach ($spans as $span) {
            /** @var JaegerSpan $span */

            $endpoint = $this->makeEndpoint(
                $span->getTracer()->getIpAddress(),
                0,  // span.port,
                $span->getTracer()->getServiceName()
            );

            $timestamp = $span->getStartTime();
            $duration = $span->getEndTime() - $span->getStartTime();

            $this->addZipkinAnnotations($span, $endpoint);

            $zipkinSpan = new ThriftSpan([
                'name' => $span->getOperationName(),
                'id' => $span->getContext()->getSpanId(),
                'parent_id' => $span->getContext()->getParentId() ?? null,
                'trace_id' => $span->getContext()->getTraceId(),
                'annotations' => $this->createAnnotations($span, $endpoint),
                'binary_annotations' => $span->getTags(),
                'debug' => $span->isDebug(),
                'timestamp' => $timestamp,
                'duration' => $duration,
            ]);

            $zipkinSpans[] = $zipkinSpan;
        }

        return $zipkinSpans;
    }

    private function addZipkinAnnotations(JaegerSpan $span, Endpoint $endpoint)
    {
        if ($span->isRpc() && $span->peer) {
            $isClient = $span->isRpcClient();

            $host = $this->makeEndpoint(
                $span->peer['ipv4'] ?? 0,
                $span->peer['port'] ?? 0,
                $span->peer['service_name'] ?? ''
            );

            $key = ($isClient) ? self::SERVER_ADDR : self::CLIENT_ADDR;

            $peer = $this->makePeerAddressTag($key, $host);
            $span->tags[$key] = $peer;
        } else {
            $tag = $this->makeLocalComponentTag(
                $span->getComponent() ?? $span->getTracer()->getServiceName(),
                $endpoint
            );

            $span->tags[COMPONENT] = $tag;
        }
    }

    private function makeLocalComponentTag(string $componentName, Endpoint $endpoint): BinaryAnnotation
    {
        return new BinaryAnnotation([
            'key' => "lc",
            'value' => $componentName,
            'annotation_type' => AnnotationType::STRING,
            'host' => $endpoint,
        ]);
    }

    private function makeEndpoint(string $ipv4, int $port, string $serviceName): Endpoint
    {
        $ipv4 = $this->ipv4ToInt($ipv4);

        return new Endpoint([
            'ipv4' => $ipv4,
            'port' => $port,
            'service_name' => $serviceName,
        ]);
    }

    private function ipv4ToInt(string $ipv4): int
    {
        if ($ipv4 == 'localhost') {
            $ipv4 = '127.0.0.1';
        } elseif ($ipv4 == '::1') {
            $ipv4 = '127.0.0.1';
        }

        $long = ip2long($ipv4);
        if (PHP_INT_SIZE === 8) {
            return $long >> 31 ? $long - (1 << 32) : $long;
        }
        return $long;
    }

    // Used for Zipkin binary annotations like CA/SA (client/server address).
    // They are modeled as Boolean type with '0x01' as the value.
    private function makePeerAddressTag(string $key, Endpoint $host): BinaryAnnotation
    {
        return new BinaryAnnotation([
            "key" => $key,
            "value" => '0x01',
            "annotation_type" => AnnotationType::BOOL,
            "host" => $host,
        ]);
    }

    /**
     * Splits an array of thrift-objects into several chunks when the buffer limit has been reached.
     *
     * @param array|ThriftSpan[]|TBase[] $thrifts
     *
     * @return array
     */
    private function chunkSplit(array $thrifts): array
    {
        $actualBufferSize = $this->zipkinBatchOverheadLength;
        $chunkId = 0;
        $chunks = [];

        foreach ($thrifts as $thrift) {
            $spanBufferLength = $this->getBufferLength($thrift);

            if (!empty($chunks[$chunkId]) && ($actualBufferSize + $spanBufferLength) > $this->maxBufferLength) {
                // point to next chunk
                ++$chunkId;

                // reset buffer size
                $actualBufferSize = $this->zipkinBatchOverheadLength;
            }

            if (!isset($chunks[$chunkId])) {
                $chunks[$chunkId] = [];
            }

            $chunks[$chunkId][] = $thrift;
            $actualBufferSize += $spanBufferLength;
        }

        return $chunks;
    }

    /**
     * Returns the length of a thrift-object.
     *
     * @param ThriftSpan|TBase $thrift
     *
     * @return int
     */
    private function getBufferLength($thrift): int
    {
        $memoryBuffer = new TMemoryBuffer();

        $thrift->write(new TCompactProtocol($memoryBuffer));

        return $memoryBuffer->available();
    }

    /*
     * @param JaegerSpan $span
     * @param Endpoint   $endpoint
     *
     * @return array|Annotation[]
     */
    private function createAnnotations(JaegerSpan $span, Endpoint $endpoint): array
    {
        $annotations = [];

        foreach ($span->getLogs() as $values) {
            $annotations[] = new Annotation([
                'timestamp' => $values['timestamp'],
                'value' => json_encode($values['fields']),
                'host' => $endpoint,
            ]);
        }

        return $annotations;
    }
}