Open PHP-MyProfiler

Robin Schumacher, MySQL’s Director of Product Management explains about the MySQL Query Profiler through his article on Using the New MySQL Query Profiler. At first glance I saw it was a good thing, and when I went deep to my dismay I found that the profile information was stored into an in memory table. Which means profile information would be lost when a session is closed. Well I was boiling my brains over the desire to profile applications which were live. And about a couple of days later, it struck my brains, that in any php application, if we open a connection to a database, normally the subsequent requests with the same credentials would return the active connection than opening a new connection. Though a new connection can be forced. And with all these information and the documentation on MySQL Developer Resources, I thought about writing one php snippet which would help me do sql profiling, and get the analysis in a colourful format.
Open PHP MyProfiler is just a trial to run query profiling on a php-mysql application, without changing the architecture too much. The profiler is open and downloadable, though the analzer, is just a mockup or a bare one and not yet ripe to be opened up. Any one who needs to do the analysis could make use of the same by downloading the profiler, and implementing with their code. The profiler would create logs depending on hostname and date. upload the profile logs to our Profile Sampler and you should be able to see the full profile of your application. Analyze your profile logs by going here.

Integration into an application should be quite simple, as including into the header or config, or just any where after the database configuration is defined, and then immediately creating a global $profiler. In the footer, or where any database activities are over, just call the $profiler->log() method. Though for some open packages there are some quirks, most of the applications this should be enough. Normally php would be getting the last open connection with the same parameters. Like for instance the wordpress, in wp-db.php, the connection request forces a new connection always. Just for profiling in some cases, I had to change this code.

Basically we start a connection to the database, and set the session variable profiling=1, and the profiling_history_size=100 which is the maximum. Means the profiler will work only for applications which do a maximum of 100 queries per instance of execution. The wordpress suite with some simple plugins can attain upto 75 queries and above. Then just before tearing down the connection, we collect all the profile information, serialize and store into a text file. There is a commercial version planned which would use curl to post each connection information directly to a central server, where the analysis and parsing would be done. The text file should be submitted to our profile sampler to view the profile information with color coding, though the color scale is a bit too colorful. Wrote it as a php5 class, since that would be eaiser to maintain.

Update
As Fernando Ipar has summarized in his comment, we have a resemblance in the final outcome, where as his solution which is described in his article Using MySQL Proxy to benchmark query performance, inclines more towards having greater system administration knowledge, and requires installation of MySQL Proxy. And as he has commented, my project Open PHP-MyProfiler would make it simple to be used on shared hosting accounts. While this simplicity does make way for a handicap, and that is the limitation of the profiles. Page instances which run more than 100 queries would end up providing us with the last 100 query performance only. As of today the coders in our lab has found one feature, since the profile entries are logged related to a single url, they could identify a lot of unnecessary queries in many pages.

Update (Feb 12)
As Wimr has commented, I did miss out on the constant PROFILE_ONLY, and this was just to make sure we got only profiles from a single IP. And we could make sure that the profiling was done on the areas which we needed it to be done.

<?php/***
* parameter $log should be a directory with the trailing slash, since the logs would be real heavy
* and as of now the directory should be writable by the webserver process..
* a file will be created under the directory foreach host with value in $_SERVER['HTTP_HOST']
*/class phpMyProfiler{
private $link;
private $error;
private $log;

Since a lot of developers have switched to the improved library, mysqli the old version did not support the mysqli. Due to popular demand, and requirement we updated the profiler with necessary mods and the improved version is available for download here. For the benefit of usage, the profiling should happen on the same connection resource, and a new method phpMyProfiler::setLink() is provided which takes one parameter byRef the mysqli connection resource. We had to retain the compatiablity, since most of our coders at Saturn were familiar with the last version.phpMyProfiler(i) (1599)

News logged at php|architect
Beth Tucker Long, the Editor In Chief of php|architect magazine has logged a News about PhpMyProfiler on March 12, 2010. Read the words from the news page.

Profile Sampler
Due to a couple of compromising situations on my godaddy hosting, I was forced to disable some features of php and it seems that the hosted version of profile-sampler does not work. To facilitate the sampling, one can download the sampler and use it on his own web server or localhost. Download the sampler PHP-MyProfiler Sampler (745)

WordPress Plugin
The profiler and sampler has been bundled into a single download, but is now two wordpress plugins. Though this has issues that this will be plugged into the wordpress flow after init and that logging is done on shutdown hook, some of the database calls are never logged. Still that is not an issue as mostly slowness would be caused by database calls from the theme and plugins. Note that logging may make system more slow and this is for identifying the bottlenecks and should never be left on for long times. Features like Log requests from IP, Log requests from IP to specific URL, Enable/Disable, Log Frequency are in the wishlist. Currently when you enable, the profiler starts logging, and creates new file for every hour. This is stored into the UPLOAD_DIR/wp_php_my_profiler with <Year-month-date-hour>.log as filename, and posted into the $wpdb-posts table with post_status = private, and post_type = profiler_log, Once logging is done, and before going for analysis, better deactivate the Profiler. Log Analyzer creates a menu entry in the admin side, and shows the logs from the $wpdb->posts table with the above properties in a tabular form, with actions ‘Analyze’ and ‘Delete’. The plugin is provided for advanced users and debuggers to find issues and bottlenecks in their plugins or themes. Download the plugin PHP MyProfiler Wordpress Plugin (1346)

CodeIgniter Adoption
Recently at Saturn we have started to use CodeIgniter due to developers as well as clients. Some projects have been transferred to us for further maintenance which was also developed on top of CodeIgniter, which needed auditing. The outcome is that I could not resist creating a port of the popular Open PHP-MyProfiler such that it can be included into the CodeIgniter workflow without any hindrance. CodeIgniter gurus may be skeptical about extending the CI_Model for this purpose whereas the overall function would have been better off as a library. This override from best practices are just for utilizing the configuration from the system as well as creating a connection to the database with the same credentials. Also the model can be loaded well ahead of system initialization through autoloader configuration. This will require one custom configuration profiler_log which can be added to any of the config files like $config['profiler_log'] = '/tmp/';. Only that this should be a valid directory where the webserver can write files onto. On shared hosts, a new directory can be created for the same purpose. Analyzer is not built as a CodeIgniter port since the standard one is enough for analyzing the logs created by this one also. Though the download is named as CI_phpmyprofiler.php.zip, the model class is phpmyprofiler, so please be aware to rename the file if the unzip did not get it right. Open PHP-MyProfiler (434)

@soussou97
The answer is written in my post, anyway to repeat the stuff.. “Integration into an application should be quite simple, as including into the header or config, or just any where after the database configuration is defined, and then immediately creating a global $profiler” with the same parameters that your scripts use to connect to the database. Should make sure that the connection your existing code makes is not forcing a new connection on each invokation.

I had a go with this class but I can’t get any info at all from ‘show profiles’ query… if I do a var_dump($data) in function log() I would get this:
array(2) { ["instance"]=> array(2) { ["timestamp"]=> int(1288283475) ["request"]=> string(18) “/profiler/test.php” } ["profiles"]=> NULL }

at the end of __contructor I added:
mysqli_query($this->link,”SELECT 1+1″);
just to make sure there is an executed query

No errors until this point, but the code seems not to go further than the first if statements. If I delete these if/return lines, the code gives me this error:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /usr/local/hosting/isgpmng/incoming/class/profiler/class.profiler.php on line 35

And the file or path should be writable by the webserver process. But none of this is your error case, I think the mysql does not provide profiling support or may be it is started with profiler disabled.

I was puzzled by the “PROFILE_ONLY” variable at the beginning of the script that is explained nowhere. I had to delete its tests.

Then when I uploaded on the sampler page I got a puzzling screen as wasn’t sure about the difference between the three input fields Upload File, Remote File and Local File. I tried upload and local but I got only empty screens as a result.

If I can help to maintain this code please tell me. This could be a very useful tool for many people.

@WimR
Sorry that I missed it, PROFILE_ONLY was defined when we first had to use it on a production environment, and did not want all the requests to be profiled. Just defined the PROFILE_ONLY with our own public IP and did the sampling.
I will send you the sampler code, the file uploads does not work here, since I had a scary hack some time back, and certain features of php is being restricted now.

@jijutm
Thank you for the code and the explanation. I have two more questions:
– long url’s are not rendered completely. They seem to be cut off at around 280 characters. Is there anything one can do about that.
– the profiling table in Information_schema has also fields source_file and source_line. I wondered if these can be gotten somewhere too in the output.
I had a look for these things myself but I found it a bit too complicated for the moment.
Thanks, Wim

@WimR
It seems that the source_file and source_line are there along with that the source_function is also seen, without all these I thought it would not be quite useful. The source file is relative in some version, and in some other the width of this field is varchar(20). As is said here http://bugs.mysql.com/bug.php?id=59273, these were corrected and updated in 5.5 and 5.6. As of now it does not seem to be worth the trouble to pick these.
Meanwhile I could not reproduce the issue about long urls, since the url is captured from REQUEST_URI, all the url should be there. Could you send me a downloadable link to a profile log, or send me one as attachment, make it as con-size as you can. You should have my email id.

The PHP development team announces the immediate availability of PHP 5.6.29. This is a security release. Several security bugs were fixed in this release. All PHP 5.6 users are encouraged to upgrade to this version.For source downloads of PHP 5.6.29 please visit our downloads page, Windows source and binaries can be found on windows.php.net/download/. The […]

The PHP development team announces the immediate availability of PHP 7.1.0. This release is the first point release in the 7.x series.PHP 7.1.0 comes with numerous improvements and new features such asNullable typesVoid return typeIterable pseudo-typeClass constant visiblity modifiersSquare bracket syntax for list() and the ability to specify keys in list()Catching multiple exceptions typesMany more […]

The PHP development team announces the immediate availability of PHP 5.6.28. This is a security release. Several security bugs were fixed in this release. All PHP 5.6 users are encouraged to upgrade to this version.For source downloads of PHP 5.6.28 please visit our downloads page, Windows source and binaries can be found on windows.php.net/download/. The […]