Do not limit your challenges.. Challenge your limits

BTemplates.com

Search This Blog

Powered by Blogger.

About Me

My photo
kathmandu, Bagmati, Nepal
I am Software developer based on Nepal.I have started coding since mid of 1995 with QBasic.My interest in software development covers a broad range of technologies from assembly to the Microsoft .NET platform to Java, Linux to Windows, Windows Mobile to Android, desktop to web to mobile, and many others. But from 2007 I am just working on Java mainly working on Java EE platform and decided just to go with it. I really like to learn new stuff and share things with others which is my main objective in creating this blog.

ArchUnit : Java architecture test library

Finally I have found the required library which will enforce architecture patterns . ArchUnit  . Currently I am exploring it and will upd...

Thursday, March 14, 2013

Running java application as linux daemon



Linux daemon is a application which runs as a background process,rather than being under the direct control of an interactive user.We can create a java application that can run as daemon process. Here is few step which will help to create a linux daemon process.
  1. Create a bash script in /etc/init.d/logging as below
#!/bin/bash
#
# chkconfig: 345 99 05
# description: Java deamon script

# service name with the first letter in lowercase 
serviceNameLo="logger"
# service name   
serviceName="logger"
# OS user name for the service  ,we need to create user, by useradd command    
serviceUser="logger"
# OS group name for the service, we can use usermod -a -G groupName userName
serviceGroup="logger"
# home directory of the service application    
applDir="/opt/logger"   
# home directory of the service user
serviceUserHome="/home/$serviceUser"
# log file for StdOut/StdErr
serviceLogFile="/opt/logger/log/$serviceNameLo.log"
# max number of seconds to wait for the daemon to terminate normally 
maxShutdownTime=15
# name of PID file (PID = process ID number)
pidFile="/opt/logger/temp/$serviceNameLo.pid"
# name of the Java launcher without the path
javaCommand="java"
# arguments for Java launcher     
javaArgs="-jar $applDir/logger.jar"
# command line to start the Java service application
javaCommandLine="java $javaArgs"
# a keyword that occurs on the commandline, used to detect an already running service process and to distinguish it from others
javaCommandLineKeyword="logger.jar"
 
# Makes the file $1 writable by the group $serviceGroup.
function makeFileWritable {
   local filename="$1"
   touch $filename || return 1
   chgrp $serviceGroup $filename || return 1
   chmod g+w $filename || return 1
   return 0; }
 
# Returns 0 if the process with PID $1 is running.
function checkProcessIsRunning {
   local pid="$1"
   if [ -z "$pid" -o "$pid" == " " ]; then return 1; fi
   if [ ! -e /proc/$pid ]; then return 1; fi
   return 0; }
 
# Returns 0 if the process with PID $1 is our Java service process.
function checkProcessIsOurService {
   local pid="$1"
   if [ "$(ps -p $pid --no-headers -o comm)" != "$javaCommand" ]; then return 1; fi
   grep -q --binary -F "$javaCommandLineKeyword" /proc/$pid/cmdline
   if [ $? -ne 0 ]; then return 1; fi
   return 0; }
 
# Returns 0 when the service is running and sets the variable $pid to the PID.
function getServicePID {
   if [ ! -f $pidFile ]; then return 1; fi
   pid="$(<$pidFile)"
   checkProcessIsRunning $pid || return 1
   checkProcessIsOurService $pid || return 1
   return 0; }
 
function startServiceProcess {
   cd $applDir || return 1
   rm -f $pidFile
   makeFileWritable $pidFile || return 1
   makeFileWritable $serviceLogFile || return 1
   cmd="nohup $javaCommandLine >>$serviceLogFile 2>&1 & echo \$! >$pidFile"
   su -m $serviceUser -s $SHELL -c "$cmd" || return 1
   sleep 0.1
   pid="$(<$pidFile)"
   if checkProcessIsRunning $pid; then :; else
      echo -ne "\n$serviceName start failed, see logfile."
      return 1
   fi
   return 0; }
 
function stopServiceProcess {
   kill $pid || return 1
   for ((i=0; i<maxShutdownTime*10; i++)); do
      checkProcessIsRunning $pid
      if [ $? -ne 0 ]; then
         rm -f $pidFile
         return 0
         fi
      sleep 0.1
      done
   echo -e "\n$serviceName did not terminate within $maxShutdownTime seconds, sending SIGKILL..."
   kill -s KILL $pid || return 1
   local killWaitTime=15
   for ((i=0; i<killWaitTime*10; i++)); do
      checkProcessIsRunning $pid
      if [ $? -ne 0 ]; then
         rm -f $pidFile
         return 0
         fi
      sleep 0.1
      done
   echo "Error: $serviceName could not be stopped within $maxShutdownTime+$killWaitTime seconds!"
   return 1; }
 
function startService {
   getServicePID
   if [ $? -eq 0 ]; then echo -n "$serviceName is already running"; RETVAL=0; return 0; fi
   echo -n "Starting $serviceName   "
   startServiceProcess
   if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi
   echo "started PID=$pid"
   RETVAL=0
   return 0; }
 
function stopService {
   getServicePID
   if [ $? -ne 0 ]; then echo -n "$serviceName is not running"; RETVAL=0; echo ""; return 0; fi
   echo -n "Stopping $serviceName   "
   stopServiceProcess
   if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi
   echo "stopped PID=$pid"
   RETVAL=0
   return 0; }
 
function checkServiceStatus {
   echo -n "Checking for $serviceName:   "
   if getServicePID; then
    echo "running PID=$pid"
    RETVAL=0
   else
    echo "stopped"
    RETVAL=3
   fi
   return 0; }
 
function main {
   RETVAL=0
   case "$1" in
      start)                                               # starts the Java program as a Linux service
         startService
         ;;
      stop)                                                # stops the Java program service
         stopService
         ;;
      restart)                                             # stops and restarts the service
         stopService && startService
         ;;
      status)                                              # displays the service status
         checkServiceStatus
         ;;
      *)
         echo "Usage: $0 {start|stop|restart|status}"
         exit 1
         ;;
      esac
   exit $RETVAL
}
 
main $1


2.  sudo chmod a+x /etc/init.d/logging

3.  chkconfig --add logging 

4.  chkconfig --level 2345 logging on

5.  update-rc.d logging defaults


Now , we can start ,stop service using below command

  • sudo service logging start
  • sudo service logging stop
  • sudo service logging restart
  • sudo service logging status

0 comments:

Post a Comment