The following details how to install R with FastRWeb/Rserve support using Nginx web server on Debian Linux.

An acknowledgement is made in advance to this important post by Jay Emerson, which covers Apache2 / Ubuntu.

The procedure below has been tested on Debian 7u2 64 bit and should be applicable to Debian / Ubuntu Linux instances. At time of writing, R version 2.15 binaries are available in the default Debian repositories.

If building R from source ensure that it is configured with the option:

--enable-R-shlib

SE-Linux users should be aware that the FastRWeb CGI process will attempt to open a Unix socket connection in order to communicate with Rserve so users may need to adjust their security policy for FCGI accordingly.

An optional procedure for installing R-CRAN archived ggplot2 is included at the end of this post, and a sample script for use of ggplot2 with FastRWeb is included also.

It is assumed that the Debian installation is relatively clean and a functional Nginx has been installed.

For R package installation, build-essentials and a functional GCC is also required.

For some optional modules, a functional gfortran is also needed.

Cairo >1.2 should be installed. There is no requirement for a full X11 installation.

0: Install required Debian packages.

$ sudo apt-get update
$ sudo apt-get install fcgiwrap r-base

NB: libxml2 should be additionally installed if the R XML package is required.

The R XML package is not required for running FastRWeb.

1: Install required R-Packages from CRAN.

$ sudo apt-get update
$ sudo R
> install.packages('Rserve')
> install.packages('Cairo')
> install.packages('FastRWeb')
> # The following is not required, but will require libxml2 (see above) if installed
> install.packages('XML')
> # The following can be substituted for any other R database interface, or omitted
> install.packages('RPostgreSQL')
> quit()

Confirm the installation folder for the R packages:

$ sudo R
> system.file("", package="FastRWeb")
[1] "/usr/local/lib/R/site-library/FastRWeb/"
> quit()

Adjust $R_SITELIB_PATH=/usr/local/lib/R/site-library as per result [1].

2: Install FastRWeb:

$ cd $R_SITELIB_PATH
$ sudo ./install.sh

This creates the FastRWeb home folder: /var/FastRWeb

3: Configure Nginx.

In the following:

  • $WWW_ROOT = Nginx ‘root’ as defined in the sites-available file.
  • $WWW_USER = Account which has ownership of $WWW_ROOT (eg. www-data)
$ sudo mkdir $WWW_ROOT/cgi-bin
$ sudo cp $R_SITELIB_PATH/FastRWeb/cgi-bin/Rcgi $WWW_ROOT/cgi-bin/R
$ sudo chown -R $WWW_USER:$WWW_USER $WWW_ROOT/cgi-bin 

Edit the Nginx sites file located: /etc/nginx/sites-available).

Before the ‘server’ definition add:

map $request_uri $request_basename {
    ~/(?[^/?]*)(?:\?|$)
    $captured_request_basename;
}

Within the ‘server’ definition, add the following fastcgi ‘location’ definition for the FastRWeb cgi-bin executable.

NB: Substitute ‘$WWW_ROOT’ with the actual root.

location ~ ^/cgi-bin/R/.*$ {
    gzip           off;
    root           $WWW_ROOT;
    fastcgi_pass   unix:/var/run/fcgiwrap.socket;
    # include      fastcgi_params;
    fastcgi_param  QUERY_STRING       $query_string;
    fastcgi_param  REQUEST_METHOD     $request_method;
    fastcgi_param  CONTENT_TYPE       $content_type;
    fastcgi_param  CONTENT_LENGTH     $content_length;

    fastcgi_param  SCRIPT_FILENAME    $document_root/cgi-bin/R;
    fastcgi_param  SCRIPT_NAME        $request_filename;
    fastcgi_param  REQUEST_URI        $request_uri;
    fastcgi_param  DOCUMENT_URI       $document_uri;
    fastcgi_param  DOCUMENT_ROOT      $document_root;
    fastcgi_param  SERVER_PROTOCOL    $server_protocol;

    fastcgi_param  PATH_INFO          $request_basename; # Key for Rcgi

    fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
    fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

    fastcgi_param  REMOTE_ADDR        $remote_addr;
    fastcgi_param  REMOTE_PORT        $remote_port;
    fastcgi_param  SERVER_ADDR        $server_addr;
    fastcgi_param  SERVER_PORT        $server_port;

    # According to RFC3875 (https://tools.ietf.org/html/rfc3875#section-4.1.14) in SERVER_NAME
    # we should put actual hostname user came to. For nginx it is in $http_host
    # This will allow to run multihost instances
    fastcgi_param  SERVER_NAME        $http_host;
}

Once updated, restart Nginx and ensure fastcgi is up.

$ sudo /etc/init.d/nginx restart
$ sudo /etc/init.d/fcgiwrap start

If there are errors during the Nginx restart check through the changes made to the site configuration file.

4: Update the Rserve configuration.

a) Security:

i) Change ownership of folders and files under: /var/FastRWeb to $WWW_USER (eg. www-data):

$ sudo chown -R $WWW_USER:$WWW_USER /var/FastRWeb

ii) Update file /var/FastRWeb/code/rserve.conf to have the following content:

umask 0007
socket /var/FastRWeb/socket
sockmod 0660
source /var/FastRWeb/code/rserve.R
control enable

(Added / modified lines in bold)

b) Start up packages:

Packages required by FastRWeb scripts can be pre-loaded by Rserve. These packages will then be available to all FastRWeb scripts.

The Rserve configuration is stored in the following file:

/var/FastRWeb/code/rserve.R

The relevant section of the file is as follows by default:

## This is jsut a friendly way to load package and report success/failure
## You will definiteily need FastRWeb, others are optional
pkgs <- c("XML", "Cairo", "Matrix", "FastRWeb") 
cat("Loading packages...\n")
for (pkg in pkgs) cat(pkg, ": ",require(pkg, quietly=TRUE, character.only=TRUE),"\n",sep='')

The bold line, pkgs <- …, needs to be updated.

If database support with package RPostgreSQL is required, update as follows:

## This is jsut a friendly way to load package and report success/failure
## You will definiteily need FastRWeb, others are optional
pkgs <- c("XML", "Cairo", "Matrix", "FastRWeb", "RPostgreSQL")
cat("Loading packages...\n")
for (pkg in pkgs) cat(pkg, ": ",require(pkg, quietly=TRUE, character.only=TRUE),"\n",sep='')

If XML support is not required the XML entry can be removed.

NB: Changes to this file would require a restart of Rserve.

5: Create an init script for Rserve.

a) Create file /etc/init.d/rserve with the following content, updating ‘WWW_USER’ if different to ‘www-data’:

#!/bin/sh
set -e

### BEGIN INIT INFO
# Provides:             Rserve
# Required-Start:       $nginx
# Required-Stop:        $nginx
# Should-Start:         $syslog
# Should-Stop:          $syslog
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    Rserve Daemon
### END INIT INFO

# WWW_USER - Update the following if Nginx running in different context.
WWW_USER=www-data

# Must be a valid filename
NAME=rserve
PIDFILE=/var/run/$NAME.pid

#This is the command to be run, give the full pathname
DAEMON='/var/FastRWeb/code/start'
DAEMON_OPTS="--daemon --quiet"

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"
cd /var/FastRWeb/code/

case "$1" in
  start)
        echo -n "Starting daemon: "$NAME
        start-stop-daemon --start --quiet --chuid $WWW_USER:$WWW_USER \ 
--background --exec $DAEMON -- $DAEMON_OPTS > /dev/null
        echo "."
        ;;
  stop)
        echo -n "Stopping daemon: "$NAME
        killall -INT Rserve
        echo "."
        ;;
  restart)
        echo -n "Restarting daemon: "$NAME
        killall -INT Rserve
        start-stop-daemon --start --quiet --chuid $WWW_USER:$WWW_USER \
--exec $DAEMON -- $DAEMON_OPTS > /dev/null &
        echo "."
        ;;

  *)
        echo "Usage: "$1" {start|stop|restart}"
        exit 1
esac

exit 0

b) Make the rserve init.d script executable:

$ sudo chmod 750 /etc/init.d/rserve

c) For Rserve to automatically start with the operating system update the start up resources:

$ sudo update-rc.d rserve defaults

6: Create a test FastRWeb R Script.

FastRWeb R scripts are located by default in the following location:

/var/FastRWeb/web.R

To test the installation and configuration create the file:

/var/FastRWeb/web.R/foo.png.R

With this content:

# foo.png.R:
run <- function(n=100, ...) {
    n <- as.integer(n)
    p <- WebPlot(800, 600)
    plot(rnorm(n), rnorm(n), pch=19, col=2)
    p
}

7: Start up Rserve and test FastRWeb

a) If Nginx is stopped, start Nginx.
b) Start Rserve

$ sudo /etc/init.d/rserve start

c) Assuming the Nginx is serving cgi-bin on localhost/cgi-bin, navigate to:

http://localhost/cgi-bin/R/foo.png?n=500

An 800×600 scatter-plot image should be displayed.

Optional: Archive installation of ggplot2 and use of ggplot2 with FastRWeb

At time of writing R version 2.15 was available from Debian repositories.

The CRAN ggplot2 package hosted on mirrors requires R 3.0 or higher.

The following procedure installs a functional ggplot2 from CRAN archive into R 2.15 which can be used with FastRWeb. (Strictly not recommended for production use.)

The test script below shows how to use ggplot2 with FastRWeb.

a) Perform a baseline (broken) installation of ggplot2 with current compatible dependencies available from CRAN:

$ sudo R
> install.packages("ggplot2", dependencies=TRUE)

This will break on a number of dependencies towards the end.

b) Correct the baseline installation by installing R-CRAN archive packages.

These archive packages were located by looking for the last releases from 2012 – close to R 2.15’s date.

They may be substituted with compatible packages located in the archive, and packages may need to be added to the following depending on installed R version and CRAN updates.

$ sudo R
> installarchive <- function(url, pkgFile) {
>    download.file(url = url, destfile = pkgFile)
>    install.packages(pkgs=pkgFile, type="source", repos=NULL)
>    unlink(pkgFile)
> }
> installarchive('http://cran.r-project.org/src/contrib/Archive/plyr/plyr_1.8.tar.gz','plyr_1.8.tar.gz')
> installarchive('http://cran.r-project.org/src/contrib/Archive/reshape2/reshape2_1.2.2.tar.gz','reshape2_1.2.2.tar.gz')
> installarchive('http://cran.r-project.org/src/contrib/Archive/scales/scales_0.2.3.tar.gz','scales_0.2.3.tar.gz')
> installarchive('http://cran.r-project.org/src/contrib/Archive/ggplot2/ggplot2_0.9.3.tar.gz','ggplot2_0.9.3.tar.gz')

The following are not required for a functional ggplot2 operation:

  • acepack
  • mvtnorm
  • multcomp
  • Hmisc

If these packages are required then a working gfortran should be installed.

Once gfortran is installed, the following will install these packages:

$ sudo R
> installarchive <- function(url, pkgFile) {
>    download.file(url = url, destfile = pkgFile)
>    install.packages(pkgs=pkgFile, type="source", repos=NULL)
>    unlink(pkgFile)
> }
> installarchive('http://cran.r-project.org/src/contrib/Archive/acepack/acepack_1.3-3.2.tar.gz','acepack_1.3-3.2.tar.gz')
> installarchive('http://cran.r-project.org/src/contrib/Archive/Hmisc/Hmisc_3.10-1.tar.gz','Hmisc_3.10-1.tar.gz')
> installarchive('http://cran.r-project.org/src/contrib/Archive/mvtnorm/mvtnorm_0.9-9994.tar.gz','mvtnorm_0.9-9994.tar.gz')
> installarchive('http://cran.r-project.org/src/contrib/Archive/multcomp/multcomp_1.2-14.tar.gz','mvtnorm_0.9-9994.tar.gz','multcomp_1.2-14.tar.gz')

c) Update Rserve

Add ggplot2 to the list of packages to be loaded by default in:

/var/FastRWeb/code/rserve.R
## This is jsut a friendly way to load package and report success/failure
## You will definiteily need FastRWeb, others are optional
pkgs <- c("XML", "Cairo", "Matrix", "FastRWeb", "RPostgreSQL", "ggplot2")
cat("Loading packages...\n")
for (pkg in pkgs) cat(pkg, ": ",require(pkg, quietly=TRUE, character.only=TRUE),"\n",sep='')

It will be necessary to restart Rserve if Rserve was previously running.

$ sudo /etc/init.d/rserve restart

d) Create a ggplot2 FastRWeb R script.

Create file /var/FastRWeb/web.R/ggplottest.png.R with the following content:

# ggplottest.png.R
run <- function(...) {
    p <- WebPlot(800,600)
    gp <- ggplot(diamonds, aes(clarity, fill=cut))+geom_bar()
    print(gp)
    p
}

e) Test the installation.

Navigate to the following location:

http://localhost/cgi-bin/R/ggplottest.png

A chart of size 800×600 should be displayed for ggplot2 diamonds data.

Further resources:

Advertisements