Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 92
0.00% covered (danger)
0.00%
0 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
ProfilerXhprof
0.00% covered (danger)
0.00%
0 / 92
0.00% covered (danger)
0.00%
0 / 9
1122
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
42
 getXhprofData
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 scopedProfileIn
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 close
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 shouldExclude
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
72
 getFunctionStats
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
90
 getOutput
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getFunctionReport
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
6
 getRawData
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Copyright 2014 Wikimedia Foundation and contributors
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 */
8
9/**
10 * Profiler that captures all function calls from the XHProf PHP extension.
11 *
12 * This extension can be installed via PECL or your operating system's package manager.
13 * This also supports the Tideways-XHProf PHP extension.
14 *
15 * @ingroup Profiler
16 * @see $wgProfiler
17 * @see https://php.net/xhprof
18 * @see https://github.com/tideways/php-xhprof-extension
19 */
20class ProfilerXhprof extends Profiler {
21    /**
22     * @var XhprofData|null
23     */
24    protected $xhprofData;
25
26    /**
27     * Profiler for explicit, arbitrary, frame labels
28     * @var SectionProfiler
29     */
30    protected $sprofiler;
31
32    /**
33     * @see $wgProfiler
34     * @param array $params Associative array of parameters:
35     *  - int flags: Bitmask of constants from the XHProf or Tideways-XHProf extension
36     *    that will be passed to its enable function,
37     *    such as `XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY | XHPROF_FLAGS_NO_BUILTINS`.
38     *    With Tideways-XHProf, use `TIDEWAYS_XHPROF_FLAGS_*` instead.
39     *  - bool running: If true, it is assumed that the enable function was already
40     *    called. The `flags` option is ignored in this case.
41     *    This exists for use with a custom web entrypoint from which the profiler
42     *    is started before MediaWiki is included.
43     *  - array include: If set, only function names matching a pattern in this
44     *    array will be reported. The pattern strings will be matched using
45     *    the PHP fnmatch() function.
46     *  - array exclude: If set, function names matching an exact name in this
47     *    will be skipped over by XHProf. Ignored functions become transparent
48     *    in the profile. For example, `foo=>ignored=>bar` becomes `foo=>bar`.
49     *    This option is backed by XHProf's `ignored_functions` option.
50     *
51     *    **Note:** The `exclude` option is not supported in Tideways-XHProf.
52     */
53    public function __construct( array $params = [] ) {
54        parent::__construct( $params );
55
56        // See T180183 and T247332 for why we need the 'running' option.
57        if ( empty( $params['running'] ) ) {
58            $flags = $params['flags'] ?? 0;
59            if ( function_exists( 'xhprof_enable' ) ) {
60                $options = isset( $params['exclude'] )
61                    ? [ 'ignored_functions' => $params['exclude'] ]
62                    : [];
63                xhprof_enable( $flags, $options );
64            } elseif ( function_exists( 'tideways_xhprof_enable' ) ) {
65                if ( isset( $params['exclude'] ) ) {
66                    throw new RuntimeException( 'The exclude option is not supported in tideways_xhprof' );
67                }
68                tideways_xhprof_enable( $flags );
69            } else {
70                throw new RuntimeException( 'Neither xhprof nor tideways_xhprof is installed' );
71            }
72        }
73
74        $this->sprofiler = new SectionProfiler();
75    }
76
77    /**
78     * @return XhprofData
79     */
80    public function getXhprofData() {
81        if ( !$this->xhprofData ) {
82            if ( function_exists( 'xhprof_disable' ) ) {
83                $data = xhprof_disable();
84            } elseif ( function_exists( 'tideways_xhprof_disable' ) ) {
85                $data = tideways_xhprof_disable();
86            } else {
87                throw new RuntimeException( 'Neither xhprof nor tideways_xhprof is installed' );
88            }
89            $this->xhprofData = new XhprofData( $data, $this->params );
90        }
91        return $this->xhprofData;
92    }
93
94    /** @inheritDoc */
95    public function scopedProfileIn( $section ): ?SectionProfileCallback {
96        $key = 'section.' . ltrim( $section, '.' );
97        return $this->sprofiler->scopedProfileIn( $key );
98    }
99
100    /**
101     * No-op for xhprof profiling.
102     */
103    public function close() {
104    }
105
106    /**
107     * Check if a function or section should be excluded from the output.
108     *
109     * @param string $name Function or section name.
110     * @return bool
111     */
112    private function shouldExclude( $name ) {
113        if ( $name === '-total' ) {
114            return true;
115        }
116        if ( !empty( $this->params['include'] ) ) {
117            foreach ( $this->params['include'] as $pattern ) {
118                if ( fnmatch( $pattern, $name, FNM_NOESCAPE ) ) {
119                    return false;
120                }
121            }
122            return true;
123        }
124        if ( !empty( $this->params['exclude'] ) ) {
125            foreach ( $this->params['exclude'] as $pattern ) {
126                if ( fnmatch( $pattern, $name, FNM_NOESCAPE ) ) {
127                    return true;
128                }
129            }
130        }
131        return false;
132    }
133
134    /** @inheritDoc */
135    public function getFunctionStats() {
136        $metrics = $this->getXhprofData()->getCompleteMetrics();
137        $profile = [];
138
139        $main = null; // units in ms
140        foreach ( $metrics as $fname => $stats ) {
141            if ( $this->shouldExclude( $fname ) ) {
142                continue;
143            }
144            // Convert elapsed times from μs to ms to match interface
145            $entry = [
146                'name' => $fname,
147                'calls' => $stats['ct'],
148                'real' => $stats['wt']['total'] / 1000,
149                '%real' => $stats['wt']['percent'],
150                'cpu' => ( $stats['cpu']['total'] ?? 0 ) / 1000,
151                '%cpu' => $stats['cpu']['percent'] ?? 0,
152                'memory' => $stats['mu']['total'] ?? 0,
153                '%memory' => $stats['mu']['percent'] ?? 0,
154                'min_real' => $stats['wt']['min'] / 1000,
155                'max_real' => $stats['wt']['max'] / 1000
156            ];
157            $profile[] = $entry;
158            if ( $fname === 'main()' ) {
159                $main = $entry;
160            }
161        }
162
163        // Merge in all of the custom profile sections
164        foreach ( $this->sprofiler->getFunctionStats() as $stats ) {
165            if ( $this->shouldExclude( $stats['name'] ) ) {
166                continue;
167            }
168
169            // @note: getFunctionStats() values already in ms
170            $stats['%real'] = $main['real'] ? $stats['real'] / $main['real'] * 100 : 0;
171            $stats['%cpu'] = $main['cpu'] ? $stats['cpu'] / $main['cpu'] * 100 : 0;
172            $stats['%memory'] = $main['memory'] ? $stats['memory'] / $main['memory'] * 100 : 0;
173            $profile[] = $stats; // assume no section names collide with $metrics
174        }
175
176        return $profile;
177    }
178
179    /**
180     * Returns a profiling output to be stored in debug file
181     *
182     * @return string
183     */
184    public function getOutput() {
185        return $this->getFunctionReport();
186    }
187
188    /**
189     * Get a report of profiled functions sorted by inclusive wall clock time
190     * in descending order.
191     *
192     * Each line of the report includes this data:
193     * - Function name
194     * - Number of times function was called
195     * - Total wall clock time spent in function in microseconds
196     * - Minimum wall clock time spent in function in microseconds
197     * - Average wall clock time spent in function in microseconds
198     * - Maximum wall clock time spent in function in microseconds
199     * - Percentage of total wall clock time spent in function
200     * - Total delta of memory usage from start to end of function in bytes
201     *
202     * @return string
203     */
204    protected function getFunctionReport() {
205        $data = $this->getFunctionStats();
206        usort( $data, static function ( $a, $b ) {
207            return $b['real'] <=> $a['real']; // descending
208        } );
209
210        $width = 140;
211        $nameWidth = $width - 65;
212        $format = "%-{$nameWidth}s %6d %9d %9d %9d %9d %7.3f%% %9d";
213        $out = [];
214        $out[] = sprintf( "%-{$nameWidth}s %6s %9s %9s %9s %9s %7s %9s",
215            'Name', 'Calls', 'Total', 'Min', 'Each', 'Max', '%', 'Mem'
216        );
217        foreach ( $data as $stats ) {
218            $out[] = sprintf( $format,
219                $stats['name'],
220                $stats['calls'],
221                $stats['real'] * 1000,
222                $stats['min_real'] * 1000,
223                $stats['real'] / $stats['calls'] * 1000,
224                $stats['max_real'] * 1000,
225                $stats['%real'],
226                $stats['memory']
227            );
228        }
229        return implode( "\n", $out );
230    }
231
232    /**
233     * Retrieve raw data from xhprof
234     * @return array
235     */
236    public function getRawData() {
237        return $this->getXhprofData()->getRawData();
238    }
239}