-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenTelemetry.php
More file actions
354 lines (309 loc) · 11.7 KB
/
Copy pathOpenTelemetry.php
File metadata and controls
354 lines (309 loc) · 11.7 KB
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
<?php
/**
* OpenTelemetry plugin for Matomo.
*
* Copyright (C) Digitalist Open Cloud <cloud@digitalist.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace Piwik\Plugins\OpenTelemetry;
use Piwik\Plugin;
use Piwik\Container\StaticContainer;
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\Context\Context;
use OpenTelemetry\API\Baggage\Baggage;
use OpenTelemetry\API\Metrics\MeterInterface;
use Piwik\Plugins\OpenTelemetry\SystemSettings;
use Monolog\Logger;
use Piwik\Plugins\OpenTelemetry\Handler\OpenTelemetryHandler;
use Piwik\Log\LoggerInterface;
/***
* Main class to create traces.
*/
class OpenTelemetry extends Plugin
{
private static $activeSpan = null;
private static $httpSpan = null;
private static $httpTracer = null;
private static $httpScope = null;
private static $apiTracer = null;
private static $meter = null;
private static $apiDurationHistogram = null;
private static $apiStartTime = null;
private static $memoryHistogram = null;
private static $archiveStartTime = null;
private static $archiveDurationHistogram = null;
private static $archiveRunsCounter = null;
/**
* Metrics for API requests.
*/
private static function meter(): MeterInterface
{
if (!self::$meter) {
self::$meter = Globals::meterProvider()->getMeter('matomo.api');
}
return self::$meter;
}
/**
* Metrics for peak memory usage for request.
*/
private static function memoryHistogram()
{
if (!self::$memoryHistogram) {
self::$memoryHistogram = Globals::meterProvider()
->getMeter('matomo.php')
->createHistogram(
'matomo.php.memory.peak',
'By',
'Peak PHP memory usage per request'
);
}
return self::$memoryHistogram;
}
private static function archiveMetrics()
{
if (!self::$archiveDurationHistogram) {
$meter = \OpenTelemetry\API\Globals::meterProvider()
->getMeter('matomo.archive');
self::$archiveDurationHistogram = $meter->createHistogram(
'matomo.archive.duration',
'ms',
'Duration of Matomo core archive runs'
);
self::$archiveRunsCounter = $meter->createCounter(
'matomo.archive.runs',
'1',
'Number of archive runs'
);
}
}
/**
* The events we want to use for OpenTelemetry.
* Also add needed JS files and variables for client tracing.
*/
public function registerEvents(): array
{
return [
'Http.sendHttpRequest' => 'onRequestStart',
'Http.sendHttpRequest.end' => 'onRequestEnd',
'API.Request.dispatch' => 'onApiStart',
'API.Request.dispatch.end' => 'onApiEnd',
'AssetManager.getJavaScriptFiles' => 'getJSFiles',
'Template.jsGlobalVariables' => 'addJsVariables',
'Platform.initialized' => 'attachOtelHandler',
'CronArchive.init.start' => 'onArchiveStart',
'CronArchive.end' => 'onArchiveEnd',
];
}
/**
* Attach logger, to catch logs from Monolog.
*/
public function attachOtelHandler(): void
{
$logger = StaticContainer::get('Psr\Log\LoggerInterface');
if ($logger instanceof Logger) {
$logger->pushHandler(
new OpenTelemetryHandler(Logger::DEBUG)
);
//$logger->pushHandler(new NullHandler(Logger::DEBUG));
}
}
/**
* Normal HTTP requests in Matomo UI.
*/
private static function httpTracer()
{
if (!self::$httpTracer) {
self::$httpTracer = Globals::tracerProvider()->getTracer('matomo.http');
}
return self::$httpTracer;
}
/**
* API requests, these happens often in Matomo UI.
*/
private static function apiTracer()
{
if (!self::$apiTracer) {
self::$apiTracer = Globals::tracerProvider()->getTracer('matomo.api');
}
return self::$apiTracer;
}
public function onArchiveStart(): void
{
// if (!self::$metricsEnabled) {
// return;
// }
self::$archiveStartTime = microtime(true);
}
public function onArchiveEnd(): void
{
// if (!self::$metricsEnabled || self::$archiveStartTime === null) {
// return;
// }
self::archiveMetrics();
$durationMs = (microtime(true) - self::$archiveStartTime) * 1000;
self::$archiveDurationHistogram->record($durationMs, [
'process.runtime.name' => PHP_SAPI,
]);
self::$archiveRunsCounter->add(1);
self::$archiveStartTime = null;
}
/**
* When request starts.
*/
public function onRequestStart(): void
{
$propagator = Globals::propagator();
$headers = [];
foreach ($_SERVER as $key => $value) {
if (str_starts_with($key, 'HTTP_')) {
$headerName = strtolower(str_replace('_', '-', substr($key, 5)));
$headers[$headerName] = $value;
}
}
$parentContext = $propagator->extract($headers);
Context::storage()->attach($parentContext);
$tracer = self::httpTracer();
self::$httpSpan = $tracer
->spanBuilder(
($_SERVER['REQUEST_METHOD'] ?? 'unknown') . ' ' . ($_SERVER['REQUEST_URI'] ?? '/')
)
->setSpanKind(SpanKind::KIND_SERVER)
->setParent($parentContext)
->setAttribute('http.url', $_SERVER['REQUEST_URI'] ?? 'unknown')
->setAttribute('http.method', $_SERVER['REQUEST_METHOD'] ?? 'UNKNOWN')
->setStartTimestamp((int) (microtime(true) * 1e9))
->startSpan();
// @todo: Not really working yet, set site id from baggage (js in this case), if we have it.
$baggage = Baggage::getCurrent();
$siteId = $baggage->getValue('matomo.site_id');
if ($siteId !== null) {
self::$httpSpan->setAttribute('matomo.site_id', $siteId);
}
self::$httpScope = self::$httpSpan->activate();
}
/**
* HTTP request end.
*/
public function onRequestEnd(): void
{
$peakMemory = memory_get_peak_usage(true);
self::memoryHistogram()->record($peakMemory, [
'process.runtime.name' => php_sapi_name(),
]);
if (self::$httpSpan) {
self::$httpSpan->setStatus(
StatusCode::STATUS_OK
);
self::$httpSpan->setAttribute(
'php.memory.peak',
memory_get_peak_usage(true)
);
self::$httpSpan->end((int) (microtime(true) * 1e9));
self::$httpSpan = null;
}
}
/**
* API start event.
*/
public function onApiStart(): void
{
$tracer = self::apiTracer();
self::$apiStartTime = microtime(true);
if (!self::$apiDurationHistogram) {
self::$apiDurationHistogram = self::meter()
->createHistogram(
'matomo.api.request.duration',
'ms',
'Duration of Matomo API requests'
);
}
self::$activeSpan = $tracer
->spanBuilder('API ' . ($_GET['method'] ?? 'unknown'))
->setSpanKind(SpanKind::KIND_SERVER)
->setAttribute('matomo.api.method', $_GET['method'] ?? 'unknown')
->setAttribute('http.method', $_SERVER['REQUEST_METHOD'] ?? 'unknown')
->setStartTimestamp((int) (microtime(true) * 1e9))
->startSpan();
self::$activeSpan->activate();
}
/**
* API end event.
*/
public function onApiEnd(): void
{
if (self::$activeSpan) {
$durationMs = null;
$peakMemory = memory_get_peak_usage(true);
self::memoryHistogram()->record($peakMemory, [
'process.runtime.name' => php_sapi_name(),
]);
if (self::$apiStartTime !== null) {
$durationMs = (microtime(true) - self::$apiStartTime) * 1000;
}
$attributes = [
'matomo.api.method' => $_GET['method'] ?? 'unknown',
'http.method' => $_SERVER['REQUEST_METHOD'] ?? 'unknown',
'http.status_code' => http_response_code() ?: 200,
'php.memory.peak' => memory_get_peak_usage(true),
];
if ($durationMs !== null && self::$apiDurationHistogram) {
self::$apiDurationHistogram->record(
$durationMs,
$attributes
);
}
self::$activeSpan->setAttribute('http.status_code', $attributes['http.status_code']);
self::$activeSpan->setStatus(StatusCode::STATUS_OK);
self::$activeSpan->end();
self::$activeSpan = null;
self::$apiStartTime = null;
}
}
/**
* Attach needed javascript files.
*/
public function getJSFiles(&$files)
{
$files[] = 'plugins/OpenTelemetry/js/start.js';
$files[] = 'plugins/OpenTelemetry/js/otel.min.js';
}
/**
* Get needed JavaScript variables from Matomo.
*/
public function addJsVariables(&$out)
{
$settings = new SystemSettings();
$enabled = (bool) $settings->enabled->getValue();
$enableDocumentLoadMonitoring = (bool) $settings->enableDocumentLoadMonitoring->getValue();
$enableUserInteractionMonitoring = (bool) $settings->enableUserInteractionMonitoring->getValue();
$enableXMLHttpRequestMonitoring = (bool) $settings->enableXMLHttpRequestMonitoring->getValue();
$enableWebVitals = (bool) $settings->enableWebVitals->getValue();
$enableUxMonitoring = (bool) $settings->enableUxMonitoring->getValue();
$serviceName = $settings->serviceName->getValue();
$otelEndpoint = $settings->otelEndpoint->getValue();
$resourceAttributes = $settings->resourceAttributes->getValue();
$out .= "piwik.openTelemetryEnabled = " . json_encode($enabled) . ";\n";
$out .= "piwik.openTelemetryServiceName = " . json_encode($serviceName) . ";\n";
$out .= "piwik.openTelemetryEndpoint = " . json_encode($otelEndpoint) . ";\n";
$out .= "piwik.openTelemetryDocumentLoadMonitoring = " . json_encode($enableDocumentLoadMonitoring) . ";\n";
$out .= "piwik.openTelemetryUserInteractionMonitoring = " . json_encode($enableUserInteractionMonitoring) . ";\n";
$out .= "piwik.openTelemetryXMLHttpRequestMonitoring= " . json_encode($enableXMLHttpRequestMonitoring) . ";\n";
$out .= "piwik.openTelemetryWebVitals = " . json_encode($enableWebVitals) . ";\n";
$out .= "piwik.openTelemetryUxMonitoring = " . json_encode($enableUxMonitoring) . ";\n";
$out .= "piwik.openTelemetryResourceAttributes = " . json_encode($resourceAttributes) . ";\n";
}
}