Diferencia entre revisiones de «OPcache»

De MoodleDocs
(tidy up)
(tidy up)
 
(No se muestran 10 ediciones intermedias de 4 usuarios)
Línea 1: Línea 1:
{{Versiones|Esta página es acerca de OPcache '''para Moodle 3.5''' y más modernos. Para la documentación anterior,  vaya a '''[[34/OPcache]]''' y '''[[29/OPcache]]''' .}}{{Entorno}}
{{Versiones|Esta página es acerca de OPcache '''para Moodle 3.5''' y más modernos. Para la documentación anterior,  vaya a '''[[34/OPcache]]''' y '''[[29/OPcache]]''' .}}{{Entorno}}
La extensión estándar OPCache está altamente recomendada; desde Moodle 2.6, es la única solución soportada oficialmente por los desarrolladores de PHP. Los beneficios son aumento del desempeño y significativamente menor uso de memoria. Sin embargo, las extensiones para cacheo de ''opcode'' (incluyendo OPcache, eAccelerator y APC) no son compatibles con los servidores configurados para usar algunos tipos comunes de manejadores PHP de alta seguridad, tales como su PHP (que se emplea por defecto en servidores Linux WHM / cPanel ). Esto es muy común en servidores compartidos.


La extensión estándar OPCache está altamente recomendada; desde Moodle 2.6, es la única solución soportada oficialmente por los desarrolladores de PHP. Los beneficios son aumento del desempeño y significativamente menor uso de memoria. Sin embargo, las extensiones para cacheo de ''opcode'' (incluyendo OPcache, eAccelerator y APC) no son compatibles con los servidores configurados para usar algunos tipos comunes de manejadores PHP de alta seguridad, tales como suPHP (que se emplea por defecto en servidores Linux WHM / cPanel ). Esto es muy comun en servidores compartidos.
[[Archivo:ES_Opcache error.png|600px]]
==Instalación==
La extensión OPcache es distribuida como parte de PHP 5.5.0 y posteriores. Está disponible también para versiones estables más antiguas de PHP desde PECL bajo el nombre original ZendOPcache.


[[Archivo:ES_Opcache error.png|600px]]
'''NOTA: Si Usted está corriendo PHP 5.3 o 5.4 Usted puede ignorar con seguridad el mensaje de revisión del [[Entorno]] sobre OpCache. Sin embargo, [https://moodle.org/mod/forum/discuss.php?d=245885 se recomienda] que actualice PHP a 5.5 o posterior; debido a los muchos problemas descritos con PHP 5.2 y 5.3, donde el actualizar PHP resultó ser la solución más sencilla. '''
 
===Linux, macOS y otras plataformas similares a Linux===
 
Usted podría necesitar instalar un paquete específico, como por ejemplo en CentOS, Fedora o Red Hat: '''dnf install php-opcache'''. Si fuera necesario añada lo siguiente a  '''php.ini''' (los instaladores de paquetes podrían hacer esto automáticamente):
<code ini>
zend_extension=/full/path/to/opcache.so
</code>


==Instalación==
===Microsoft Windows===


La extensión OPcache es distribuída como parte de PHP 5.5.0 y posteriores. Está disponible también para versiones estables más antiguas de PHP desde PECL bajo el nombre original ZendOPcache.
La extensión '''php_opcache.dll''' está incluida en la carpeta '''ext''' dentro de [https://windows.php.net/download PHP for Windows binary downloads].
Para habilitarla añada lo siguiente a '''php.ini''':


'''NOTA: Si Usted está corriendo PHP 5.3 o 5.4 Usted puede ignorar con seguridad el mensaje de revisión del [[Entorno]] sobre OpCache. Sin embargo, [https://moodle.org/mod/forum/discuss.php?d=245885 se recomienda] que actualice PHP a 5.5 o posterior; debido a los muchos problemas descritos con PHP 5.2 y 5.3, donde el actualizar PHP resultó ser la solución más sencilla. '''
<code ini>
zend_extension=php_opcache.dll
</code>




==Configuración==
==Configuración==
Configuraciones en '''php.ini''' <syntaxhighlight lang="ini"> ('''PHP v5.0''')
[opcache]
zend_extension=php_opcache.dl;
opcache.enable=1;
opcache.memory_consumption=128;
opcache.max_accelerated_files=50000;
opcache.revalidate_freq=6;
;Requerido para Moodle
opcache.use_cwd=1;
opcache.validate_timestamps=1;
opcache.save_comments=1;
opcache.enable_file_override=0;


Configuraciones en PHP.ini :
;Si algo no funciona en Moodle
opcache.revalidate_path=1; Puede arreglar problemas con rutas include
opcache.mmap_base=0x20000000; (Windows only) fix OPcache crashes with event id 487


<code ini>
; Experimental for Moodle 2.6 and later
;opcache.fast_shutdown = 1
;opcache.enable_cli = 1 ; Speeds up CLI cron
;opcache.load_comments = 0 ; May lower memory use, might not be compatible with add-ons and other apps.
</syntaxhighlight>It's worth noting that in PHP v8.0 and above, many of these Opcache parameters have been updated (with some parameters being deprecated) and the defaults are now largely sufficient - you'll notice that memory_consumption, max_accelerated_files, use_cwd, validate_timestamps & enable_file_override default to the suggested values above. For PHP v8.0, the default configuration looks like the following:<syntaxhighlight lang="ini">
[opcache]
[opcache]
zend_extension = php_opcache.dll
; Determines if Zend OPCache is enabled
opcache.enable = 1
;opcache.enable=1
opcache.memory_consumption = 128
opcache.max_accelerated_files = 10000
opcache.revalidate_freq = 60


; Requerido para Moodle
; Determines if Zend OPCache is enabled for the CLI version of PHP
opcache.use_cwd = 1
;opcache.enable_cli=0
opcache.validate_timestamps = 1
opcache.save_comments = 1
opcache.enable_file_override = 0


; Si algo no funciona en Moodle
; The OPcache shared memory storage size.
;opcache.revalidate_path = 1 ; Puede arreglar problemas con rutas ''include''
;opcache.memory_consumption=128
;opcache.mmap_base = 0x20000000 ; (Windows only) fix OPcache crashes with event id 487


; Experimental para Moodle 2.6 y posteriores
; The maximum number of keys (scripts) in the OPcache hash table.
;opcache.fast_shutdown = 1
; Only numbers between 200 and 1000000 are allowed.
;opcache.enable_cli = 1 ; Acelera CLI cron
;opcache.max_accelerated_files=10000
;opcache.load_comments = 0 ; Puede disminuir el uso de memoria, puede no ser compatible con complementos y otras apps
 
</code>
; When this directive is enabled, the OPcache appends the current working
; directory to the script key, thus eliminating possible collisions between
; files with the same name (basename). Disabling the directive improves
; performance, but may break existing applications.
;opcache.use_cwd=1
 
; When disabled, you must reset the OPcache manually or restart the
; webserver for changes to the filesystem to take effect.
;opcache.validate_timestamps=1
 
; How often (in seconds) to check file timestamps for changes to the shared
; memory storage allocation. ("1" means validate once per second, but only
; once per request. "0" means always validate)
;opcache.revalidate_freq=2
 
; Enables or disables file search in include_path optimization
;opcache.revalidate_path=0
 
; Allow file existence override (file_exists, etc.) performance feature.
;opcache.enable_file_override=0
</syntaxhighlight>Things that you'd consider changing in PHP v8.0 and above to match the original script are:


Al usar plataformas no-Windows, Usted tiene que usar la configuración de ''zend_extension'' para cargar la extensión OPcache en PHP al añadirla a php.ini:
* revalidate_freq (defaults to 2, 60 was the previously recommended value)
<code ini>
* enable_cli (defaults to 0, 1 was previously recommended)
zend_extension=/full/path/to/opcache.so
</code>




Al usar IIS Usted necesitará PHP 5.5 y Usted necesitará añadir la extensión para opcache bajo de la sección de ''ExtensionList'' del archivo php.ini.  Para PHP 5.3 y 5.4 Usted puede descargar los archivos binarios por separado desde [http://windows.php.net/downloads/pecl/releases/opcache]  y Usted también necesitará escribir la ruta absoluta completa al dll del módulo en php.ini.


<code ini>
Personally after the last update to Moodle 4.3 (running PHP 8.2 on our server), I opted to simply leave the defaults running for testing - as far as we can tell, we haven't seen a performance hit, though it's worth noting the installation I manage/work with is only ~100 users, compared with the multiple thousands other Moodle installations contend with - so it's really a case of see what best suits your Organization. Fortunately the two options above are relatively simple :)
[ExtensionList]
...
zend_extension=php_opcache.dll
</code>


Below are a couple of descriptions for two of the above parameters:
; memory_consumption
; memory_consumption
From: [http://blog.jpauli.tech/2015/03/05/opcache.html PHP's OPCache extension review]
From: [http://blog.jpauli.tech/2015-03-05-opcache-html/ PHP's OPCache extension review]
*''The size of the memory segment can be told using the opcache.memory_consumption INI setting (Megabytes). Size it big, don't hesitate to give space. Never ever run out of shared memory space, if you do, you will lock your processes, we'll get back to that later.''
*''The size of the memory segment can be told using the opcache.memory_consumption INI setting (Megabytes). Size it big, don't hesitate to give space. Never ever run out of shared memory space, if you do, you will lock your processes, we'll get back to that later.''


*''Size the shared memory segment according to your needs, don't forget that a production server dedicated to PHP processes may bundle several dozens of Gigabytes of memory, just for PHP. Having a 1Gb shared memory segment (or more) is not uncommon, it will depend on your needs, but if you use a modern application stack, aka framework based, with lots of dependencies etc... , then use at least 1Gb of shared memory.''
*''Size the shared memory segment according to your needs, don't forget that a production server dedicated to PHP processes may bundle several dozens of Gigabytes of memory, just for PHP. Having a 1Gb shared memory segment (or more) is not uncommon, it will depend on your needs, but if you use a modern application stack, aka framework based, with lots of dependencies etc... , then use at least 1Gb of shared memory.''


Having that in mind, set opcache.memory_consumption to a value high enough to avoid filling it up (as long as your RAM usage allows you to), and then monitor the OPCache to adjust that value to its optimal size. As the total size of the PHP files in a standard Moodle 3.6 is almost 90MB, setting this value higher than that can be a good idea. Take into account that the PHP files of the plugins and those on the MoodleData folder (language pack files...) also count, so these values can be different on each installation. If you have several instances of Moodle you should multiply that value by the number of instances.
Having that in mind, set opcache.memory_consumption to a value high enough to avoid filling it up (as long as your RAM usage allows you to), and then monitor the OPCache to adjust that value to its optimal size. As the total size of the PHP files in a standard Moodle 4.3 is around 111MB, setting this value higher than that can be a good idea. Take into account that the PHP files of the plugins and those on the MoodleData folder (language pack files...) also count, so these values can be different on each installation. If you have several instances of Moodle you should multiply that value by the number of instances.


Tip: If using Linux, you can know the total size of the PHP files of a folder using this command:
Tip: If using Linux, you can know the total size of the PHP files of a folder using this command:
Línea 69: Línea 110:
; max_accelerated_files
; max_accelerated_files
From: [http://php.net/manual/en/opcache.configuration.php#ini.opcache.max-accelerated-files php.net max-accelerated-files]
From: [http://php.net/manual/en/opcache.configuration.php#ini.opcache.max-accelerated-files php.net max-accelerated-files]
*''The maximum number of keys (and therefore scripts) in the OPcache hash table. The actual value used will be the first number in the set of prime numbers { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 } that is greater than or equal to the configured value. The minimum value is 200. The maximum value is 100000 in PHP < 5.5.6, and 1000000 in later versions.''
*''The maximum number of keys (and therefore scripts) in the OPcache hash table. The actual value used will be the first number in the set of prime numbers { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987, 262237, 524521, 1048793 } that is greater than or equal to the configured value. The minimum value is 200. The maximum value is 1000000. Values outside of this range are clamped to the permissible range.''


Ya que Moodle 3.6 contiene casi 10.000 archivos PHP, arriba se recomienda que opcache.max_accelerated_files debería de ajustarse a 10000 ´para acomodar esto (16229 de hecho se usará para la explicación de arriba). Si Usted tiene varias instancias de Modlle Usted debrá multiplicar ese valor por el número de instancias.
As Moodle 4.3 contains more than 13.700 php files it is recommended above that opcache.max_accelerated_files should be set to 14000 to accommodate this (16229 will actually be used as per the explanation above). If you have several instances of Moodle you should multiply that value by the number of instances.


Si están instalados varios plugins adicionales, de forma tal que sus archivos PHP exceden de 16229 entonces debería  de usarse el siguiente valor apropiado para max_accelerated_files.
If many additional plugins are installed so that your total PHP files exceed 16229 then the next most suitable value for max_accelerated_files should be used.
Sugerncia: Si Usted está usando Linux, Usted puede conocer el número total de archivos PHP de su Moodle usando este comando:
Tip: If using Linux, you can know the total PHP files of your Moodle using this command:
<code ini>
<code ini>
find ./ -type f | grep -E ".*\.php$" | sed -e 's/.*\(\.[a-zA-Z0-9]*\)$/\1/' | sort | uniq -c | sort -n
find ./ -type f | grep -E ".*\.php$" | sed -e 's/.*\(\.[a-zA-Z0-9]*\)$/\1/' | sort | uniq -c | sort -n
</code>
</code>


 
==Plugin para la gestión de Opcache==
==Plugin para gestión de Opcache ==
[[File:ES_Opcache_management_message.png|400px]]
[[File:ES_Opcache_management_message.png|400px]]


Usted podría considerar instalar el plugin adicional de [https://moodle.org/plugins/tool_opcache Opcache management] - Plugin de Moodle que añade una Interfase Gráfica del Usuario para gestión de Opcache de PHP, una herramienta de Interfase de Línea de comando para reiniciar Opcache PHP y para revisar Nagios para PHP Opcache.
Usted podría considerar instalar el plugin adicional de [https://moodle.org/plugins/tool_opcache Opcache management] - Plugin de Moodle que añade una Interfase Gráfica del Usuario para gestión de Opcache de PHP, una herramienta de Interfase de Línea de comando para reiniciar Opcache PHP y para revisar Nagios para PHP Opcache.


[[File:Opcache management status.png|800px]]
[[File:Opcache management status.png|800px]]
Línea 90: Línea 130:
* [http://pecl.php.net/package/ZendOpcache PECL ZendOPcache]
* [http://pecl.php.net/package/ZendOpcache PECL ZendOPcache]
* [http://windows.php.net/downloads/pecl/releases/opcache/ Windows builds for PHP 5.3-5.4]
* [http://windows.php.net/downloads/pecl/releases/opcache/ Windows builds for PHP 5.3-5.4]
Forum discussions:
Forum discussions:
* Using Moodle [https://moodle.org/mod/forum/discuss.php?d=244133 OPcache: Memory Usage = 100% (is this good or bad?)]
* Using Moodle [https://moodle.org/mod/forum/discuss.php?d=244133 OPcache: Memory Usage = 100% (is this good or bad?)]

Revisión actual - 15:09 31 ene 2024

note icon.png Existe documentación diferente para varias versiones de Moodle: Esta página es acerca de OPcache para Moodle 3.5 y más modernos. Para la documentación anterior, vaya a 34/OPcache y 29/OPcache .

La extensión estándar OPCache está altamente recomendada; desde Moodle 2.6, es la única solución soportada oficialmente por los desarrolladores de PHP. Los beneficios son aumento del desempeño y significativamente menor uso de memoria. Sin embargo, las extensiones para cacheo de opcode (incluyendo OPcache, eAccelerator y APC) no son compatibles con los servidores configurados para usar algunos tipos comunes de manejadores PHP de alta seguridad, tales como su PHP (que se emplea por defecto en servidores Linux WHM / cPanel ). Esto es muy común en servidores compartidos.

ES Opcache error.png

Instalación

La extensión OPcache es distribuida como parte de PHP 5.5.0 y posteriores. Está disponible también para versiones estables más antiguas de PHP desde PECL bajo el nombre original ZendOPcache.

NOTA: Si Usted está corriendo PHP 5.3 o 5.4 Usted puede ignorar con seguridad el mensaje de revisión del Entorno sobre OpCache. Sin embargo, se recomienda que actualice PHP a 5.5 o posterior; debido a los muchos problemas descritos con PHP 5.2 y 5.3, donde el actualizar PHP resultó ser la solución más sencilla.

Linux, macOS y otras plataformas similares a Linux

Usted podría necesitar instalar un paquete específico, como por ejemplo en CentOS, Fedora o Red Hat: dnf install php-opcache. Si fuera necesario añada lo siguiente a php.ini (los instaladores de paquetes podrían hacer esto automáticamente): zend_extension=/full/path/to/opcache.so

Microsoft Windows

La extensión php_opcache.dll está incluida en la carpeta ext dentro de PHP for Windows binary downloads. Para habilitarla añada lo siguiente a php.ini:

zend_extension=php_opcache.dll


Configuración

Configuraciones en php.ini

 ('''PHP v5.0''')
[opcache] 
zend_extension=php_opcache.dl; 
opcache.enable=1;
opcache.memory_consumption=128;
opcache.max_accelerated_files=50000;
opcache.revalidate_freq=6;


;Requerido para Moodle

opcache.use_cwd=1; 
opcache.validate_timestamps=1; 
opcache.save_comments=1; 
opcache.enable_file_override=0;

;Si algo no funciona en Moodle
opcache.revalidate_path=1; Puede arreglar problemas con rutas include
opcache.mmap_base=0x20000000; (Windows only) fix OPcache crashes with event id 487

; Experimental for Moodle 2.6 and later
;opcache.fast_shutdown = 1
;opcache.enable_cli = 1 ; Speeds up CLI cron
;opcache.load_comments = 0 ; May lower memory use, might not be compatible with add-ons and other apps.

It's worth noting that in PHP v8.0 and above, many of these Opcache parameters have been updated (with some parameters being deprecated) and the defaults are now largely sufficient - you'll notice that memory_consumption, max_accelerated_files, use_cwd, validate_timestamps & enable_file_override default to the suggested values above. For PHP v8.0, the default configuration looks like the following:

[opcache]
; Determines if Zend OPCache is enabled
;opcache.enable=1

; Determines if Zend OPCache is enabled for the CLI version of PHP
;opcache.enable_cli=0

; The OPcache shared memory storage size.
;opcache.memory_consumption=128

; The maximum number of keys (scripts) in the OPcache hash table.
; Only numbers between 200 and 1000000 are allowed.
;opcache.max_accelerated_files=10000

; When this directive is enabled, the OPcache appends the current working
; directory to the script key, thus eliminating possible collisions between
; files with the same name (basename). Disabling the directive improves
; performance, but may break existing applications.
;opcache.use_cwd=1

; When disabled, you must reset the OPcache manually or restart the
; webserver for changes to the filesystem to take effect.
;opcache.validate_timestamps=1

; How often (in seconds) to check file timestamps for changes to the shared
; memory storage allocation. ("1" means validate once per second, but only
; once per request. "0" means always validate)
;opcache.revalidate_freq=2

; Enables or disables file search in include_path optimization
;opcache.revalidate_path=0

; Allow file existence override (file_exists, etc.) performance feature.
;opcache.enable_file_override=0

Things that you'd consider changing in PHP v8.0 and above to match the original script are:

  • revalidate_freq (defaults to 2, 60 was the previously recommended value)
  • enable_cli (defaults to 0, 1 was previously recommended)


Personally after the last update to Moodle 4.3 (running PHP 8.2 on our server), I opted to simply leave the defaults running for testing - as far as we can tell, we haven't seen a performance hit, though it's worth noting the installation I manage/work with is only ~100 users, compared with the multiple thousands other Moodle installations contend with - so it's really a case of see what best suits your Organization. Fortunately the two options above are relatively simple :)

Below are a couple of descriptions for two of the above parameters:

memory_consumption

From: PHP's OPCache extension review

  • The size of the memory segment can be told using the opcache.memory_consumption INI setting (Megabytes). Size it big, don't hesitate to give space. Never ever run out of shared memory space, if you do, you will lock your processes, we'll get back to that later.
  • Size the shared memory segment according to your needs, don't forget that a production server dedicated to PHP processes may bundle several dozens of Gigabytes of memory, just for PHP. Having a 1Gb shared memory segment (or more) is not uncommon, it will depend on your needs, but if you use a modern application stack, aka framework based, with lots of dependencies etc... , then use at least 1Gb of shared memory.

Having that in mind, set opcache.memory_consumption to a value high enough to avoid filling it up (as long as your RAM usage allows you to), and then monitor the OPCache to adjust that value to its optimal size. As the total size of the PHP files in a standard Moodle 4.3 is around 111MB, setting this value higher than that can be a good idea. Take into account that the PHP files of the plugins and those on the MoodleData folder (language pack files...) also count, so these values can be different on each installation. If you have several instances of Moodle you should multiply that value by the number of instances.

Tip: If using Linux, you can know the total size of the PHP files of a folder using this command: find ./ -type f -name "*.php" -printf "%s\n" | gawk -M '{t+=$1}END{print t}' | numfmt --to=iec

max_accelerated_files

From: php.net max-accelerated-files

  • The maximum number of keys (and therefore scripts) in the OPcache hash table. The actual value used will be the first number in the set of prime numbers { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987, 262237, 524521, 1048793 } that is greater than or equal to the configured value. The minimum value is 200. The maximum value is 1000000. Values outside of this range are clamped to the permissible range.

As Moodle 4.3 contains more than 13.700 php files it is recommended above that opcache.max_accelerated_files should be set to 14000 to accommodate this (16229 will actually be used as per the explanation above). If you have several instances of Moodle you should multiply that value by the number of instances.

If many additional plugins are installed so that your total PHP files exceed 16229 then the next most suitable value for max_accelerated_files should be used. Tip: If using Linux, you can know the total PHP files of your Moodle using this command: find ./ -type f | grep -E ".*\.php$" | sed -e 's/.*\(\.[a-zA-Z0-9]*\)$/\1/' | sort | uniq -c | sort -n

Plugin para la gestión de Opcache

ES Opcache management message.png

Usted podría considerar instalar el plugin adicional de Opcache management - Plugin de Moodle que añade una Interfase Gráfica del Usuario para gestión de Opcache de PHP, una herramienta de Interfase de Línea de comando para reiniciar Opcache PHP y para revisar Nagios para PHP Opcache.

Opcache management status.png

Vea también

Forum discussions: