-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathDrupalIntegration.php
More file actions
420 lines (367 loc) · 17.7 KB
/
Copy pathDrupalIntegration.php
File metadata and controls
420 lines (367 loc) · 17.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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
<?php
namespace DDTrace\Integrations\Drupal;
use DDTrace\HookData;
use DDTrace\Integrations\Integration;
use DDTrace\SpanData;
use DDTrace\Tag;
use DDTrace\Type;
use DDTrace\Util\ObjectKVStore;
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
use function DDTrace\active_span;
use function DDTrace\hook_method;
use function DDTrace\install_hook;
use function DDTrace\remove_hook;
use function DDTrace\set_user;
use function DDTrace\trace_method;
class DrupalIntegration extends Integration
{
const NAME = 'drupal';
public static function init(): int
{
ini_set('datadog.trace.spans_limit', max(1500, ini_get('datadog.trace.spans_limit')));
trace_method(
'Drupal\Core\DrupalKernel',
'handle',
[
'prehook' => static function (SpanData $span) {
// A pre-hook is used here to ensure that the root span name is set before the symfony integration
// checks for it.
$service = \ddtrace_config_app_name('drupal');
$rootSpan = \DDTrace\root_span();
$rootSpan->name = 'drupal.request';
$rootSpan->service = $service;
Integration::tagFrameworkServiceSource($rootSpan, 'drupal');
$rootSpan->meta[Tag::SPAN_KIND] = 'server';
$rootSpan->meta[Tag::COMPONENT] = self::NAME;
$span->name = 'drupal.kernel.handle';
$span->type = Type::WEB_SERVLET;
$span->service = $service;
Integration::tagFrameworkServiceSource($span, 'drupal');
$span->meta[Tag::SPAN_KIND] = 'server';
$span->meta[Tag::COMPONENT] = self::NAME;
}
]
);
$stackedHttpKernelTracer = static function (SpanData $span) {
$span->name = 'drupal.httpkernel.handle';
$span->type = Type::WEB_SERVLET;
Integration::setComponentMetadata($span, 'drupal');
};
// See Drupal\Core\DependencyInjection\Compiler\StackedKernelPass
// If a middleware is tagged with 'responder' => true, then the underlying middleware and the HTTP kernel
// are flagged as 'lazy', meaning Symfony\Component\HttpKernel\HttpKernel::handle() may not be called.
// Drupal 9-
trace_method('Stack\StackedHttpKernel', 'handle', $stackedHttpKernelTracer);
// Drupal 10+
trace_method('Drupal\Core\StackMiddleware\StackedHttpKernel', 'handle', $stackedHttpKernelTracer);
trace_method(
'Drupal\Core\DrupalKernel',
'boot',
[
'prehook' => static function (SpanData $span) {
$span->name = 'drupal.kernel.boot';
$span->type = Type::WEB_SERVLET;
Integration::setComponentMetadata($span, 'drupal');
}
]
);
// Cache Metrics (Cache hit/miss) - TBC
/*
hook_method(
'Drupal\Core\Cache\CacheBackendInterface',
'getMultiple',
static function ($cacheBackend, $scope, $args) {
$candidates = count($args[0]);
},
static function ($cacheBackend, $scope, $args, $retval) {
$hits = count($args[0]); // the &cids parameter is modified by reference to match the cache hits
}
);
*/
// Module and Hook Metrics
/*
hook_method(
'Drupal\Core\Extension\ModuleHandler',
'invokeAllWith',
static function ($moduleHandler, $scope, $args) {
// @var string $hook
$hook = $args[0];
// @var callable $callback
$callback = $args[1];
install_hook(
$callback,
static function (HookData $callbackHookData) use ($hook) {
// callback's signature: (callable $hook, string $module)
$args = $callbackHookData->args;
$module = $args[1];
$functionName = $module . '_' . $hook;
install_hook(
$functionName,
static function (HookData $fnHookData) use ($hook, $module, $functionName) {
// Create a span as a metric workaround
$span = $fnHookData->span();
$span->name = 'drupal.hook.' . $hook;
$span->type = Type::WEB_SERVLET;
Integration::setComponentMetadata($span, 'drupal');
$span->meta['drupal.hook'] = $hook;
$span->meta['drupal.module'] = $module;
$span->meta['drupal.function'] = $functionName;
remove_hook($fnHookData->id);
}
);
remove_hook($callbackHookData->id);
}
);
}
);
*/
install_hook(
'Drupal\Core\Extension\ModuleHandler::invokeAllWith',
static function (HookData $hookData) {
/** @var string $hook */
$hook = $hookData->args[0];
/** @var callable $callback */
$callback = $hookData->args[1];
if ($hook === 'cron') {
$hookData->data = install_hook(
$callback,
static function (HookData $callbackHookData) use ($hook) {
// callback's signature: (callable $hook, string $module)
$args = $callbackHookData->args;
$module = $args[1];
$functionName = $module . '_' . $hook;
install_hook(
$functionName,
static function (HookData $fnHookData) use ($hook, $module, $functionName) {
$span = $fnHookData->span();
$span->name = 'drupal.hook.' . $hook;
$span->type = Type::WEB_SERVLET;
Integration::setComponentMetadata($span, 'drupal');
$span->resource = $functionName;
$span->meta['drupal.hook'] = $hook;
$span->meta['drupal.module'] = $module;
$span->meta['drupal.function'] = $functionName;
remove_hook($fnHookData->id);
}
);
}
);
}
}, static function (HookData $hookData) {
if (isset($hookData->data)) {
remove_hook($hookData->data);
}
}
);
// View Metrics
/*
install_hook(
'Drupal\views\ViewExecutable::execute',
function (HookData $hook) {
// Create a span as a metric workaround
$span = $hook->span();
$span->name = 'drupal.view.execute';
$span->type = Type::WEB_SERVLET;
Integration::setComponentMetadata($span, 'drupal');
// @var \Drupal\views\Entity\View $storage
$storage = $this->storage;
if (method_exists($storage, 'label')) {
$label = $storage->label();
if (is_string($label)) {
$span->meta['drupal.view'] = $label;
}
}
}
);
*/
hook_method(
'Drupal\Core\Theme\ThemeManager',
'setThemeRegistry',
static function ($themeManager, $scope, $args) {
// The theme registry is otherwise protected
ObjectKVStore::put($themeManager, 'theme_registry', $args[0]);
}
);
hook_method(
'Drupal\Core\Theme\Registry',
'__construct',
static function ($registry, $scope, $args) {
// The theme is otherwise protected
// _construct($root, $cache, $lock, $module_handler, $theme_handler, $theme_initialization, $theme_name, $runtime_cache, $module_list)
ObjectKVStore::put($registry, 'theme_name', $args[6]);
}
);
trace_method(
'Drupal\Core\Theme\ThemeManager',
'render',
[
'recurse' => true,
'prehook' => function (SpanData $span, $args) {
$span->name = 'drupal.theme.render';
$span->service = \ddtrace_config_app_name('drupal');
Integration::tagFrameworkServiceSource($span, 'drupal');
$span->type = Type::WEB_SERVLET;
$span->meta[Tag::COMPONENT] = DrupalIntegration::NAME;
/** @var \Drupal\Core\Theme\ThemeManager $this */
$activeTheme = $this->getActiveTheme();
$themeName = $activeTheme->getName();
$themeEngine = $activeTheme->getEngine();
if (!empty($themeName)) {
$span->meta['drupal.render.theme'] = $themeName;
}
if (!empty($themeEngine)) {
$span->meta['drupal.render.engine'] = $themeEngine;
if (function_exists("{$themeEngine}_render_template")) {
$renderFunction = "{$themeEngine}_render_template";
// The theme engine may use a different extension and a different renderer
// Moreover, Drupal can use different themes in the same application
// The render function will always be called during the ThemeManager::render call
install_hook(
$renderFunction,
static function (HookData $hook) use ($span) {
$span->meta['drupal.template.file'] = $hook->args[0];
remove_hook($hook->id);
}
);
}
}
},
'posthook' => function (SpanData $span, $args) {
/** @var null|\Drupal\Core\Theme\Registry $themeRegistry */
$themeRegistry = ObjectKVStore::get($this, 'theme_registry');
if ($themeRegistry) {
$runtimeThemeRegistry = $themeRegistry->getRuntime();
$hook = $args[0];
if (is_array($hook)) {
foreach ($hook as $candidate) {
if ($runtimeThemeRegistry->has($candidate)) {
break;
}
}
$hook = $candidate;
}
$originalHook = $hook;
if (!$runtimeThemeRegistry->has($hook)) {
// Iteratively strip everything after the last '__' delimiter, until an
// implementation is found
while ($pos = strrpos($hook, '__')) {
$hook = substr($hook, 0, $pos);
if ($runtimeThemeRegistry->has($hook)) {
break;
}
}
}
if ($runtimeThemeRegistry->has($hook)) {
$span->meta['drupal.render.hook'] = $span->resource = $hook;
$info = $runtimeThemeRegistry->get($hook);
if (isset($info['base hook'])) {
$span->meta['drupal.render.base_hook'] = $info['base hook'];
}
if (isset($info['type'])) {
$span->meta['drupal.render.type'] = $info['type'];
}
if (isset($info['render element'])) {
$span->meta['drupal.render.element'] = $info['render element'];
}
if (isset($info['template'])) {
$span->meta['drupal.template.template'] = $info['template'];
}
if (isset($info['function'])) {
$span->meta['drupal.render.theme_function'] = $info['function'];
}
if (isset($info['path'])) {
// The template can be from a different theme than the active one
// Format: '.../themes/<theme_name>/...'
$path = $info['path'];
$themePathStart = strpos($path, '/themes/');
if ($themePathStart !== false) {
$themePath = substr($path, $themePathStart + 8); // Between '/themes/', 8 = strlen('/themes/')
$themePath = substr($themePath, 0, strpos($themePath, '/')); // Until the next '/'
$span->meta['drupal.template.theme'] = $themePath;
}
}
} else {
$span->meta['drupal.render.hook'] = $span->resource = $originalHook;
}
}
}
]
);
hook_method(
'Drupal\Core\EventSubscriber\MainContentViewSubscriber',
'__construct',
static function ($mainContViewSubscriber, $scope, $args) {
// These are otherwise protected
$classResolver = $args[0];
$mainContentRenderers = $args[2];
ObjectKVStore::put($mainContViewSubscriber, 'class_resolver', $classResolver);
ObjectKVStore::put($mainContViewSubscriber, 'main_content_renderers', $mainContentRenderers);
}
);
hook_method(
'Drupal\Core\EventSubscriber\MainContentViewSubscriber',
'onViewRenderArray',
null,
static function ($mainContViewSubscriber, $scope, $args) {
// Called on the kernel.view event => active span should be symfony.kernel.view
$span = active_span();
if ($span->name === 'symfony.kernel.view') {
$classResolver = ObjectKVStore::get($mainContViewSubscriber, 'class_resolver');
$mainContentRenderers = ObjectKVStore::get($mainContViewSubscriber, 'main_content_renderers');
/** @var \Symfony\Component\HttpKernel\Event\ViewEvent $event */
$event = $args[0];
$request = $event->getRequest();
$result = $event->getControllerResult();
if ($classResolver
&& $mainContentRenderers
&& is_array($result)
&& ($request->query->has(MainContentViewSubscriber::WRAPPER_FORMAT)
|| $request->getRequestFormat() == 'html'
)
) {
$wrapper = $request->query->get(MainContentViewSubscriber::WRAPPER_FORMAT, 'html');
// Fall back to HTML if the requested wrapper envelope is not available.
$wrapper = isset($mainContentRenderers[$wrapper]) ? $wrapper : 'html';
$renderer = $classResolver->getInstanceFromDefinition($mainContentRenderers[$wrapper]);
if ($renderer) {
$span->resource = get_class($renderer);
}
}
}
}
);
trace_method(
'Symfony\Component\HttpFoundation\Response',
'send',
static function (SpanData $span) {
$span->name = 'symfony.response.send';
$span->service = \ddtrace_config_app_name('drupal');
Integration::tagFrameworkServiceSource($span, 'drupal');
$span->type = Type::WEB_SERVLET;
$span->meta[Tag::COMPONENT] = self::NAME;
}
);
hook_method(
'Drupal\Core\Session\AccountProxy',
'setAccount',
static function ($This, $scope, $args) {
if (!\DDTrace\root_span()) {
return;
}
$account = $args[0];
if ($account instanceof \Drupal\Core\Session\AccountInterface) {
$metadata = [
'login' => $account->getAccountName(),
'username' => $account->getDisplayName(),
'email' => $account->getEmail(),
];
$metadata = array_filter($metadata, static function ($value) {
return !empty($value);
});
set_user($account->id(), $metadata);
}
}
);
return Integration::LOADED;
}
}