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