Après vous avoir proposé un rapide comparatif des solutions de pastebin-like en auto-hébergé, voici donc un tutoriel pour l’installation de haste-server. Haste utilise la technologie Node.js. Il est configurable en un fichier, et dispose même d’un client Ruby à utiliser dans son terminal. Enfin il s’appuie sur les couleurs foncées de Solarized.
J’en profite donc pour vous proposer quelques lignes sur la gestion des versions Node.js.
Pour ce tutoriel, je suis sur une Debian Squeeze, avec redis
, à vous d’adapter en fonction de votre système.
Etape 1 : créer un utilisateur dédié
La première chose à effectuer est de créer sur votre système un utilisateur dédié au service que nous allons mettre en place.
En ligne de commande, dans votre terminal :
adduser --home /home/hastebin hastebin --ingroup users
Ici je défini à minima le dossier utilisateur (situé dans mon répertoire standard /home) et le groupe d’utilisateurs auquel ce compte est rattaché. Si vous souhaitez davantage sur les commandes liées à la création d’utilisateur je vous renvoie sur cette page.
Etape 2 : installer Node.js
Si vous avez déjà une installation de Node.js sur votre machine, vous pouvez passer à l’étape suivante évidemment. Sinon voici de quoi l’installer. Plusieurs méthodes cohabitent pour l’installation de Node.js, que ça soit depuis la source, depuis git ou depuis les répertoires Sid. Node.js évoluant rapidement c’est assez embêtant de devoir prendre le risque que votre application ne fonctionne plus avec la nouvelle version de Node.js. C’est là que l’installation avec une gestion des versions est intéressantes. Au choix :
Méthode 1 :
- Installer Node.js selon la méthode qui vous plait,
- Installer ensuite le module de TJ Holowaychuk (créateur d’Express JS) nommé n :
sudo npm install -g n # puis la commande qui permet de récupérer la dernière version sudo n latest # si besoin vous pouvez lister les version installées faites simplement n # et évidemment tout le reste est disponible dans le man de n
Méthode 2 :
Il existe pour Node.js un script qui permet de gérer les versions utilisées de la même façon que RVM pour Ruby. Il s’agit de NVM, dont vous trouverez toute la documentation sur Github.
Pour l’installer rien de plus simple :
curl https://raw.github.com/creationix/nvm/master/install.sh | sh
Ensuite on installe la version de node désirée avec la commande :
nvm install 0.10 nvm use 0.10
Etape 3 : installer redis
Pour redis, il y a pas mal de tutoriels sur le net … donc je vous laisse chercher un peu. Je proposerai plus tard un tutoriel pour vous présenter ma configuration redis
.
Etape 4 : installer haste-server
Commençons par nous positionner dans le répertoire hastebin (cf. étape 1) puis récupérons depuis Github le contenu et attribuons les droits.
# à adapter en fonction du nom d'utilisateur et du dossier choisi à l'étape 1 : cd /home/hastebin # puis récupérons les fichiers via Github git clone https://github.com/seejohnrun/haste-server.git # attribuons les bons droits (à adapter en fonction du nom d'utilisateur et du dossier choisi à l'étape 1) chown -R hastebin:users /home/hastebin/haste-server chmod -R 755 /home/hastebin/haste-server
Ensuite, pour installer haste-server, positionnons nous dans le dossier :
# à adapter en fonction du nom d'utilisateur et du dossier choisi à l'étape 1 évidemment cd /home/hastebin/haste-server su hastebin npm install
Etape 5 : modifier/adapter la configuration de haste-server
Editez le fichier /home/hastebin/haste-server/config.js
soit avec votre éditeur favori soit via le terminal et nano : nano /home/hastebin/haste-server/config.js
.
L’ensemble des paramètres que vous pouvez éditer est disponible ici : https://github.com/seejohnrun/haste-server/blob/master/README.md.
Mais attardez vous sur les suivants :
-
port
: le port sur lequel sera joignable votre application haste-server, par défaut 7777, mais pour moi, je le personnaliserai en 9003, -
host
: le nom d’hôte de votre serveur, par défautlocalhost
.
Si comme moi vous utilisez redis
il vous faudra faire un petit npm install redis
puis modifier le fichier /home/hastebin/haste-server/config.js
pour la section suivante, en personnalisant notamment le port redis
que vous utilisez :
{ "type": "redis", "host": "localhost", "port": 6379, "db": 2 }
Sachez que vous pouvez aussi utiliser memcached
alternativement à redis
.
Etape 6 : tester …
Pour effectuer un test :
# à adapter en fonction du nom d'utilisateur et du dossier choisi à l'étape 1 évidemment cd /home/hastebin/haste-server su hastebin npm start
Allez ensuite sur le navigateur de la machine puis entrez l’adresse http://localhost:9003
. Votre application node.js haste-server devrait être accessible. Quittez le processus depuis votre terminal avec CTL+c.
Etape 7 : lancer haste-server en tant que service au boot de la machine
Là-encore plusieurs alternatives s’offrent à nous. Je suis parti sur un script dans /etc/init.d
. Pour ce faire, créez le script /etc/init.d/hastebin
avec le contenu suivant :
#!/bin/bash ### BEGIN INIT INFO # Provides: hastebin # Required-Start: $local_fs $remote_fs $network $syslog $redis_server # Required-Stop: $local_fs $remote_fs $network $syslog $redis_server # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: starts hastebin # Description: starts hastebin ### END INIT INFO PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin # modify if you need DAEMON_ARGS="/home/hastebin/haste-server/server.js" # path to your node.js server/app DESC="node.js pastebin server" # whatever fancy description you like NODEUSER=hastebin:users # USER who OWNS the daemon process (no matter whoever runs the init script) LOCAL_VAR_RUN=/var/run # in case the init script is run by non-root user, you need to NAME=node # name of the node.js executable DAEMON=/usr/local/bin/$NAME # this SHOULD POINT TO where your node executable is # Do NOT "set -e" [ $UID -eq "0" ] && LOCAL_VAR_RUN=/var/run # in case this script is run by root, override user setting THIS_ARG=$0 INIT_SCRIPT_NAME=`basename $THIS_ARG` [ -h $THIS_ARG ] && INIT_SCRIPT_NAME=`basename $(readlink $THIS_ARG)` # in case of symlink INIT_SCRIPT_NAME_NOEXT=${INIT_SCRIPT_NAME%.*} PIDFILE="$LOCAL_VAR_RUN/$INIT_SCRIPT_NAME_NOEXT.pid" SCRIPTNAME=/etc/init.d/$INIT_SCRIPT_NAME # Exit if the package is not installed [ -x "$DAEMON" ] || { echo "can't find Node.js ($DAEMON)" >&2; exit 0; } # Exit if the 'run' folder is not present [ -d "$LOCAL_VAR_RUN" ] || { echo "Directory $LOCAL_VAR_RUN does not exist. Modify the '$INIT_SCRIPT_NAME_NOEXT' init.d script ($THIS_ARG) accordingly" >&2; exit 0; } # Read configuration variable file if it is present [ -r /etc/default/$INIT_SCRIPT_NAME ] && . /etc/default/$INIT_SCRIPT_NAME # Load the VERBOSE setting and other rcS variables . /lib/init/vars.sh # Define LSB log_* functions. # Depend on lsb-base (>= 3.0-6) to ensure that this file is present. . /lib/lsb/init-functions # uncomment to override system setting # VERBOSE=yes # # Function that starts the daemon/service # do_start() { # Return # 0 if daemon has been started # 1 if daemon was already running # 2 if daemon could not be started start-stop-daemon --start --quiet --pidfile $PIDFILE --chuid $NODEUSER --chdir /home/hastebin/haste-server/ --background --exec $DAEMON --test > /dev/null \ || { [ "$VERBOSE" != no ] && log_daemon_msg " ---> Daemon already running $DESC" "$INIT_SCRIPT_NAME_NOEXT"; return 1; } start-stop-daemon --start --quiet --chuid $NODEUSER --make-pidfile --pidfile $PIDFILE --chdir /home/hastebin/haste-server/ --background --exec $DAEMON -- \ $DAEMON_ARGS \ || { [ "$VERBOSE" != no ] && log_daemon_msg " ---> could not be start $DESC" "$INIT_SCRIPT_NAME_NOEXT"; return 2; } # Add code here, if necessary, that waits for the process to be ready # to handle requests from services started subsequently which depend # on this one. As a last resort, sleep for some time. [ "$VERBOSE" != no ] && log_daemon_msg " ---> started $DESC" "$INIT_SCRIPT_NAME_NOEXT" } # # Function that stops the daemon/service # do_stop() { # Return # 0 if daemon has been stopped # 1 if daemon was already stopped # 2 if daemon could not be stopped # other if a failure occurred start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --chuid $NODEUSER --exec $DAEMON RETVAL="$?" #[ "$VERBOSE" != no ] && [ "$RETVAL" = 1 ] && log_daemon_msg " ---> SIGKILL failed => hardkill $DESC" "$INIT_SCRIPT_NAME_NOEXT" [ "$RETVAL" = 2 ] && return 2 # Wait for children to finish too if this is a daemon that forks # and if the daemon is only ever run from this initscript. # If the above conditions are not satisfied then add some other code # that waits for the process to drop all resources that could be # needed by services started subsequently. A last resort is to # sleep for some time. start-stop-daemon --stop --quiet --oknodo --retry=0/3/KILL/5 --pidfile $PIDFILE --chuid $NODEUSER --exec $DAEMON -- $DAEMON_ARGS [ "$?" = 2 ] && return 2 # Many daemons don't delete their pidfiles when they exit. rm -f $PIDFILE [ "$VERBOSE" != no ] && [ "$RETVAL" = 1 ] && log_daemon_msg " ---> $DESC not running" "$INIT_SCRIPT_NAME_NOEXT" [ "$VERBOSE" != no -a "$RETVAL" = 0 ] && log_daemon_msg " ---> $DESC stopped" "$INIT_SCRIPT_NAME_NOEXT" return "$RETVAL" } # # Function that sends a SIGHUP to the daemon/service # do_reload() { # # If the daemon can reload its configuration without # restarting (for example, when it is sent a SIGHUP), # then implement that here. # start-stop-daemon --stop --quiet --signal 1 --pidfile $PIDFILE --chuid $NODEUSER --name $NAME return 0 } # # Function that returns the daemon # do_status() { # # http://refspecs.freestandards.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/iniscrptact.html # 0 program is running or service is OK # 1 program is dead and /var/run pid file exists # (2 program is dead and /var/lock lock file exists) (not used here) # 3 program is not running # 4 program or service status is unknown RUNNING=$(running) # $PIDFILE corresponds to a live $NAME process ispidactive=$(pidof $NAME | grep `cat $PIDFILE 2>&1` >/dev/null 2>&1) ISPIDACTIVE=$? if [ -n "$RUNNING" ]; then if [ $ISPIDACTIVE ]; then log_success_msg "$INIT_SCRIPT_NAME_NOEXT (launched by $USER) (--chuid $NODEUSER) is running" exit 0 fi else if [ -f $PIDFILE ]; then log_success_msg "$INIT_SCRIPT_NAME_NOEXT (launched by $USER) (--chuid $NODEUSER) is not running, phantom pidfile $PIDFILE" exit 1 else log_success_msg "no instance launched by $USER, of $INIT_SCRIPT_NAME_NOEXT (--chuid $NODEUSER) found" exit 3 fi fi } running() { RUNSTAT=$(start-stop-daemon --start --quiet --pidfile $PIDFILE --chuid $NODEUSER --background --exec $DAEMON --test > /dev/null) if [ "$?" = 1 ]; then echo y fi } case "$1" in start) [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$INIT_SCRIPT_NAME_NOEXT" do_start case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; stop) [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$INIT_SCRIPT_NAME_NOEXT" do_stop case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; #reload|force-reload) # # If do_reload() is not implemented then leave this commented out # and leave 'force-reload' as an alias for 'restart'. # #log_daemon_msg "Reloading $DESC" "$NAME" #do_reload #log_end_msg $? #;; restart|force-reload) # # If the "reload" option is implemented then remove the # 'force-reload' alias # log_daemon_msg "Restarting $DESC" "$INIT_SCRIPT_NAME_NOEXT" do_stop case "$?" in 0|1) do_start case "$?" in 0) log_end_msg 0 ;; 1) log_end_msg 1 ;; # Old process is still running *) log_end_msg 1 ;; # Failed to start esac ;; *) # Failed to stop log_end_msg 1 ;; esac ;; status) do_status ;; *) echo "Usage: $SCRIPTNAME {status|start|stop|restart|force-reload}" >&2 exit 3 ;; esac
Il faut évidemment penser personnaliser les lignes :
# Provides: hastebin
avec le nom du service, ici hastebin
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
de sorte que le PATH contienne bien le dossier où est disponible node.js et haste-serverNODEUSER=hastebin:users
en fonction de l’utilisateur et du groupe d’utilisateurs choisi en étape 1
à rendre ce script exécutable : sudo chmod 755 /etc/init.d/hastebin
puis le tester avec /etc/init.d/hastebin start
pour lancer et /etc/init.d/hastebin stop
pour quitter.
Si tout fonctionne, vous pouvez ensuite dire au système qu’il faut charger ce service au démarrage avec sudo update-rc.d hastebin
.
Etape 8 : utiliser un nom de domaine propre et le proxy d’apache
Pour optimiser l’ensemble, le mieux est maintenant de rendre disponible votre service disponible depuis un port web standard (80), en utilisant donc soit votre firewall soit le proxy web (Apache ou NGinx).
Ici je vous détaille la procédure pour Apache, celle pour NGinx est correctement documentée ici.
Pour ce tutoriel, nous allons rendre disponible haste-server sur le sous-domaine hastebin.monserveur.fr. Je pars du principe que ce nom de domaine pointe bien sur la machine sur laquelle vous travaillez).
Nous allons d’abord créer un domaine virtuel Apache avec sudo nano /etc/apache2/sites-available/hastebin.conf
.
Nous entrons les données suivantes :
<VirtualHost *:80> ServerName hastebin.monserveur.fr ServerSignature Off CustomLog /var/log/apache2/hastebin_access.log combined ErrorLog /var/log/apache2/hastebin_error.log ErrorLog syslog:local2 ProxyVia On ProxyRequests Off ProxyPass / http://localhost:9003/ ProxyPassReverse / http://localhost:9003/ ProxyPreserveHost on <Proxy *> Options FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Proxy> </VirtualHost>
Pensez évidemment à personnaliser le fichier en fonction de votre configuration, notamment :
ServerName hastebin.monserveur.fr
avec le bon nom de domaine
ProxyPass / http://localhost:9003/
etProxyPassReverse / http://localhost:9003/
avec le port qui est utilisé par haste-server (choisi à l’étape 5)
Il vous faut ensuite enchainer les commandes suivantes dans votre terminal :
# activer le domaine virtuel : a2ensite hastebin.conf # rechargeons la configuration d'apache /etc/init.d/apache2 reload # puis redémarrons apache /etc/init.d/apache2 restart
Vous pouvez ensuite faire vos tests sur http://hastebin.monserveur.fr
… et normalement tout roule.
Etape 9 : améliorons un peu tout ça
La première chose que vous pouvez faire pour améliorer un peu l’installation de ce service consiste à fermer dans iptables
le port 9003 (ou celui que vous avez assigné à l’application Node.js haste-server), en gardant évidemment un accès pour le loopback.
Ensuite, vous pouvez fanciser un peu l’interface si vous le voulez, en éditant le fichier /home/hastebin/haste-server/static/application.js
. Il faut chercher les lignes qui suivent “haste.prototype.configureButtons = function()” et modifier les textes portant l’intitulé “label” et “shortcutDescription”. Pour prendre en compte les modification il faudra redémarrer haste-server avec /etc/init.d/hastebin restart
.
Comme d’habitude tous vos commentaires sont les bienvenus !