-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpanConverter.php
301 lines (242 loc) · 10.2 KB
/
SpanConverter.php
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
<?php
declare(strict_types=1);
namespace OpenTelemetry\Contrib\Zipkin;
use function max;
use OpenTelemetry\API\Common\Time\ClockInterface;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\Contrib\Zipkin\SpanKind as ZipkinSpanKind;
use OpenTelemetry\SDK\Resource\ResourceInfoFactory;
use OpenTelemetry\SDK\Trace\EventInterface;
use OpenTelemetry\SDK\Trace\SpanConverterInterface;
use OpenTelemetry\SDK\Trace\SpanDataInterface;
use OpenTelemetry\SemConv\ResourceAttributes;
class SpanConverter implements SpanConverterInterface
{
const STATUS_CODE_TAG_KEY = 'otel.status_code';
const STATUS_DESCRIPTION_TAG_KEY = 'error';
const KEY_INSTRUMENTATION_SCOPE_NAME = 'otel.scope.name';
const KEY_INSTRUMENTATION_SCOPE_VERSION = 'otel.scope.version';
const KEY_DROPPED_ATTRIBUTES_COUNT = 'otel.dropped_attributes_count';
const KEY_DROPPED_EVENTS_COUNT = 'otel.dropped_events_count';
const KEY_DROPPED_LINKS_COUNT = 'otel.dropped_links_count';
public const NANOS_PER_MICROSECOND = 1_000;
const REMOTE_ENDPOINT_PREFERRED_ATTRIBUTE_TO_RANK_MAP = [
'peer.service' => 1,
'net.peer.name' => 2,
'net.peer.ip' => 3,
'peer.hostname' => 4,
'peer.address' => 5,
'http.host' => 6,
'db.name' => 7,
];
const NET_PEER_IP_KEY = 'net.peer.ip';
private readonly string $defaultServiceName;
public function __construct()
{
$this->defaultServiceName = ResourceInfoFactory::defaultResource()->getAttributes()->get(ResourceAttributes::SERVICE_NAME);
}
/** @psalm-pure */
public static function nanosToMicros(int $nanoseconds): int
{
return intdiv($nanoseconds, ClockInterface::NANOS_PER_MICROSECOND);
}
private function sanitiseTagValue($value): string
{
// Casting false to string makes an empty string
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
// Zipkin tags must be strings, but opentelemetry
// accepts strings, booleans, numbers, and lists of each.
if (is_array($value)) {
return implode(',', array_map(fn ($value) => $this->sanitiseTagValue($value), $value));
}
// Floats will lose precision if their string representation
// is >=14 or >=17 digits, depending on PHP settings.
// Can also throw E_RECOVERABLE_ERROR if $value is an object
// without a __toString() method.
// This is possible because OpenTelemetry\API\Trace\Span does not verify
// setAttribute() $value input.
return (string) $value;
}
public function convert(iterable $spans): array
{
$aggregate = [];
foreach ($spans as $span) {
$aggregate[] = $this->convertSpan($span);
}
return $aggregate;
}
private function convertSpan(SpanDataInterface $span): array
{
$spanParent = $span->getParentContext();
$startTimestamp = self::nanosToMicros($span->getStartEpochNanos());
$endTimestamp = self::nanosToMicros($span->getEndEpochNanos());
$serviceName = $span->getResource()->getAttributes()->get(ResourceAttributes::SERVICE_NAME)
??
$this->defaultServiceName;
$row = [
'id' => $span->getSpanId(),
'traceId' => $span->getTraceId(),
'localEndpoint' => [
'serviceName' => $serviceName,
],
'name' => $span->getName(),
'timestamp' => $startTimestamp,
'duration' => max(1, $endTimestamp - $startTimestamp),
'tags' => [],
];
$convertedKind = SpanConverter::toSpanKind($span);
if ($convertedKind != null) {
$row['kind'] = $convertedKind;
}
if ($spanParent->isValid()) {
$row['parentId'] = $spanParent->getSpanId();
}
if ($span->getStatus()->getCode() !== StatusCode::STATUS_UNSET) {
$row['tags'][self::STATUS_CODE_TAG_KEY] = $span->getStatus()->getCode();
}
if ($span->getStatus()->getCode() === StatusCode::STATUS_ERROR) {
$row['tags'][self::STATUS_DESCRIPTION_TAG_KEY] = $span->getStatus()->getDescription();
}
if (!empty($span->getInstrumentationScope()->getName())) {
$row[SpanConverter::KEY_INSTRUMENTATION_SCOPE_NAME] = $span->getInstrumentationScope()->getName();
}
if ($span->getInstrumentationScope()->getVersion() !== null) {
$row[SpanConverter::KEY_INSTRUMENTATION_SCOPE_VERSION] = $span->getInstrumentationScope()->getVersion();
}
foreach ($span->getAttributes() as $k => $v) {
$row['tags'][$k] = $this->sanitiseTagValue($v);
}
foreach ($span->getResource()->getAttributes() as $k => $v) {
$row['tags'][$k] = $this->sanitiseTagValue($v);
}
foreach ($span->getInstrumentationScope()->getAttributes() as $k => $v) {
$row['tags'][$k] = $this->sanitiseTagValue($v);
}
foreach ($span->getEvents() as $event) {
$row['annotations'][] = SpanConverter::toAnnotation($event);
}
if ($span->getTotalDroppedEvents() > 0) {
$row['tags'][self::KEY_DROPPED_EVENTS_COUNT] = (string) $span->getTotalDroppedEvents();
}
if ($span->getTotalDroppedLinks() > 0) {
$row['tags'][self::KEY_DROPPED_LINKS_COUNT] = (string) $span->getTotalDroppedLinks();
}
$droppedAttributes = $span->getAttributes()->getDroppedAttributesCount()
+ $span->getInstrumentationScope()->getAttributes()->getDroppedAttributesCount()
+ $span->getResource()->getAttributes()->getDroppedAttributesCount();
if ($droppedAttributes > 0) {
$row['tags'][self::KEY_DROPPED_ATTRIBUTES_COUNT] = (string) $droppedAttributes;
}
if (($span->getKind() === SpanKind::KIND_CLIENT) || ($span->getKind() === SpanKind::KIND_PRODUCER)) {
$remoteEndpointData = SpanConverter::toRemoteEndpoint($span);
if ($remoteEndpointData !== null) {
$row['remoteEndpoint'] = $remoteEndpointData;
}
}
if (empty($row['tags'])) {
unset($row['tags']);
}
return $row;
}
private static function toSpanKind(SpanDataInterface $span): ?string
{
return match ($span->getKind()) {
SpanKind::KIND_SERVER => ZipkinSpanKind::SERVER,
SpanKind::KIND_CLIENT => ZipkinSpanKind::CLIENT,
SpanKind::KIND_PRODUCER => ZipkinSpanKind::PRODUCER,
SpanKind::KIND_CONSUMER => ZipkinSpanKind::CONSUMER,
SpanKind::KIND_INTERNAL => null,
default => null,
};
}
private static function toAnnotation(EventInterface $event): array
{
$eventName = $event->getName();
$attributesAsJson = SpanConverter::convertEventAttributesToJson($event);
$value = ($attributesAsJson !== null) ? sprintf('"%s": %s', $eventName, $attributesAsJson) : sprintf('"%s"', $eventName);
$annotation = [
'timestamp' => self::nanosToMicros($event->getEpochNanos()),
'value' => $value,
];
if ($event->getAttributes()->getDroppedAttributesCount() > 0) {
$annotation[self::KEY_DROPPED_ATTRIBUTES_COUNT] = (string) $event->getAttributes()->getDroppedAttributesCount();
}
return $annotation;
}
private static function convertEventAttributesToJson(EventInterface $event): ?string
{
if (count($event->getAttributes()) === 0) {
return null;
}
$attributesAsJson = json_encode($event->getAttributes()->toArray());
if (($attributesAsJson === false)) {
return null;
}
return $attributesAsJson;
}
private static function toRemoteEndpoint(SpanDataInterface $span): ?array
{
$attribute = SpanConverter::findRemoteEndpointPreferredAttribute($span);
if (!$attribute) {
return null;
}
[$key, $value] = $attribute;
if (!is_string($value)) {
return null;
}
return match ($key) {
SpanConverter::NET_PEER_IP_KEY => SpanConverter::getRemoteEndpointDataFromIpAddressAndPort(
$value,
SpanConverter::getPortNumberFromSpanAttributes($span)
),
default => [
'serviceName' => $value,
],
};
}
private static function findRemoteEndpointPreferredAttribute(SpanDataInterface $span): ?array
{
$preferredAttrRank = null;
$preferredAttr = null;
foreach ($span->getAttributes() as $key => $value) {
if (array_key_exists($key, SpanConverter::REMOTE_ENDPOINT_PREFERRED_ATTRIBUTE_TO_RANK_MAP)) {
$attrRank = SpanConverter::REMOTE_ENDPOINT_PREFERRED_ATTRIBUTE_TO_RANK_MAP[$key];
if (($preferredAttrRank === null) || ($attrRank <= $preferredAttrRank)) {
$preferredAttr = [$key, $value];
$preferredAttrRank = $attrRank;
}
}
}
return $preferredAttr;
}
private static function getRemoteEndpointDataFromIpAddressAndPort(string $ipString, ?int $portNumber): ?array
{
if (!filter_var($ipString, FILTER_VALIDATE_IP)) {
return null;
}
$remoteEndpointArr = [
'serviceName' => 'unknown',
];
if (filter_var($ipString, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$remoteEndpointArr['ipv4'] = ip2long($ipString);
}
if (filter_var($ipString, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$remoteEndpointArr['ipv6'] = inet_pton($ipString);
}
$remoteEndpointArr['port'] = $portNumber ?? 0;
return $remoteEndpointArr;
}
private static function getPortNumberFromSpanAttributes(SpanDataInterface $span): ?int
{
if (($portVal = $span->getAttributes()->get('net.peer.port')) !== null) {
$portInt = (int) $portVal;
if (($portInt > 0) && ($portInt < pow(2, 16))) {
return $portInt;
}
}
return null;
}
}