wtorek, 16 kwietnia 2013

RPi - Running services at boot

I wanted to start a few services while my Rasperry Pi is booting. Since my days as linux "administrator" are gone, I needed to do some research how to achieve that.

Services to be started: H2 database server, serial port listening service, tomcat - in that order.

Naturally, all applications have been installed.
First step - prepare script files:

/etc/init.d/h2 file:
#!/bin/bash

### BEGIN INIT INFO
# Provides:          h2
# Required-Start:
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: h2 database
# Description:       h2 database
### END INIT INFO


test -f /lib/lsb/init-functions || exit 1
. /lib/lsb/init-functions

H2_HOME=/opt/h2
DAEMON=h2server
ARGS=


#PID=$(get_pid $DAEMON)

case "$1" in
 start)
  log_begin_msg "Starting h2 database"
   $H2_HOME/bin/$DAEMON $ARGS & #>/dev/null
   log_end_msg 0
   ;;
 stop)
   log_begin_msg "Stopping $DAEMON"
   kill `ps aux | awk '/h2.*jar/{print $2}'` > /dev/null
   ;;
 restart)
   $0 stop
   sleep 1
   $0 start
   ;;
 *)
   echo "usage: $0 {start|stop|restart}"  
esac


/etc/init.d/rxreader file:
#!/bin/bash

### BEGIN INIT INFO
# Provides:          rxreader
# Required-Start: $tomcat
# Required-Stop: $tomcat
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: rxreader
# Description:       rxreader
### END INIT INFO


test -f /lib/lsb/init-functions || exit 1
. /lib/lsb/init-functions

RXRD_HOME=/opt/rxreader
DAEMON=read
ARGS=


case "$1" in
 start)
  log_begin_msg "Starting h2 database"
   #[ -z "$PID" ] && 
   $RXRD_HOME/bin/$DAEMON $ARGS & #>/dev/null
   log_end_msg 0
   ;;
 stop)
   log_begin_msg "Stopping $DAEMON"
   kill `ps aux | awk '/rxreader/{print $2}'` > /dev/null
   ;;
 restart)
   $0 stop
   sleep 1
   $0 start
   ;;
 *)
   echo "usage: $0 {start|stop|restart}"  
esac

/etc/init.d/tomcat file:
#!/bin/bash

### BEGIN INIT INFO
# Provides:          tomcat
# Required-Start: $h2
# Required-Stop: $h2
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: tomcat
# Description:       tomcat
### END INIT INFO


test -f /lib/lsb/init-functions || exit 1
. /lib/lsb/init-functions

TOMCAT_HOME=/opt/apache-tomcat-7
DAEMON=startup.sh
ARGS=


case "$1" in
 start)
  log_begin_msg "Starting apache tomcat"
   $TOMCAT_HOME/bin/$DAEMON $ARGS & #>/dev/null
   log_end_msg 0
   ;;
 stop)
   log_begin_msg "Stopping $DAEMON"
   $TOMCAT_HOME/bin/shutdown.sh
   ;;
 restart)
   $0 stop
   sleep 1
   $0 start
   ;;
 *)
   echo "usage: $0 {start|stop|restart}"  
esac

When file are in /etc/init.d directory we have to run update-rc command, which installs (or removes) System-V style init script links:
sudo update-rc.d h2 defaults
sudo update-rc.d tomcat defaults
sudo update-rc.d rxreader defaults

Now you can restart RPi or start services manually:
sudo service h2 start
sudo service rxreader start
sudo service tomcat start