Page MenuHomePhabricator

Migrate configuration of www.wikimedia.it from mod_php to PHP-FPM (with dedicated Unix user, etc.) - cover PHP 7.4 + 8.1
Closed, ResolvedPublic2 Estimated Story Points

Assigned To
Authored By
valerio.bozzolan
Jun 7 2023, 5:19 PM
Referenced Files
F37111004: Errore PSW.png
Jun 21 2023, 8:11 AM
Restricted File
Jun 13 2023, 8:04 AM
Tokens
"Like" token, awarded by valerio.bozzolan.

Description

It would be nice to migrate the VirtualHost of www.wikimedia.it from the legacy configuration of mod_php to a dedicated pool of PHP-FPM.

This is the current/old VirtualHost in our repository:

https://gitlab.wikimedia.org/repos/wikimedia-it/wmit-infrastructure/-/blob/f322bcd06f9dd301ee87cee2bde8d8a5d7855e36/servers/intreccio/conf/apache2/sites-available/it-wikimedia-www-ssl.conf

This is the current/old location on the filesystem:

/etc/wmit-infrastructure/servers/intreccio/conf/apache2/sites-available/it-wikimedia-www-ssl.conf

The new configuration should be probably created in this location (note that there are some useful files nearby to copy as inspiration):

/etc/wmit-infrastructure/servers/intreccio/conf/php/7.3/fpm/pool.d/www.conf

Suggested specifications:

TopicValueNotes
Proposed dedicated unix user namewmit-www
Proposed listen to socket VS portsocketWhy not. A socket works and reduces proxy overhead. We love the planet 💚
Proposed socket file name/run/php/php7.3-fpm-www.sock

That's all!


Pro:

  • mod_php is damn more simple to adopt than PHP-FPM
  • it would be easier to discover if the process is doing something nasty since it's a dedicated Unix user and not www-data
  • it's easier to separate privileges
  • probably it could improve responsiveness, but there is no evidence

Cons:

  • We may need to occupy a new port (e.g. 900X)
  • PHP-FPM allows better ITSec standards (avoid to run every PHP process as www-data)
  • we need to review privileges in order to do not allow anything else than wmit-www

Event Timeline

valerio.bozzolan triaged this task as Low priority.
valerio.bozzolan updated the task description. (Show Details)
valerio.bozzolan moved this task from Backlog to 🌐 Web on the WMIT-Infrastructure board.
valerio.bozzolan renamed this task from Migrate configuration of www.wikimedia.it from mod_php to php_fom (with dedicated Unix user, etc.) to Migrate configuration of www.wikimedia.it from mod_php to PHP-FPM (with dedicated Unix user, etc.).Jun 7 2023, 5:53 PM

Ciao Valerio,

Mi scuso per la tardiva risposta ma in questi giorni abbiamo dovuto risolvere delle urgenze in azienda.

Volevo chiederti più informazioni a riguardo del ticket che ho ricevuto sul portale di Wikimedia

Grazie!

Davide Cuteri
Systems & Network Specialist
Cell +39 388 888 3539
Località Rilate 18 – 14100 Asti
Anylink Group S.r.l.
Tel +39 0141 477528
anylinkgroup.com

[cid:3cbcbabe-afe8-462f-adb8-615bdc8f2cf1]


Da: valerio.bozzolan <no-reply@phabricator.wikimedia.org>
Inviato: mercoledì 7 giugno 2023 19:53
A: Davide Cuteri <davide.cuteri@anylinkgroup.com>
Oggetto: [Maniphest] [Retitled] T338346: Migrate configuration of www.wikimedia.it from mod_php to PHP-FPM (with dedicated Unix user, etc.)

valerio.bozzolan renamed this task from "Migrate configuration of www.wikimedia.it from mod_php to php_fom (with dedicated Unix user, etc.)" to "Migrate configuration of www.wikimedia.it from mod_php to PHP-FPM (with dedicated Unix user, etc.)". View Taskhttps://phabricator.wikimedia.org/T338346

TASK DETAIL
https://phabricator.wikimedia.org/T338346

EMAIL PREFERENCES
https://phabricator.wikimedia.org/settings/panel/emailpreferences/

To: DavideCuteri-WMIT, valerio.bozzolan
Cc: Nemo_bis, stefano.cannillo, valerio.bozzolan

{F37102329}

Ciao @DavideCuteri-WMIT!

Stavo conversando con il collega @stefano.cannillo. Questa potrebbe essere una buona, piccola, sebbene abbastanza critica, attività sistemistica di Anylink, da poter pianificare insieme.

In pratica, al momento sul server intreccio c'è il virtualhost per https://www.wikimedia.it/ che funziona grazie a "mod_php" (quindi Apache fa tutto, esegue lui PHP) e invece vorremmo passare ad una configurazione più moderna usando PHP FPM (quindi Apache si occupa solo dei file statici, e i file PHP vengono elaborati da un pool PHP-FPM che gira a parte, in ascolto su una porta, o su un socket file).

È relativamente sicuro testare il tutto, per esempio creando un nuovo virtualhost di test sul server intreccio.

Mi farebbe piacere sapere se sia un'attività che possiamo far ricadere nelle vostre competenze. Sarebbe di grande aiuto ai volontari che solitamente se ne occupano.

Ciao!

Si, va bene! Io ho iniziato a fare qualche test su una mia macchina virtuale.

Ti contatterò quanto prima per programmare come procedere se sei d'accordo

Probabilmente un buon candidato è it-wikimedia-survey-ssl.conf

Si, avevo rimosso il commento perchè avevo poi visto su in descrizione e ho letto li il nome

Avevo provato ad accedere a Wikina ma mi dava errore su i permessi

La tua utenza dovrebbe essere nei sudoers 👍

Ciao Valerio, ho un problema con la password durante le operazioni con il sudo.

Ho controllato la password e sono sicuro che sia corretta, ho usato quella di accesso al sito.. Ho addirittura provato con la chiave privata per scrupolo
Ti mando comunque in allegato la schermata

Grazie!

Errore PSW.png (280×1 px, 26 KB)

Ciao Davide, riprova ora. Alla fine non eri nel gruppo sudo, ed era configurato male /etc/sudoers. Ora dovrebbe andare.

Queste utenze sono autorizzate ad entrare solo con chiavi SSH, volutamente nessuna utenza dovrebbe avere una password. Una volta che l'utenza accede, se è nei sudoers, dovrebbe subito poter fare le operazioni di cui ha bisogno.

Ciao Valerio,

Ho provato e funziona
Grazie!!

Per il nome dei virtual host ci sono degli standard?

Grazie per la domanda

Idealmente con il dominio inverso. Al posto del punto, un trattino.

Se il dominio di prova fosse test.www.wikimedia.it allora il file si potrebbe chiamare it-wikimedia-www-test.

Poi suffissi per versione :80 e versione :443:

it-wikimedia-www-test-txt.conf
it-wikimedia-www-test-ssl.conf

(Non è obbligatorio)

Segnalo questi due comandi per fare controllo sintassi:

apache2ctl configtest

E per ricaricare senza disservizi:

apache2ctl graceful

Ciao Valerio,

Abbiamo guardato sul file di configurazione di Wikimedia.it ma nel file di configurazione ha già le righe per l'FPM.

Può essere che sia già stata eseguita la modifica?

Grazie!

Se ci stiamo riferendo a questa riga, al momento è commentata

/etc/apache2/sites-available/it-wikimedia-www-ssl.conf
#
# In fabula we were using the Centos 7 package 'rh-php73-php-fpm'
#
# See https://phabricator.wikimedia.org/T270776
#
# ProxyPassMatch ^/(.*\.php)$ fcgi://127.0.0.1:9003/var/www/wmi/wordpress

Ciao Valerio,

Ho creato la DocumentRoot in /var/www/test1.wikimedia.it/test1.php - Con dentro il comando phpinfo che mi hai suggerito tu

Ho creato il VirtualHost nella seguente path e con il nome:
/etc/apache2/sites-available/it-wikimedia-www-test-ssl.conf - Dentro il file di configurazione ho inserito i comandi per l' FPM

Solo che provando a testare la pagina da un browser esterno, con il nome che gli ho assegnato io a livello di DNS va in errore e invece inserendo l'indirizzo IP del server mi reindirizza alla pagina di Wikimedia.it giustamente.

Tu conosci un modo per testare il tutto?

Grazie!

Ciao @DavideCuteri-WMIT, forse ho dimenticato una premessa. WMIT ha bisogno di consulenza per sistemistica su server dichiaratamente LAMP. Fortunatamente sono tutti così. È un problema questo?

Sostanzialmente quindi si parlerà abbastanza spesso di toccare una LAMP.

Cerco di capire il mio punto di vista. Diversi volontari hanno sempre svolto queste operazioni "un po' a caso nel tempo libero", quindi ho insistito per trovare una figura professionale per effettuare lavorazioni sistemistiche su ambienti LAMP al posto loro. Sono stato piuttosto contento di trovare voi, in questo sostegno ai volontari, che potete operare in orario lavorativo al contrario nostro che abbiamo un altro lavoro.

Sono quindi a completa disposizione per indicare o migliorare le linee guida di WMIT, e aiutare nella documentazione in essere, ecc. ma non dovrei essere io, da volontario, a disposizione di una persona pagata, per aiutarla a superare un problema su un server LAMP, risalendo dal sintomo comunicato dalla persona pagata, ovvero: «va in errore».

Tornando a noi.

Se immagino correttamente, è possibile che visitando https://test1.wikimedia.it/ riscontri un errore "HTTP 403 Forbidden". In quel caso conviene analizzare i log di apache per approfondire.

$ tail -f /var/log/apache2/error.log
... AH01276: Cannot serve directory /var/www/test1.wikimedia.it/wordpress/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm) found, and server-generated directory index forbidden by Options directive

Per risolvere basta un file index.php dentro alla tua DocumentRoot.

Ma anche visitando il file diretto https://test1.wikimedia.it/test1.php (vedo che è in posizione) riscontro anche io un errore: "HTTP 503 Service Unavailable". Anche per quel caso esaminare i log di Apache aiuta:

$ tail -f /var/log/apache2/error.log
No such file or directory: AH02454: FCGI: attempt to connect to Unix domain socket /run/php/php7.3-fpm.sock (*) failed

Quindi non esiste quel percorso.

Quindi torniamo al punto di partenza: cosa è stato fatto? Bisognava configurare PHP-FPM. È stato fatto? Mi sembra di no, sul posto sembra ci sia solo il mio vecchio file disabilitato l'anno scorso per dei test:

ls -la /etc/php/7.3/fpm/pool.d/
total 48
drwxr-xr-x 2 root root  4096 giu 26 13:38 .
drwxr-xr-x 3 root root  4096 mag  9 17:42 ..
-rw-r--r-- 1 root root 20209 mag  9 17:43 wikina.conf
-rw-r--r-- 1 root root 19703 giu 15  2022 www.conf.disabled

Chiedo gentilmente di rileggere un attimo la descrizione di questo Task, in alto, in cui avevo cercato con cura di descrivere il da farsi. Nel caso di dubbi, consiglio di documentarsi un attimo su come funziona un server LAMP, in particolare PHP-FPM.

Grazie per la collaborazione Davide

Se ci stiamo riferendo a questa riga, al momento è commentata

/etc/apache2/sites-available/it-wikimedia-www-ssl.conf
#
# In fabula we were using the Centos 7 package 'rh-php73-php-fpm'
#
# See https://phabricator.wikimedia.org/T270776
#
# ProxyPassMatch ^/(.*\.php)$ fcgi://127.0.0.1:9003/var/www/wmi/wordpress

Chiarisco un attimo questo commento ↑

Questa riga che hai trovato era stata commentata perché proveniva da una installazione che purtroppo è stata distrutta dopo un incendio. Può essere sicuramente di "ispirazione" ma non è qualcosa che può funzionare in questo server o in altri con un copia-incolla purtroppo.

Qualcosa che invece può essere ben più di una ispirazione, sono le configurazioni menzionate nella descrizione di questo Task. Cito questa per esempio che funziona benissimo per la wikina ed è sicuramente un ottimo spunto da cui partire:

https://gitlab.wikimedia.org/repos/wikimedia-it/wmit-infrastructure/-/blob/f322bcd06f9dd301ee87cee2bde8d8a5d7855e36/servers/intreccio/conf/apache2/include/it-wikimedia-wiki-main.conf

Ciao @DavideCuteri-WMIT :)

Segnalo che questa attività è ancora da svolgere. Più o meno da volontario questa attività l'ho preventivata a 2 ore di lavoro. Nel senso che in un'ora si installa una LAMP (con FPM), e nell'altra ora me la terrei buona per i test.

Non c'è fretta sul fare questa attività. È però importante sbloccare lo stallo e poter ricevere da parte vostra una opinione professionale, per capire se potrebbe divertirvi farlo oppure se è una cosa che di solito non fate, e certamente troviamo altre cose più divertenti da fare.

Ciao @valerio.bozzolan

In questa settimana fino a venerdì siamo occupati con un corso di aggiornamento, lunedì ti faremo sapere

Ciao

Ciao Davide,

Grazie per aver avvisato.

Buongiorno a tutti.

Mi attacco a questo ticket perchè è sempre più impellente la necessità di avere a disposizione una versione di PHP (8.1) più avanzata per

  • Wordpress (www.wikimedia.it)
  • Matomo (matomo.wikimedia.it)

Sarebbe utile avere su intreccio 2 versioni di PHP (7.3 e 8.1) via FPM.

Ci sono aggiornamenti in merito?
E' previsto un ETA per l'attività?

valerio.bozzolan raised the priority of this task from Low to High.
valerio.bozzolan set the point value for this task to 2.
valerio.bozzolan removed a subscriber: DavideCuteri-WMIT.
valerio.bozzolan renamed this task from Migrate configuration of www.wikimedia.it from mod_php to PHP-FPM (with dedicated Unix user, etc.) to Migrate configuration of www.wikimedia.it from mod_php to PHP-FPM (with dedicated Unix user, etc.) - cover PHP 7.4 + 8.1.Jan 30 2024, 2:34 PM
valerio.bozzolan updated the task description. (Show Details)

Good luck.

I will do a sprint at 12:40 today.

Aaaand without surprise I need more time after dinner to conclude, in front of a good TV series maybe.

@valerio.bozzolan keep me updated, so I can schedule the wordpress (and matomo) updates.

NOTE: I noticed an adminer.php exposed. Better to hide this kind of stuff. Moved in the parent directory.
  • run apt update + apt upgrade
  • install sury.org repository following https://packages.sury.org/php/README.txt
  • created a dedicated user called www-wikimediait that is also in the www-data group.
  • apt install php8.1-fpm php7.3-fpm
  • apt install php8.1-mysql php8.1-curl php8.1-imagick php8.1-mbstring php8.1-xml suggested from https://make.wordpress.org/hosting/handbook/server-environment/ - maybe others missing
  • configured basic /etc/php/8.1/fpm/pool.d/it.wikimedia.www.conf
  • configured basic /etc/wmit-infrastructure/servers/intreccio/conf/apache2/sites-available/it-wikimedia-www-test-ssl.conf

To test this thing, please poison your local DNS like this:

/etc/hosts
51.75.90.142 test.www.wikimedia.it

Then visit this, accepting the broken certificate:

https://test.www.wikimedia.it/

IMPORTANT: WordPress will try to redirect to the canonical location. I don't know how to skip this to do tests. But at least we have some progress \o/

I also don't know how to access the /wp-admin/ page since it was probably hardened :)

OK I've added a dirty snippet in wp-config.php to avoid redirects to the canonical domain. Something like:

// Avoid to redirect outside the testing environment.
// TODO: remove this when this task is concluded :D :D :D
//   https://phabricator.wikimedia.org/T338346
if(@$_SERVER['SERVER_NAME'] === 'test.www.wikimedia.it') {
        define( 'WP_HOME', 'https://' . $_SERVER['HTTP_HOST'] . '/' );
}

We can test things \o/

But... the WordPress plugin W3 Total Cache is somehow broken, at least in PHP 8.1:

/var/log/fpm-php.it.wikimedia.www.err.log
[07-Feb-2024 20:03:03 UTC] PHP Warning:  Trying to access array offset on value of type bool in /var/www/wmi/wordpress/wp-content/plugins/wiki-embed/WikiEmbed.php on line 112
[07-Feb-2024 20:03:03 UTC] PHP Warning:  Trying to access array offset on value of type bool in /var/www/wmi/wordpress/wp-content/plugins/wiki-embed/WikiEmbed.php on line 116
[07-Feb-2024 20:03:03 UTC] PHP Fatal error:  ob_start(): Cannot use output buffering in output buffering display handlers in /var/www/wmi/wordpress/wp-content/plugins/w3-total-cache/Util_WpFile.php on line 298
...

So https://test.www.wikimedia.it "runs" with PHP 8.1 and you can now test things.

Related documentation update

https://meta.wikimedia.org/w/index.php?title=Wikimedia_Italia%2FWebsite%2FTechnical_documentation&diff=26192416&oldid=25931521

// Avoid to redirect outside the testing environment.
// TODO: remove this when this task is concluded :D :D :D
//   https://phabricator.wikimedia.org/T338346
if(@$_SERVER['SERVER_NAME'] === 'test.www.wikimedia.it') {
        define( 'WP_HOME', 'https://' . $_SERVER['HTTP_HOST'] . '/' );
}

I suppose that the problem is that Wordpress has its base_url hardcoded in database.
That means that it cannot work on different domains at the same time.

We can test things \o/

But... the WordPress plugin W3 Total Cache is somehow broken, at least in PHP 8.1:

I'll take a look. I hope it's only a cache problem for a cache plugin.

To migrate the main website to PHP 8.1 how do you suggest to proceed?

ADD to /etc/apache2/sites-available/it-wikimedia-www-ssl.conf

<FilesMatch \.php$>

         # sudo apt install php8.1-fpm
         SetHandler "proxy:unix:/run/php/php8.1-fpm.sock|fcgi://localhost/"
 </FilesMatch>
  1. rename /etc/apache2/sites-available/it-wikimedia-www-test-ssl.conf in /etc/apache2/sites-available/it-wikimedia-www-ssl.conf

About the W3 Total Cache broken in production, 2.3.2 was probably bugged (?)

https://wordpress.org/support/topic/website-crash-after-upgrade-to-2-3-2/

But we are using 2.6.1 (゜-゜) so... no hints.

Somebody on Stack Overflow has an apparently similar symptom, during a memory exhaustion - https://stackoverflow.com/a/71461253/3451846 - but I have not proof of any follow-up memory exhaustion in the logs. And, btw, both mod_php and PHP-FPM have memory_limit of 128MB. Same value. In any case, we can grow to 512M if you think we need that, but we should maybe try to do at least a quick profiling first, to better understand our current needs.

Anyway I'm super confused after I've inspected the relevant line of source code of that plugin. I just immediately see a potential infinite recursion there (゜-゜)

/var/www/wmi/wordpress/wp-content/plugins/w3-total-cache/Util_WpFile.php
/**
 * Get WordPress filesystems credentials. Required for WP filesystem usage.
 *
 * @param string  $method  Which method to use when creating
 * @param string  $url     Where to redirect after creation
 * @param bool|string $context path to folder that should be have filesystem credentials.
 * If false WP_CONTENT_DIR is assumed
 * @throws Util_WpFile_FilesystemOperationException with S/FTP form if it can't get the required filesystem credentials
 */
private static function request_filesystem_credentials( $method = '', $url = '', $context = false ) {
        if ( strlen( $url ) <= 0 ) {
                $url = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
        }

        $url = preg_replace( '/&w3tc_note=([^&]+)/', '', $url );

        // Ensure request_filesystem_credentials() is available.
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/template.php';

        $success = true;
        ob_start(); // ← ← ← ← ← crash here
        if ( false === ( $creds = request_filesystem_credentials( $url, $method, false, $context, array() ) ) ) {
                $success =  false;
        }
        $form = ob_get_contents();
        ob_end_clean();

Need more time to troubleshoot

Ah, interestingly, PHP does NOT produce a stack trace as default in logs, after a Fatal Error. So I think there is more here and that could really be an infinite recursion. Probably time to XDebug.

Here some issues:

1- @paolo.casagrande.wmit is not able to upload files in Wordpress interface
2- Sometimes the websiite respond 500

Solutions

1- Upload issue

For sure its a permission issue.

chown -R www-wikimediait: wp-content/

Solved the problem.
@valerio.bozzolan any suggetion for a better solution?

2- Random 500 errors

I've done somes changes in /etc/php/8.1/fpm/php.ini

memory_limit = 256M
max_execution_time = 60

Stefano, thanks for fixing that regression. Yours was the right solution. We are not using anymore the Unix user called www-data (shared), but we have a dedicated one instead (www-wikimediait). So now the website is more secure and isolated from the others.

Ideally, only files that should be writable by that WordPress should be assigned to that user. All other files should not.

I've updated the documentation accordingly to that:

https://meta.wikimedia.org/wiki/Wikimedia_Italia/Website/Technical_documentation#Hardening (diff)

Feel free to also update things if you see something weird 👍

(Let's also see if you still get these random 500 errors) see you

Ah, let's declare as concluded \o/