-
Notifications
You must be signed in to change notification settings - Fork 2
/
XHProfComponent.php
431 lines (374 loc) · 11.3 KB
/
XHProfComponent.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
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
421
422
423
424
425
426
427
428
429
430
431
<?php
namespace stevad\xhprof;
use Yii;
use yii\base\BootstrapInterface;
use yii\base\ErrorException;
use yii\helpers\FileHelper;
use yii\helpers\Json;
use yii\web\Request;
use yii\web\View;
/**
* XHProf application component for Yii Framework 2.x.
* Uses original XHProf UI to display results.
*
* Designed to profile application from bootstrap until executing PHP shutdown function. You can also manually start
* and stop profiler in any place of your code. By default component save last 25 reports. You can see them in bundled
* debug panel for official yii2-debug extension (https://github.com/yiisoft/yii2-debug). All reports are also
* available by default in XHProf UI (e.g. http://some.path.to/xhprof_html)
*
* @author Vadym Stepanov <[email protected]>
* @date 15.11.2019
*/
class XHProfComponent extends \yii\base\Component implements BootstrapInterface
{
/**
* Enable/disable component in Yii
*
* @var bool
*/
public $enabled = true;
/**
* Direct filesystem path or path alias to directory with reports file
*
* @var string
*/
public $reportPath = '@runtime/xhprof';
/**
* How many reports to store in history file
*
* @var integer
*/
public $maxReportsCount = 25;
/**
* Flag to automatically start profiling during component bootstrap. Set to false if you want to manually start
* XHProf and start profiling.
*
* @var bool
*/
public $autoStart = true;
/**
* Flag to automatically stop running profiling session in shutdown function
*
* @var bool
*/
public $autoStop = true;
/**
* Force terminate profile process in shutdown function if it is still running with disabled `autoStop` flag
*
* @var bool
*/
public $forceStop = true;
/**
* Set value to trigger profiling only by specified GET param with any value
*
* @var string
*/
public $triggerGetParam;
/**
* If this component is used without yii2-debug extension, set true to show overlay with links to report and
* call graph. Otherwise, set false and add panel to yii2-debug (see readme for more details).
*
* @var bool
*/
public $showOverlay = true;
/**
* Direct filesystem path or path alias to the 'xhprof_lib' directory
*
* @var string
*/
public $libPath;
/**
* URL path to XHProf html reporting files without leading slash
*
* @var string
*/
public $htmlReportBaseUrl = '/xhprof_html';
/**
* Default directory to store XHProf runs. If not specified - will use 'sys_get_temp_dir()' value
*
* @var string|null
*/
public $tmpPath;
/**
* Enable/disable flag XHPROF_FLAGS_NO_BUILTINS (see http://php.net/manual/ru/xhprof.constants.php)
*
* @var bool
*/
public $flagNoBuiltins = true;
/**
* Enable/disable flag XHPROF_FLAGS_CPU (see http://php.net/manual/ru/xhprof.constants.php)
* Default: false. Reason - some overhead in calculation on linux OS
*
* @var bool
*/
public $flagCpu = false;
/**
* Enable/disable flag XHPROF_FLAGS_MEMORY (see http://php.net/manual/ru/xhprof.constants.php)
*
* @var bool
*/
public $flagMemory = true;
/**
* List of functions to ignore during profiling (http://php.net/manual/ru/function.xhprof-enable.php)
*
* @var array
*/
public $ignoredFunctions = [];
/**
* List of routes to not run xhprof on.
*
* @var array
*/
public $blacklistedRoutes = ['debug*'];
/**
* Current report details
*
* @var array
*/
private $reportInfo;
/**
* Path to the temporary directory with reports
*
* @var string
*/
private $reportSavePath;
public function init()
{
Yii::setAlias('@yii2-xhprof', __DIR__);
parent::init();
}
/**
* Initialize component and check path to xhprof library files. Start profiling and add overlay (if allowed
* by configuration).
*
* @return void
* @throws ErrorException
*/
public function bootstrap($app)
{
if (empty($this->libPath)) {
throw new ErrorException('Lib path cannot be empty');
}
$libPath = $this->libPath;
if (\strpos($libPath, '@') === 0) {
$libPath = Yii::getAlias($libPath);
}
$config = [
'flagNoBuiltins' => $this->flagNoBuiltins,
'flagCpu' => $this->flagCpu,
'flagMemory' => $this->flagMemory,
'ignoredFunctions' => $this->ignoredFunctions,
'runNamespace' => Yii::$app->id,
'libPath' => $libPath,
'htmlUrlPath' => $this->getReportBaseUrl(),
];
if ($this->tmpPath) {
$config['tmpPath'] = $this->tmpPath;
}
XHProf::getInstance()->configure($config);
if (!$this->enabled
|| PHP_SAPI === 'cli'
|| ($this->triggerGetParam !== null && $app->request->getQueryParam($this->triggerGetParam) === null)
|| $this->isRouteBlacklisted()
) {
return;
}
if ($this->autoStart) {
$this->beginProfiling();
}
if ($app->request instanceof Request && $this->showOverlay && !$app->request->isAjax) {
OverlayAsset::register($app->view);
$app->view->on(View::EVENT_END_BODY, [$this, 'appendResultsOverlay']);
}
\register_shutdown_function([$this, 'stopProfiling']);
}
/**
* Check if current route is blacklisted (should not be processed)
*
* @return bool
*/
private function isRouteBlacklisted()
{
$result = false;
$routes = $this->blacklistedRoutes;
if (Yii::$app instanceof \yii\web\Application) {
$requestRoute = Yii::$app->getUrlManager()->parseRequest(Yii::$app->getRequest())[0];
} else {
$request = Yii::$app->getRequest()->getParams();
if (!isset($request[0])) {
return true;
}
$requestRoute = $request[0];
}
foreach ($routes as $route) {
$route = \str_replace('*', '([a-zA-Z0-9\/\-\._]{0,})', \str_replace('/', '\/', '^' . $route));
if (\preg_match("/{$route}/", $requestRoute) !== 0) {
$result = true;
break;
}
}
return $result;
}
/**
* Configure XHProf instance and start profiling
*
* @return void
*/
public function beginProfiling()
{
XHProf::getInstance()->run();
}
/**
* Stop profiling and save report
*
* @return array List of urls to report and callgraph if XHProf was active
*/
public function stopProfiling()
{
$XHProf = XHProf::getInstance();
$report = [];
if ($XHProf->isStarted()
&& $XHProf->getStatus() === XHProf::STATUS_RUNNING
&& ($this->autoStop || (!$this->autoStop && $this->forceStop))
) {
$report = $XHProf->stop();
}
if ($this->isActive()) {
$this->saveReport();
}
return $report;
}
/**
* Get base URL part to the XHProf UI
*
* @return string
*/
public function getReportBaseUrl()
{
if (\strpos($this->htmlReportBaseUrl, '/') === 0) {
return Yii::$app->getRequest()->getAbsoluteUrl() . $this->htmlReportBaseUrl;
}
return $this->htmlReportBaseUrl;
}
/**
* Get if component enabled and xhprof profiler is currently started
*
* @return bool
*/
public function isActive()
{
return $this->enabled && XHProf::getInstance()->isStarted();
}
/**
* Save current report to history file and check size of the history.
*
* @return void
*/
private function saveReport()
{
$reports = $this->loadReports();
$reports[] = $this->getReportInfo();
if (\count($reports) > $this->maxReportsCount) {
\array_shift($reports);
}
$reportsFile = "{$this->getReportSavePath()}/reports.json";
\file_put_contents($reportsFile, Json::encode($reports));
}
/**
* Load list of previous reports from JSON file
*
* @return array
*/
public function loadReports()
{
$reportsFile = "{$this->getReportSavePath()}/reports.json";
$reports = [];
if (\is_file($reportsFile)) {
$reports = Json::decode(\file_get_contents($reportsFile));
}
return $reports;
}
/**
* Get reports save path
*
* @return string
*/
public function getReportSavePath()
{
if ($this->reportSavePath === null) {
$path = $this->reportPath;
if ($path === null) {
$path = Yii::$app->getRuntimePath() . '/xhprof';
} elseif (\strpos($path, '@') === 0) {
$path = Yii::getAlias($path);
}
if (!\is_dir($path)) {
FileHelper::createDirectory($path, 0777, true);
}
$this->reportSavePath = $path;
}
return $this->reportSavePath;
}
/**
* Get report details for current profiling process. Info consists of:
* - unique run identifier (runId)
* - namespace for run (ns, current application ID by default)
* - requested URL (url)
* - time of request (time)
*
* @return array key-valued list
*/
public function getReportInfo()
{
if (!$this->isActive()) {
return [
'enabled' => false,
'runId' => null,
'ns' => null,
'url' => null,
'time' => null,
];
}
if ($this->reportInfo === null) {
if (Yii::$app instanceof yii\web\Application) {
$request = Yii::$app->getRequest();
$url = $request->getHostInfo() . $request->getUrl();
} else {
$url = Yii::$app->controller->id . '/' . Yii::$app->controller->action->id;
}
$this->reportInfo = [
'enabled' => true,
'runId' => XHProf::getInstance()->getRunId(),
'ns' => XHProf::getInstance()->getRunNamespace(),
'url' => $url,
'time' => \microtime(true),
];
}
return $this->reportInfo;
}
/**
* Add code to display own overlay with links to report and callgraph for current profile run
*
* @return void
*/
public function appendResultsOverlay()
{
$XHProf = XHProf::getInstance();
if (!$XHProf->isStarted()) {
return;
}
$data = $this->getReportInfo();
$reportUrl = $XHProf->getReportUrl($data['runId'], $data['ns']);
$callgraphUrl = $XHProf->getCallgraphUrl($data['runId'], $data['ns']);
echo <<<EOD
<script type="text/javascript">
(function() {
var overlay = document.createElement('div');
overlay.setAttribute('id', 'xhprof-overlay');
overlay.innerHTML = '<div class="xhprof-header">XHProf</div><a href="{$reportUrl}" target="_blank">Report</a><a href="{$callgraphUrl}" target="_blank">Callgraph</a>';
document.getElementsByTagName('body')[0].appendChild(overlay);
})();
</script>
EOD;
}
}