This repository has been archived by the owner on Jan 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathTideways.php
1525 lines (1304 loc) · 49.5 KB
/
Tideways.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Tideways
*
* Copyright 2014-2018 Tideways GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Tideways\Traces;
/**
* Abstraction for trace spans.
*
* Different implementations based on support
*/
abstract class Span
{
/**
* Create Child span
* @private
*/
abstract public function createSpan($name = null);
/**
* @private
* @return array
*/
abstract public function getSpans();
/**
* 32/64 bit random integer.
*
* @return int
*/
public abstract function getId();
/**
* Record start of timer in microseconds.
*
* If timer is already running, don't record another start.
*/
public abstract function startTimer();
/**
* Record stop of timer in microseconds.
*
* If timer is not running, don't record.
*/
public abstract function stopTimer();
/**
* Annotate span with metadata.
*
* @param array<string,scalar>
*/
public abstract function annotate(array $annotations);
}
namespace Tideways\Traces;
class NullSpan extends Span
{
public function createSpan($name = null)
{
return $this;
}
public function getSpans()
{
return array();
}
public function getId()
{
return 0;
}
/**
* Record start of timer in microseconds.
*
* If timer is already running, don't record another start.
*/
public function startTimer()
{
}
/**
* Record stop of timer in microseconds.
*
* If timer is not running, don't record.
*/
public function stopTimer()
{
}
/**
* Annotate span with metadata.
*
* @param array<string,scalar>
*/
public function annotate(array $annotations)
{
}
}
namespace Tideways\Traces;
use Tideways\Profiler;
/**
* When Tideways PHP extension is not installed the span API
* is handled in memory.
*/
class PhpSpan extends Span
{
const ID = 'i';
const NAME = 'n';
const STARTS = 'b';
const STOPS = 'e';
const ANNOTATIONS = 'a';
/**
* @var array
*/
private static $spans = array();
private static $startTime = false;
/**
* @var bool
*/
private $timerRunning = false;
/**
* @var int
*/
private $idx;
static public function clear()
{
self::$spans = array();
self::$startTime = microtime(true);
}
public function createSpan($name = null)
{
$idx = count(self::$spans);
return new self($idx, $name);
}
/**
* @return int
*/
private static function currentDuration()
{
return intval(round((microtime(true) - self::$startTime) * 1000000));
}
public function getSpans()
{
return self::$spans;
}
public function __construct($idx, $name = null)
{
$this->idx = $idx;
self::$spans[$idx] = array(
self::STARTS => array(),
self::STOPS => array(),
self::ANNOTATIONS => array(),
);
if ($name) {
self::$spans[$idx][self::NAME] = $name;
}
}
public function getId()
{
if (!isset(self::$spans[$this->idx][self::ID])) {
self::$spans[$this->idx][self::ID] = \Tideways\Profiler::generateRandomId();
}
return self::$spans[$this->idx][self::ID];
}
public function startTimer()
{
if ($this->timerRunning) {
return;
}
self::$spans[$this->idx][self::STARTS][] = self::currentDuration();
$this->timerRunning = true;
}
public function stopTimer()
{
if (!$this->timerRunning) {
return;
}
self::$spans[$this->idx][self::STOPS][] = self::currentDuration();
$this->timerRunning = false;
}
public function annotate(array $annotations)
{
foreach ($annotations as $name => $value) {
if (!is_scalar($value)) {
continue;
}
self::$spans[$this->idx][self::ANNOTATIONS][$name] = (string)$value;
}
}
}
namespace Tideways\Traces;
class TwExtensionSpan extends Span
{
/**
* @var int
*/
private $idx;
public function createSpan($name = null)
{
return new self(tideways_span_create($name));
}
public function getSpans()
{
return tideways_get_spans();
}
public function __construct($idx)
{
$this->idx = $idx;
}
/**
* 32/64 bit random integer.
*
* @return int
*/
public function getId()
{
return $this->idx;
}
/**
* Record start of timer in microseconds.
*
* If timer is already running, don't record another start.
*/
public function startTimer()
{
tideways_span_timer_start($this->idx);
}
/**
* Record stop of timer in microseconds.
*
* If timer is not running, don't record.
*/
public function stopTimer()
{
tideways_span_timer_stop($this->idx);
}
/**
* Annotate span with metadata.
*
* @param array<string,scalar>
*/
public function annotate(array $annotations)
{
tideways_span_annotate($this->idx, $annotations);
}
}
namespace Tideways\Profiler;
/**
* Low-level abstraction for storage of profiling data.
*/
interface Backend
{
public function socketStore(array $trace);
public function socketStoreMeasurement(array $measurement);
public function udpStore(array $trace);
}
namespace Tideways\Profiler;
class NetworkBackend implements Backend
{
/**
* Old v1 type profile format.
*/
const TYPE_PROFILE = 'profile';
/**
* v2 type traces
*/
const TYPE_TRACE = 'trace';
/**
* new format for all types
*/
const TYPE_T2 = 't2';
private $socketFile;
private $udp;
public function __construct($socketFile = "unix:///var/run/tideways/tidewaysd.sock", $udp = "127.0.0.1:8135")
{
$this->socketFile = $socketFile;
$this->udp = $udp;
}
/**
* To avoid user apps messing up socket errors that Tideways can produce
* when the daemon is not reachable, this error handler is used
* wrapped around daemons to guard user apps from erroring.
*/
public static function ignoreErrorsHandler($errno, $errstr, $errfile, $errline)
{
// ignore all errors!
}
public function socketStore(array $trace)
{
if (!function_exists('json_encode')) {
\Tideways\Profiler::log(1, "ext/json must be installed and activated to use Tideways.");
return;
}
set_error_handler(array(__CLASS__, "ignoreErrorsHandler"));
$fp = stream_socket_client($this->socketFile);
if ($fp == false) {
\Tideways\Profiler::log(1, "Cannot connect to socket for storing trace.");
restore_error_handler();
return;
}
$flags = 0;
if (defined('JSON_PARTIAL_OUTPUT_ON_ERROR')) {
$flags = constant('JSON_PARTIAL_OUTPUT_ON_ERROR');
}
$payload = json_encode(array('type' => self::TYPE_TRACE, 'payload' => $trace), $flags);
$timeout = (int)ini_get('tideways.timeout');
// We always enforce a timeout, even when the user configures
// tideways.timeout=0 manually
if (!$timeout) {
$timeout = 10000;
}
if ($trace['keep']) {
// as a dev trace we collect more data and the developer can be
// waiting a little longer to make sure the socket gets everything.
$timeout *= 10;
}
stream_set_timeout($fp, 0, $timeout); // 10 milliseconds max
if (fwrite($fp, $payload) < strlen($payload)) {
\Tideways\Profiler::log(1, "Could not write payload to socket.");
}
fclose($fp);
restore_error_handler();
\Tideways\Profiler::log(3, "Sent trace to socket.");
}
public function socketStoreMeasurement(array $measurement)
{
if (!function_exists('json_encode')) {
\Tideways\Profiler::log(1, "ext/json must be installed and activated to use Tideways.");
return;
}
set_error_handler(array(__CLASS__, "ignoreErrorsHandler"));
$fp = stream_socket_client($this->socketFile);
if ($fp == false) {
\Tideways\Profiler::log(1, "Cannot connect to socke for recording measurement.");
restore_error_handler();
return;
}
$spans = array(
array(
'ts' => $measurement['spans'][0]['b'][0],
'd' => $measurement['spans'][0]['e'][0] - $measurement['spans'][0]['b'][0],
'a' => array(
'tw.key' => $measurement['apiKey'],
'tw.s' => $measurement['service'],
'tw.tx' => $measurement['tx'],
'php.memory' => $measurement['spans'][0]['a']['mem'],
),
'n' => 'php',
)
);
$payload = json_encode(array('type' => self::TYPE_T2, 'payload' => $spans));
// Golang is very strict about json types.
$payload = str_replace('"a":[]', '"a":{}', $payload);
stream_set_timeout($fp, 0, 200);
if (fwrite($fp, $payload) < strlen($payload)) {
\Tideways\Profiler::log(1, "Could not write payload to socket.");
}
fclose($fp);
restore_error_handler();
\Tideways\Profiler::log(3, "Sent trace to socket.");
}
public function udpStore(array $trace)
{
if (!function_exists('json_encode')) {
\Tideways\Profiler::log(1, "ext/json must be installed and activated to use Tideways.");
return;
}
set_error_handler(array(__CLASS__, "ignoreErrorsHandler"));
$fp = stream_socket_client("udp://" . $this->udp);
if ($fp == false) {
\Tideways\Profiler::log(1, "Cannot connect to UDP port for storing trace.");
restore_error_handler();
return;
}
unset($trace['id']);
$payload = json_encode($trace);
// Golang is very strict about json types.
$payload = str_replace('"a":[]', '"a":{}', $payload);
stream_set_timeout($fp, 0, 200);
if (fwrite($fp, $payload) < strlen($payload)) {
\Tideways\Profiler::log(1, "Could not write payload to UDP port.");
}
fclose($fp);
restore_error_handler();
\Tideways\Profiler::log(3, "Sent trace to UDP port.");
}
}
namespace Tideways\Profiler;
/**
* Convert a Backtrace to a String like {@see Exception::getTraceAsString()} would do.
*/
class BacktraceConverter
{
static public function convertToString(array $backtrace)
{
$trace = '';
foreach ($backtrace as $k => $v) {
if (!isset($v['function'])) {
continue;
}
if (!isset($v['file'])) {
$v['file'] = '';
}
if (!isset($v['line'])) {
$v['line'] = '';
}
$args = '';
if (isset($v['args'])) {
$args = implode(', ', array_map(function ($arg) {
return (is_object($arg)) ? get_class($arg) : gettype($arg);
}, $v['args']));
}
$trace .= '#' . ($k) . ' ';
if (isset($v['file'])) {
$trace .= $v['file'] . '(' . $v['line'] . '): ';
}
if (isset($v['class'])) {
$trace .= $v['class'] . '->';
}
$trace .= $v['function'] . '(' . $args .')' . "\n";
}
return $trace;
}
}
namespace Tideways;
/**
* Tideways PHP API
*
* Contains all methods to gather measurements and profile data with
* Xhprof and send to local Profiler Collector Daemon.
*
* This class is intentionally monolithic and static to allow
* users to easily copy it into their projects or auto-prepend PHP
* scripts.
*
* @example
*
* Tideways\Profiler::start($apiKey);
* Tideways\Profiler::setTransactionName("my tx name");
*
* Calling the {@link stop()} method is not necessary as it is
* called automatically from a shutdown handler, if you are timing
* worker processes however it is necessary:
*
* Tideways\Profiler::stop();
*
* The method {@link setTransactionName} is required, failing to call
* it will result in discarding of the data.
*/
class Profiler
{
const MODE_DISABLED = 0;
const MODE_NONE = 0;
const MODE_BASIC = 1;
const MODE_PROFILING = 2;
const MODE_TRACING = 4;
const MODE_FULL = 6;
const EXTENSION_NONE = 0;
const EXTENSION_XHPROF = 1;
const EXTENSION_TIDEWAYS = 2;
const EXT_FATAL = 1;
const EXT_EXCEPTION = 4;
const EXT_TRANSACTION_NAME = 8;
const FRAMEWORK_ZEND_FRAMEWORK1 = 'zend1';
const FRAMEWORK_ZEND_FRAMEWORK2 = 'zend2';
const FRAMEWORK_SYMFONY2_COMPONENT = 'symfony2c';
const FRAMEWORK_SYMFONY2_FRAMEWORK = 'symfony2';
const FRAMEWORK_OXID = 'oxid';
const FRAMEWORK_OXID6 = 'oxid6';
const FRAMEWORK_SHOPWARE = 'shopware';
const FRAMEWORK_WORDPRESS = 'wordpress';
const FRAMEWORK_LARAVEL = 'laravel';
const FRAMEWORK_MAGENTO = 'magento';
const FRAMEWORK_MAGENTO2 = 'magento2';
const FRAMEWORK_PRESTA16 = 'presta16';
const FRAMEWORK_DRUPAL8 = 'drupal8';
const FRAMEWORK_TYPO3 = 'typo3';
const FRAMEWORK_FLOW = 'flow';
const FRAMEWORK_FLOW4 = 'flow4';
const FRAMEWORK_CAKE2 = 'cake2';
const FRAMEWORK_CAKE3 = 'cake3';
const FRAMEWORK_YII = 'yii';
const FRAMEWORK_YII2 = 'yii2';
/**
* Default XHProf/Tideways hierachical profiling options.
*/
private static $defaultOptions = array(
'ignored_functions' => array(
'call_user_func',
'call_user_func_array',
'array_filter',
'array_map',
'array_reduce',
'array_walk',
'array_walk_recursive',
'Symfony\Component\DependencyInjection\Container::get',
),
'transaction_function' => null,
'exception_function' => null,
'watches' => array(),
'callbacks' => array(),
'framework' => null,
);
private static $trace;
private static $currentRootSpan;
private static $shutdownRegistered = false;
private static $error = false;
private static $mode = self::MODE_DISABLED;
private static $backend;
private static $extension = self::EXTENSION_NONE;
private static $logLevel = 0;
public static function setBackend(Profiler\Backend $backend = null)
{
self::$backend = $backend;
}
public static function detectExceptionFunction($function)
{
self::$defaultOptions['exception_function'] = $function;
}
/**
* Instruct Tideways Profiler to automatically detect transaction names during profiling.
*
* @param string $function - A transaction function name
*/
public static function detectFrameworkTransaction($function)
{
self::detectFramework($function);
}
/**
* Configure detecting framework transactions and ignoring unnecessary layer calls.
*
* If the framework is not from the list of known frameworks it is assumed to
* be a function name that is the transaction function.
*
* @param string $framework
*/
public static function detectFramework($framework)
{
self::$defaultOptions['framework'] = $framework;
$cli = (php_sapi_name() === 'cli');
switch ($framework) {
case self::FRAMEWORK_ZEND_FRAMEWORK1:
self::$defaultOptions['transaction_function'] = 'Zend_Controller_Action::dispatch';
self::$defaultOptions['exception_function'] = 'Zend_Controller_Response_Abstract::setException';
break;
case self::FRAMEWORK_ZEND_FRAMEWORK2:
self::$defaultOptions['transaction_function'] = 'Zend\\Mvc\\Controller\\ControllerManager::get';
break;
case self::FRAMEWORK_SYMFONY2_COMPONENT:
self::$defaultOptions['transaction_function'] = $cli
? 'Symfony\Component\Console\Application::find'
: 'Symfony\Component\HttpKernel\Controller\ControllerResolver::createController';
self::$defaultOptions['exception_function'] = $cli
? 'Symfony\Component\Console\Application::renderException'
: 'Symfony\Component\HttpKernel\HttpKernel::handleException';
break;
case self::FRAMEWORK_SYMFONY2_FRAMEWORK:
self::$defaultOptions['transaction_function'] = $cli
? 'Symfony\Component\Console\Application::find'
: 'Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver::createController';
self::$defaultOptions['exception_function'] = $cli
? 'Symfony\Component\Console\Application::renderException'
: 'Symfony\Component\HttpKernel\HttpKernel::handleException';
break;
case self::FRAMEWORK_OXID:
self::$defaultOptions['transaction_function'] = 'oxView::setClassName';
self::$defaultOptions['exception_function'] = 'oxShopControl::_handleBaseException';
break;
case self::FRAMEWORK_OXID6:
self::$defaultOptions['transaction_function'] = 'OxidEsales\EshopCommunity\Core\Controller\BaseController::setClassKey';
self::$defaultOptions['exception_function'] = 'OxidEsales\EshopCommunity\Core\ShopControl::logException';
break;
case self::FRAMEWORK_SHOPWARE:
self::$defaultOptions['transaction_function'] = $cli
? 'Symfony\Component\Console\Application::find'
: 'Enlight_Controller_Action::dispatch';
self::$defaultOptions['exception_function'] = $cli
? 'Symfony\Component\Console\Application::renderException'
: 'Zend_Controller_Response_Abstract::setException';
break;
case self::FRAMEWORK_WORDPRESS:
self::$defaultOptions['transaction_function'] = 'get_query_template';
break;
case self::FRAMEWORK_LARAVEL:
self::$defaultOptions['transaction_function'] = $cli
? 'Symfony\Component\Console\Application::find'
: 'Illuminate\Routing\Controller::callAction';
self::$defaultOptions['exception_function'] = $cli
? 'Symfony\Component\Console\Application::renderException'
: 'Illuminate\Foundation\Http\Kernel::reportException';
break;
case self::FRAMEWORK_MAGENTO:
self::$defaultOptions['transaction_function'] = 'Mage_Core_Controller_Varien_Action::dispatch';
self::$defaultOptions['exception_function'] = 'Mage::printException';
break;
case self::FRAMEWORK_MAGENTO2:
self::$defaultOptions['transaction_function'] = 'Magento\Framework\App\ActionFactory::create';
self::$defaultOptions['exception_function'] = 'Magento\Framework\App\Http::catchException';
break;
case self::FRAMEWORK_PRESTA16:
self::$defaultOptions['transaction_function'] = 'ControllerCore::getController';
self::$defaultOptions['exception_function'] = 'PrestaShopExceptionCore::displayMessage';
break;
case self::FRAMEWORK_DRUPAL8:
self::$defaultOptions['transaction_function'] = 'Drupal\Core\Controller\ControllerResolver::createController';
self::$defaultOptions['exception_function'] = 'Symfony\Component\HttpKernel\HttpKernel::handleException';
break;
case self::FRAMEWORK_FLOW:
self::$defaultOptions['transaction_function'] = 'TYPO3\Flow\Mvc\Controller\ActionController_Original::callActionMethod';
self::$defaultOptions['exception_function'] = 'TYPO3\Flow\Error\AbstractExceptionHandler::handleException';
break;
case self::FRAMEWORK_FLOW4:
self::$defaultOptions['transaction_function'] = 'Neos\Flow\Mvc\Controller\ActionController_Original::callActionMethod';
self::$defaultOptions['exception_function'] = 'Neos\Flow\Error\AbstractExceptionHandler::handleException';
break;
case self::FRAMEWORK_TYPO3:
self::$defaultOptions['transaction_function'] = 'TYPO3\CMS\Extbase\Mvc\Controller\ActionController::callActionMethod';
self::$defaultOptions['exception_function'] = 'TYPO3\CMS\Error\AbstractExceptionHandler::handleException';
break;
case self::FRAMEWORK_CAKE2:
self::$defaultOptions['transaction_function'] = 'Controller::invokeAction';
self::$defaultOptions['exception_function'] = 'ExceptionRenderer::__construct';
break;
case self::FRAMEWORK_CAKE3:
self::$defaultOptions['transaction_function'] = 'Cake\\Controller\\Controller::invokeAction';
self::$defaultOptions['exception_function'] = 'Cake\\Error\\ExceptionRenderer::__construct';
break;
case self::FRAMEWORK_YII:
self::$defaultOptions['transaction_function'] = 'CController::run';
self::$defaultOptions['exception_function'] = 'CApplication::handleException';
break;
case self::FRAMEWORK_YII2:
self::$defaultOptions['transaction_function'] = 'yii\\base\\Module::runAction';
self::$defaultOptions['exception_function'] = 'yii\\base\\ErrorHandler::handleException';
break;
default:
self::$defaultOptions['transaction_function'] = $framework;
break;
}
}
/**
* Add more ignore functions to profiling options.
*
* @param array<string> $functionNames
* @return void
*/
public static function addIgnoreFunctions(array $functionNames)
{
foreach ($functionNames as $functionName) {
self::$defaultOptions['ignored_functions'][] = $functionName;
}
}
/**
* Start profiling in development mode.
*
* This will always generate a full profile and send it to the profiler.
* It adds a correlation id that forces the profile into "developer"
* traces and activates the memory profiling as well.
*
* WARNING: This method can cause huge performance impact on production
* setups. Make sure to wrap this in your own sampling code and don't
* execute it in every request.
*/
public static function startDevelopment($apiKey = null, array $options = array())
{
if ($apiKey) {
$options['api_key'] = $apiKey;
} else if (!isset($options['api_key'])) {
$options['api_key'] = isset($_SERVER['TIDEWAYS_APIKEY']) ? $_SERVER['TIDEWAYS_APIKEY'] : ini_get("tideways.api_key");
}
$time = time() + 60;
$_SERVER['TIDEWAYS_SESSION'] =
"time=" . $time . "&user=&method=&hash=" .
hash_hmac('sha256', 'method=&time=' . $time . '&user=', md5($options['api_key']))
;
self::start($options);
}
/**
* Start production profiling for the application.
*
* There are three modes for profiling:
*
* 1. Wall-time only profiling of the complete request (no overhead)
* 2. Full profile/trace using xhprof (depending of # function calls
* significant overhead)
* 3. Whitelist-profiling mode only interesting functions.
* (5-40% overhead, requires custom xhprof version >= 0.95)
*
* Decisions to profile are made based on a sample-rate and random picks.
* You can influence the sample rate and pick a value that suites your
* application. Applications with lower request rates need a much higher
* transaction rate (25-50%) than applications with high load (<= 1%).
*
* Factors that influence sample rate:
*
* 1. Second parameter $sampleRate to start() method.
* 2. _tideways Query Parameter (string key is deprecated or array)
* 3. Cookie TIDEWAYS_SESSION
* 4. TIDEWAYS_SAMPLERATE environment variable.
* 5. X-TIDEWAYS-PROFILER HTTP header
*
* start() automatically invokes a register shutdown handler that stops and
* transmits the profiling data to the local daemon for further processing.
*
* @param array|string $options Either options array or api key (when string)
* @param int $sampleRate Deprecated, use "sample_rate" key in options instead.
*
* @return void
*/
public static function start($options = array(), $sampleRate = null)
{
self::ignoreTransaction(); // this discards any data that was collected up to now and restarts.
if (!is_array($options)) {
$options = array('api_key' => $options);
}
if ($sampleRate !== null) {
$options['sample_rate'] = $sampleRate;
}
$defaults = array(
'api_key' => isset($_SERVER['TIDEWAYS_APIKEY']) ? $_SERVER['TIDEWAYS_APIKEY'] : ini_get("tideways.api_key"),
'sample_rate' => isset($_SERVER['TIDEWAYS_SAMPLERATE']) ? intval($_SERVER['TIDEWAYS_SAMPLERATE']) : (ini_get("tideways.sample_rate") ?: 0),
'collect' => isset($_SERVER['TIDEWAYS_COLLECT']) ? $_SERVER['TIDEWAYS_COLLECT'] : (ini_get("tideways.collect") ?: self::MODE_PROFILING),
'monitor' => isset($_SERVER['TIDEWAYS_MONITOR']) ? $_SERVER['TIDEWAYS_MONITOR'] : (ini_get("tideways.monitor") ?: self::MODE_BASIC),
'triggered' => self::MODE_FULL,
'log_level' => ini_get("tideways.log_level") ?: 0,
'service' => isset($_SERVER['TIDEWAYS_SERVICE']) ? $_SERVER['TIDEWAYS_SERVICE'] : ini_get("tideways.service"),
'framework' => isset($_SERVER['TIDEWAYS_FRAMEWORK']) ? $_SERVER['TIDEWAYS_FRAMEWORK'] : ini_get("tideways.framework"),
);
$options = array_merge($defaults, $options);
if (strlen((string)$options['api_key']) === 0) {
return;
}
self::$logLevel = $options['log_level'];
self::init($options['api_key'], $options);
self::decideProfiling($options['sample_rate'], $options);
}
/**
* Enable the profiler in the given $mode.
*
* @param string $mode
* @return void
*/
private static function enableProfiler($mode)
{
self::$mode = $mode;
if (self::$extension === self::EXTENSION_TIDEWAYS && (self::$mode !== self::MODE_DISABLED)) {
switch (self::$mode) {
case self::MODE_FULL:
$flags = 0;
break;
case self::MODE_PROFILING:
$flags = TIDEWAYS_FLAGS_NO_SPANS;
break;
case self::MODE_TRACING:
$flags = TIDEWAYS_FLAGS_NO_HIERACHICAL;
break;
default:
$flags = TIDEWAYS_FLAGS_NO_COMPILE | TIDEWAYS_FLAGS_NO_USERLAND | TIDEWAYS_FLAGS_NO_BUILTINS;
break;
}
self::$currentRootSpan = new \Tideways\Traces\TwExtensionSpan(0);
tideways_enable($flags, self::$defaultOptions);
if (($flags & TIDEWAYS_FLAGS_NO_SPANS) === 0) {
foreach (self::$defaultOptions['watches'] as $watch => $category) {
tideways_span_watch($watch, $category);
}
foreach (self::$defaultOptions['callbacks'] as $function => $callback) {
tideways_span_callback($function, $callback);
}
}
self::log(2, "Starting tideways extension for " . self::$trace['apiKey'] . " with mode: " . $mode);
} elseif (self::$extension === self::EXTENSION_XHPROF && (self::$mode & self::MODE_PROFILING) > 0) {
\Tideways\Traces\PhpSpan::clear();
self::$currentRootSpan = new \Tideways\Traces\PhpSpan(0, 'app');
self::$currentRootSpan->startTimer();
xhprof_enable(0, self::$defaultOptions);
self::log(2, "Starting xhprof extension for " . self::$trace['apiKey'] . " with mode: " . $mode);
} else {
\Tideways\Traces\PhpSpan::clear();
self::$currentRootSpan = new \Tideways\Traces\PhpSpan(0, 'app');
self::$currentRootSpan->startTimer();
self::log(2, "Starting non-extension based tracing for " . self::$trace['apiKey'] . " with mode: " . $mode);
}
}
/**
* Check if headers, cookie or environment variables for a developer trace
* are present. This method does not validate if the passed information is
* actually valid for the current API Key.
*
* @return bool
*/
public static function containsDeveloperTraceRequest()
{
if (isset($_SERVER['HTTP_X_TIDEWAYS_PROFILER']) && is_string($_SERVER['HTTP_X_TIDEWAYS_PROFILER'])) {
return true;
} else if (isset($_SERVER['TIDEWAYS_SESSION']) && is_string($_SERVER['TIDEWAYS_SESSION'])) {
return true;
} else if (isset($_COOKIE['TIDEWAYS_SESSION']) && is_string($_COOKIE['TIDEWAYS_SESSION'])) {
return true;
} else if (isset($_GET['_tideways']) && is_array($_GET['_tideways'])) {
return true;
}
return false;
}
/**
* Decide in which mode to start collecting data.
*
* @param int $treshold (0-100)
* @param array $options
* @return int
*/
private static function decideProfiling($treshold, array $options = array())
{
$vars = array();
$type = null;
$tidewaysReferenceId = null;
if (isset($_SERVER['HTTP_X_TIDEWAYS_PROFILER']) && is_string($_SERVER['HTTP_X_TIDEWAYS_PROFILER'])) {
parse_str($_SERVER['HTTP_X_TIDEWAYS_PROFILER'], $vars);
$type = 'header X-Tideways-Profiler';
$tidewaysReferenceId = isset($_SERVER['HTTP_X_TIDEWAYS_REF']) ? $_SERVER['HTTP_X_TIDEWAYS_REF'] : null;
} else if (isset($_SERVER['TIDEWAYS_SESSION']) && is_string($_SERVER['TIDEWAYS_SESSION'])) {
parse_str($_SERVER['TIDEWAYS_SESSION'], $vars);
$type = 'environment variable TIDEWAYS_SESSION';
$tidewaysReferenceId = isset($_SERVER['TIDEWAYS_REF']) ? $_SERVER['TIDEWAYS_REF'] : null;
} else if (isset($_COOKIE['TIDEWAYS_SESSION']) && is_string($_COOKIE['TIDEWAYS_SESSION'])) {
parse_str($_COOKIE['TIDEWAYS_SESSION'], $vars);
$type = 'cookie TIDEWAYS_SESSION';
$tidewaysReferenceId = isset($_COOKIE['TIDEWAYS_REF']) ? $_COOKIE['TIDEWAYS_REF'] : null;
} else if (isset($_GET['_tideways']) && is_array($_GET['_tideways'])) {
$vars = $_GET['_tideways'];
$type = 'GET parameter';
}
if (isset($_SERVER['TIDEWAYS_DISABLE_SESSIONS']) && $_SERVER['TIDEWAYS_DISABLE_SESSIONS']) {
$vars = array();
}
if (isset($vars['hash'], $vars['time'], $vars['user'], $vars['method'])) {
$message = 'method=' . $vars['method'] . '&time=' . $vars['time'] . '&user=' . $vars['user'];
self::log(3, "Found explicit trigger trace parameters in " . $type);
if (hash_hmac('sha256', $message, md5(self::$trace['apiKey'])) === $vars['hash']) {
if ($vars['time'] < time()) {
self::log(1, "trigger trace request with " . $type . " is authenticated, but signature is too old: " . $vars['time'] . " < " . time());
self::$mode = self::MODE_DISABLED;
return;
}
if (self::$logLevel >= 2) {
$location = "unknown";
$backtrace = debug_backtrace();
for ($i = count($backtrace) - 1; $i >= 0; $i--) { // find the last call location before going into Tideways\Profiler
if (isset($backtrace[$i-1]['class']) && $backtrace[$i-1]['class'] === "Tideways\\Profiler") {
$location = isset($backtrace[$i]['file']) ? $backtrace[$i]['file'] : '';
$location .= (':' . (isset($backtrace[$i]['line']) ? $backtrace[$i]['line'] : ''));
break;
}
}