realpath() to a happy Opcache

Tom Adam

PHP Execution Flow

  1. File loaded into memory
  2. PHP lexed and syntax analysed
  3. Tokens compiled into opcode
  4. Opcodes executed

Opcache Execution Flow

  1. Opcode loaded from memory
  2. Opcode executed

Opcache Config

# FPM / CLI
opcache.enable = 1
opcache.memory_consumption = ?
opcache.max_accelerated_files = ?
opcache.interned_strings_buffer = ?
opcache.save_comments = 0/1
opcache.fast_shutdown = 1

# CLI only
opcache.enable_cli = 1
opcache.file_cache = "/tmp/php-file-cache"
opcache.file_cache_only = 1
opcache.file_cache_consistency_checks = 1

Realpath

Realpath Cache

include('include.php');
print_r(realpath_cache_get());

[
    '/home/vagrant/./include.php' => [
        'key'      => 3250252058440589612,
        'is_dir'   => false,
        'realpath' => '/home/vagrant/include.php',
        'expires'  => 1470831105,
    ],
    '/home' => [
        'key'      => 4353355791257440477,
        'is_dir'   => true,
        'realpath' => '/home',
        'expires'  => 1470831105,
    ],
    '/home/vagrant' => [
        'key'      => 1412428085930400000,
        'is_dir'   => true,
        'realpath' => '/home/vagrant',
        'expires'  => 1470831105,
    ],
];
./b        => /a/b
/a/b/../c  => /a/c
/c -> /a/b => /a/b

Realpath Cache Config

realpath_cache_size = ?
realpath_cache_ttl = 0

Clearing the cache

clearstatcache(true);

Deployment Procedure

├─ current -> ../releases/20160803103000
└─ releases
   ├─ 20160803103000
   ├─ 20160802083000
   └─ 20160801093500
  1. Pull / upload to new release folder
  2. Pre-release tasks
  3. Symlink release to current
  4. Post-release tasks

Deploy Structure

Deployment Caching Issue

Realpath, Opcache and Deployment

current/index.php -> releases/1/index.php

# Deploy

current/index.php -> releases/2/index.php

# Realpath cache still contains releases/1/index.php for current/index.php.

Solutions

  • Multiple FPM masters and load balancer
  • (Un-)Graceful restart
  • Immutable Infrastructure
  • Docker

Opcache Further Reading

  • https://www.scribd.com/document/18171982/PHP-Compiler-Internals
  • http://jpauli.github.io/2015/03/05/opcache.html
  • https://blog.appdynamics.com/php/why-every-php-application-should-use-an-opcache/

Questions?

realpath() to a happy Opcache

By tomadam

realpath() to a happy Opcache

  • 1,238