Nova Resource:Wikisource/Wikisource Export

From Wikitech
Jump to navigation Jump to search

We have two VPS instances and two Toolforge tools (one each for prod and test). The latter exist because WS Export used to be hosted there, and the VPSs still use those tools' databases and email addresses.

Creating a new instance

Create a new g2.cores4.ram8.disk80 instance running on the latest Debian (or a g3.cores1.ram1.disk20 for the test instance). Once the instance has been spawned, SSH in and follow these steps:

  1. Install PHP and Apache, along with some dependencies:
    sudo apt update
    sudo apt -y upgrade
    sudo apt -y install php php-mysql php-sqlite3 php-intl php-zip apache2 libapache2-mod-php mariadb-client calibre php-curl php-xml php-dom php-mbstring
  2. We use the packaged version of Calibre, even though they recommend not to because it can be out of date; it's been working fine for us. Note that Calibre can fail to clean up its temp files in some situations, so we also add the following in /etc/cron.daily/calibre-cleanup:
    find /tmp -path '*calibre*' -user www-data -mtime +1 -exec rm -r {} \;
  3. Install some fonts. Mostly these are available in the Debian repositories, but the Mukta family must be installed manually to maintain backwards compatibility (these used to be packaged with the tool's code), and Amiri is not available elsewhere.
    sudo apt -y install fontconfig fonts-freefont-ttf fonts-linuxlibertine fonts-dejavu-core fonts-gubbi fonts-opendyslexic fonts-noto fonts-noto-cjk
    wget -O
    wget -O
    wget -O
    wget -O
    sudo unzip -d /usr/local/share/fonts/Mukta
    sudo unzip -d /usr/local/share/fonts/MuktaMahee
    sudo unzip -d /usr/local/share/fonts/MuktaMalar
    sudo unzip -d /usr/local/share/fonts/MuktaVaani
    wget -O
    sudo unzip -j "amiri-1.000/fonts/*" -d /usr/local/share/fonts/Amiri
    sudo cp -r Indigo-main/fonts /usr/local/share/fonts/Indigo
    sudo fc-cache -v
  4. Install composer by following these instructions (we don't include them here because you must validate the download), but make sure to install to the /usr/local/bin directory and with the filename composer, e.g.:
    sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
  5. Clone the repository, first removing the html directory created by Apache.
    cd /var/www && sudo rm -rf html
    sudo git clone tool
    cd /var/www/tool
  6. Become the root user with sudo su root
  7. Add a block storage filesystem at /ws-export/ with a directory in it symlimked from the tool's var/ directory:
    mkdir /ws-export/var
    chown -R www-data:www-data /ws-export/var
    ln -s /ws-export/var /var/www/tool/var
  8. Run sudo composer install --no-dev -o
  9. Copy .env to .env.local and edit the environment variables in it.
  10. Make sure that all the files in the repo are owned by www-data.
    sudo chown -R www-data:www-data .
  11. Create the web server configuration file at /etc/apache2/sites-available/wsexport.conf with the following:
    <VirtualHost *:80>
            Redirect /
    <VirtualHost *:80>
            DocumentRoot /var/www/tool/public
            php_value memory_limit 512M
            # Requests with these user agents are denied and logged at ${APACHE_LOG_DIR}/denied.log
            SetEnvIfNoCase User-Agent "(uCrawler|Baiduspider|CCBot|scrapy\.org|kinshoobot|YisouSpider|Sogou web spider|yandex\.com\/bots|twitterbot|TweetmemeBot|SeznamBot|datasift\.com\/bot|Googlebot|Yahoo! Slurp|Python-urllib|BehloolBot|MJ13bot|SemrushBot|facebookexternalhit|rcdtokyo\.com|Pcore-HTTP|yacybot|ltx71|RyteBot|bingbot|python-requests|Cloudflare-AMP|Mr\.4x3|MSIE 7\.0; AOL 9\.5|Acoo Browser|AcooBrowser|MSIE 6\.0; Windows NT 5\.1; SV1; QQDownload|\.NET CLR 2\.0\.50727|MSIE 7\.0; Windows NT 5\.1; Trident\/4\.0; SV1; QQDownload|Frontera|tigerbot|Slackbot|Discordbot|LinkedInBot|BLEXBot|filterdb\.iss\.net|SemanticScholarBot|FemtosearchBot|BrandVerity|Zuuk crawler|archive\.org_bot|mediawords bot|Qwantify\/Bleriot|Pinterestbot|EarwigBot|Citoid \(Wikimedia|GuzzleHttp|PageFreezer|Java\/|SiteCheckerBot|Re\-re Studio|^R \(|GoogleDocs|WinHTTP|cis455crawler|WhatsApp|Archive\-It|lua\-resty\-http|crawler4j|libcurl|dygg\-robot|GarlikCrawler|Gluten Free Crawler|WordPress|Paracrawl|7Siters|Microsoft Office Excel|MJ12bot|AhrefsBot|dotbot|amp-cloud|naver\.me\/spd|Adsbot|linkfluence|coccocbot|sqlmap|Applebot|MauiBot|PetalBot|FacebookBot|UMichBot|LinuxGetUrl|; MSIE (6|7|8)\.0;|deepnoc)" bad_bot=yes
            # Google Cloud, Amazon AWS among other webhost blocks. Requests are logged at ${APACHE_LOG_DIR}/denied.log
            SetEnvIfExpr "%{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch '' || %{HTTP:X-Forwarded-For} -ipmatch ''" bad_bot=yes
            # Calibre env vars:
            SetEnv CALIBRE_CONFIG_DIRECTORY /tmp/calibre-config
            SetEnv CALIBRE_TEMP_DIR /var/www/tool/var/calibre-temp
            LogFormat "%{X-Forwarded-For}i %t \"%r\" %>s \"%{Referer}i\" \"%{User-Agent}i\"" wsexport
            CustomLog ${APACHE_LOG_DIR}/access.log wsexport expr=!(reqenv('bad_bot')=='yes'||reqenv('dontlog')=='yes')
            CustomLog ${APACHE_LOG_DIR}/denied.log wsexport expr=(reqenv('bad_bot')=='yes')
            ErrorLog ${APACHE_LOG_DIR}/error.log
            ScriptAlias /tool "/var/www/tool/public"
            Redirect /wikisource-fr-good.atom /opds/fr/Bon_pour_export.xml
            Redirect /opds/fr.xml /opds/fr/Bon_pour_export.xml
            <Directory /var/www/tool/public/>
                 Options Indexes FollowSymLinks
                 AllowOverride All
                 Require all granted
                 DirectoryIndex index.php book.php
                 # Rewrite URLs for Symfony:
                 RewriteEngine On
                 RewriteRule ^index\.php$ - [L]
                 RewriteCond %{REQUEST_FILENAME} !-f
                 RewriteCond %{REQUEST_FILENAME} !-d
                 RewriteRule . /index.php [L]
            <Directory /var/www/tool/>
                    Options Indexes FollowSymLinks
                    AllowOverride None
                    Require all granted
                    Deny from env=bad_bot
                    <Files "robots.txt">
                            # Allow bots to find out that they're not allowed
                            Allow from all
            ErrorDocument 403 "Access denied. If you are human and were wrongfully affected by this block, please contact"
            RewriteCond "%{HTTP_REFERER}" "^http://127\.0\.0\.1:(5500|8002)/index\.html" [NC]
            RewriteRule .* - [R=403,L]
            RewriteCond "%{HTTP_USER_AGENT}" "^[Ww]get"
            RewriteRule .* - [R=403,L]
            RewriteEngine On
            RewriteCond %{HTTP:X-Forwarded-Proto} !https
            RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]
  12. Set PHP configuration in /etc/php/8.2/mods-available/wsexport.ini:
    max_execution_time = 60;
    And enable it with sudo phpenmod wsexport
  13. Enable/disable the needed Apache modules, and enable the web server configuration.
    sudo a2dismod mpm_event
    sudo a2enmod php8.2 rewrite
    sudo a2dissite 000-default
    sudo a2ensite wsexport
    sudo service apache2 reload
  14. (Re)start Apache:
    sudo service apache2 restart
    Moving forward, you should use sudo service apache2 graceful to restart the server.
  15. Add a cronjob to prune the cache twice a day:
    00 1,13 * * * /usr/local/bin/
    Where the script is the following:
    df /ws-export/
    /usr/bin/php /var/www/tool/bin/console cache:pool:prune
    df /ws-export/
  16. Set up annual log dump files by running the following weekly (it's located at /etc/cron.weekly/wsexport-dump-logs, and note that you have to put the tool's DB credentials into /etc/mysql/conf.d/wsexport.cnf):
    if [ -z "$YEAR" ]; then
      YEAR=$( date +%Y )
    echo "Dumping logs of $YEAR to $LOGDIR"
    mysqldump --defaults-file=/etc/mysql/conf.d/wsexport.cnf \
            s52561__wsexport_p books_generated \
            --where="YEAR(time) = $YEAR" \
            | gzip -c > $LOGDIR/$YEAR.sql.gz
    chown -R www-data:www-data $LOGDIR
    ls -l $LOGDIR
    You should also create a symlink to make these logs public at
    ln -s /ws-export/wsexport_logs /var/www/tool/public/logs
  17. Add log rotation to Symfony's logs by creating the file /etc/logrotate.d/symfony with:
    /var/www/tool/var/log/*.log {
            su www-data www-data
            rotate 14
            create 640 root adm 
                    if /etc/init.d/apache2 status > /dev/null ; then \
                        /etc/init.d/apache2 reload > /dev/null; \
                    if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
                            run-parts /etc/logrotate.d/httpd-prerotate; \
                    fi; \
    You can check that it works by running it directly:
    $ sudo logrotate -f /etc/logrotate.d/symfony

crontab summary

Crontab for www-data:

# OPDS exports.
@daily php /var/www/tool/bin/console app:opds -q -l en --category=Ready_for_export
@daily php /var/www/tool/bin/console app:opds -q -l fr --category=Bon_pour_export

# Prune cache.
00 1,7,13,19 * * * /usr/local/bin/ > /dev/null