Clear Varnish cache via PHP: a Drupal 7 proof of concept

Using Varnish as reverse proxy or proxy is an useful approach to reduce the load of webservers like Apache.

In Drupal 7 I’ve to clear the varnish cache of a specific domain when Drupal caches are globally cleared. Drupal has the right hook invoked when cache are cleared:

Now this piece of code simply adds the current domain to a ASCII text file on /var/www/varnishdomains2cleardir/varnishdomains2clear.

Preparing the file to the write

On CentOS you have to add /var/www/varnishdomains2cleardir to the httpd-writable directories list using:

Now the empty file is ready to be written by your hook_flush_caches() implementation. Now enable the clearvarnishcache module and clear the cache to write the current domain name to the file.

hook_flush_caches()

The clear varnish cache script

To clear the varnish cache you usually have to be logged as root using the command varnishadm. Here a script that will read the domains file written above, clear the varnish cache for that domain and then remove the domains lines.

varnishadm

Make this script as executable .sh file using chmod a+x on it. If you run the bash script, varnish cache for files on the domains list will be cleared. It’s not so useful when using the Drupal UI so we should schedule this task periodically, e.g. every minute.

Scheduling the varnish clear cache

Here the crontab entry for execute the script every minute:

The steps

User clear Drupal cache hook_flush_caches() is invoked: the domains list file is written clear varnish cache script is launched by root every minute for each domain in the list, varnish cache is cleared

hook_flush_caches()

This is the end of this proof of concept. The code wasn’t tested against attacks so please comment if you have any suggestion to improve it. I’m not very fond of the idea of a php script writing something read by a bash script but this is the less problematic solution I found for this case.

https://web.archive.org/web/20150401000000*/https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_flush_caches/7

https://web.archive.org/web/20150401000000*/https://www.varnish-cache.org/docs/3.0/reference/varnishadm.html

https://web.archive.org/web/20150401000000*/https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_flush_caches/7

Proxied content from gemini://chirale.org/2015-04-01_1249.gmi (external content)

Gemini request details:

Original URL
gemini://chirale.org/2015-04-01_1249.gmi
Status code
Success
Meta
text/gemini; charset=utf-8
Proxied by
kineto

Be advised that no attempt was made to verify the remote SSL certificate.