Monday 7 October 2019

De-duplication and Opcache

As I now have a lot of Wordpress sites to look after (argh!) I wanted to see if I coiuld set them up to be a bit more efficient in memory. However due to the way Wordpress resolves the location of files, it would have required the wp-settings.php file to be almost completely replaced to set the paths in PHP. I wondered if I could use symlinks on the filesystem to achieve the same goal without hacking the code. The answer appears to be yes - here's the output from my test case:

Opcache and symlinks

This script includes the same file via different paths which use symlinks. The objective is determine whether this creates 1 or 2 entries in opcache - and hence whether I can run multiple Wordpress sites from the same files without rewriting the code

Include from linked1 : This is /var/www/html/myvhost/include/testsymlink.php
include from linked2 : This is /var/www/html/myvhost/include/testsymlink.php

/var/www/html/myvhost/include/testsymlink.php
Array
(
    [full_path] => /var/www/html/myvhost/include/testsymlink.php
    [hits] => 9
    [memory_consumption] => 736
    [last_used] => Mon Oct  7 10:31:53 2019
    [last_used_timestamp] => 1570444313
    [timestamp] => 1570443328
)
2 files included resolve to a single entry in opcache - yay!
Note that some caution is required when applying upgrades to the wordpress install!

Source code for this script

<?php
print "<h1>Opcache and symlinks</h1>";
print 
"<p>This script includes the same file via different paths which use symlinks. The objective is determine whether this creates 1 or 2 entries in opcache - and hence whether I can run multiple Wordpress sites from the same files without rewriting the code</p><p>\n";
print 
"Include from linked1 : ";
include 
"linked1/testsymlink.php";
print 
"include from linked2 : ";
include 
"linked2/testsymlink.php";

print 
"<pre>";
$data=opcache_get_status(true);
foreach (
$data['scripts'] as $script=>$sd) {
   if (
"testsymlink.php"==basename($script)) {
       print 
$script "\n";
       
print_r($sd);
   }
}
print 
"</pre>";

print 
"2 files included resolve to a single entry in opcache - yay!<br />\n";
print 
"Note that some caution is required when applying upgrades to the wordpress install!<br />\n";    
print 
"<h2>Source code for this script</h2>";
highlight_file(__FILE__);


2 comments:

  1. Note that this is not true de-duplication; if I had multiple files with exactly the same content, opcache would create an entry for each one. That might be a nice capability for some people but I can live without it for now.

    ReplyDelete
  2. Also its not a viable fix for multiple Wordpress sites where code frequently calls "realpath()" to determine the relative location of other content.

    ReplyDelete