How do I run Java as a service on Ubuntu? - java

So after 2 days (yes I'm a complete rookie when it comes to servers) trying to get this working I give up and turn to SO for help :)
I want to start my java app on start, log to a logfile. That's it :)
start on runlevel [2345]
stop on runlevel [!2345]
#Respawn the process if it crashes
#If it respawns more than 10 times in 5 seconds stop
respawn
respawn limit 10 5
expect fork
script
cd /home/ubuntu/admin/
mvn spring-boot:run > /var/log/upstart/admin.log 2>&1
end script
Running "sudo start admin" works and I get "admin start/running" in console.. No log is created and the java app is not started.. ?
What am I missing?
How do I run Java as a service on Ubuntu?

I don't mean to sidetrack, but I've deployed Java applications on Ubuntu in production since 2010 and had very little success with Upstart. I use init.d scripts and start-stop-daemon. Side bonus: it works on more distros.
Create /etc/init.d/my-java-app:
#!/bin/sh
#
# my-java-app My Java App
#
# chkconfig: - 80 05
# description: Enable My Java Application
#
### BEGIN INIT INFO
# Provides: my-java-app
# Required-Start: $remote_fs $network
# Required-Stop: $remote_fs $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Description: My Java Application
# Short-Description: Enable My Java Application
### END INIT INFO
DESC="my java app"
NAME=my-java-app
PIDFILE=/var/run/$NAME.pid
RUN_AS=ubuntu
WORK_DIR=/home/ubuntu/admin
DAEMON=/usr/bin/mvn
DAEMON_OPTS="spring-boot:run"
# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh
# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions
do_start() {
start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE \
--background \
--chuid $RUN_AS \
--chdir $WORK_DIR \
--exec $DAEMON -- $DAEMON_OPTS
}
do_stop() {
start-stop-daemon --stop --quiet --pidfile $PIDFILE
if [ -e $PIDFILE ]
then rm $PIDFILE
fi
}
case "$1" in
start)
echo -n "Starting $DESC: $NAME"
do_start
echo "."
;;
stop)
echo -n "Stopping $DESC: $NAME"
do_stop
echo "."
;;
restart)
echo -n "Restarting $DESC: $NAME"
do_stop
sleep 1
do_start
echo "."
;;
status)
status_of_proc -p $PIDFILE "$DAEMON" "$NAME" && exit 0 || exit $?
;;
*)
echo "usage: $NAME {start|stop|restart}"
exit 1
;;
esac
Make it belong to root, make it executable, and set it up to run on startup with:
sudo chown root:root /etc/init.d/my-java-app
sudo chmod 755 /etc/init.d/my-java-app
sudo update-rc.d my-java-app defaults
To start the service you can run:
sudo service my-java-app start
To stop the service you can run:
sudo service my-java-app stop
This is based on a simplified version of the /etc/init.d/skeleton file included by Ubuntu.
The man page for start-stop-daemon is worth looking at if you want to tweak this further.b

Related

How to create Linux service

I am trying to run my jar as a service because my server should not shouting down when the system is getting shutdown. So I plan to start the server as a service.
My script is,
#!/bin/sh
### BEGIN INIT INFO
# Provides: myservice
# Required-Start: $local_fs $remote_fs $network $syslog
# Required-Stop: $local_fs $remote_fs $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# X-Interactive: true
# Short-Description: Start/stop myservice server
### END INIT INFO
JARPATH="/usr/local/myservice/lib"
PID=$JARPATH/pid
start() {
echo "Starting myservice ..."
if [ ! -f $PID ]; then
nohup java -jar $JARPATH/myservice-1.0.0.jar $JARPATH 2>> /dev/null >> /dev/null &
echo $! > $PID
echo "myservice started ..."
else
echo "myservice is already running ..."
fi
}
stop() {
if [ -f $PID ]; then
#PID=$(cat /usr/local/myservice/pid);
echo "Stopping myservice ..."
kill $(cat "$PID");
echo "myservice stopped ..."
rm $PID
else
echo "myservice is not running ..."
fi
}
case $1 in
start)
echo $JARPATH
echo $PID
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
esac
And I did the following steps,
sudo chmod +x /etc/init.d/myservice
sudo update-rc.d myservice defaults
And then start the service using the following command, But the above script is not working...
sudo service myservice start
Here what did I wrong??
Kindly provide your thoughts.
The above script works fine when I put a double quotes in $1,
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
esac

jboss_init_redhat is not working

I used Redhat and Jboss 4.2.2 GA for application server.
I have a basic problem that when I try to run
./jboss_init_redhat.sh start
is not working.
Basicly I want to run inside jboss_init_redhat.sh file;
/opt/jboss/bin/run.sh -c X -b 0.0.0.0
This line is working but jboss_init_redhat.sh not working.That's our problem.
I checked all permissions but there is not any permission problem.
jboss_init_redhat.sh is below:
#!/bin/sh
#
# $Id: jboss_init_redhat.sh 60992 2007-02-28 11:33:27Z dimitris#jboss.org $
#
# JBoss Control Script
#
# To use this script run it as root - it will switch to the specified user
#
# Here is a little (and extremely primitive) startup/shutdown script
# for RedHat systems. It assumes that JBoss lives in /usr/local/jboss,
# it's run by user 'jboss' and JDK binaries are in /usr/local/jdk/bin.
# All this can be changed in the script itself.
#
# Either modify this script for your requirements or just ensure that
# the following variables are set correctly before calling the script.
#define where jboss is - this is the directory containing directories log, bin, conf etc
JBOSS_HOME=${JBOSS_HOME:-"/opt/jboss"}
#define the user under which jboss will run, or use 'RUNASIS' to run as the current user
JBOSS_USER=${JBOSS_USER:-"jboss"}
#make sure java is in your path
JAVAPTH=${JAVAPTH:-"/usr/local/jdk/bin"}
#configuration to use, usually one of 'minimal', 'default', 'all'
JBOSS_CONF=${JBOSS_CONF:-"ikarus"}
#if JBOSS_HOST specified, use -b to bind jboss services to that address
JBOSS_HOST="0.0.0.0"
JBOSS_BIND_ADDR=${JBOSS_HOST:+"-b $JBOSS_HOST"}
#define the classpath for the shutdown class
JBOSSCP=${JBOSSCP:-"$JBOSS_HOME/bin/shutdown.jar:$JBOSS_HOME/client/jnet.jar"}
#define the script to use to start jboss
JBOSSSH=${JBOSSSH:-"$JBOSS_HOME/bin/run.sh -c $JBOSS_CONF $JBOSS_BIND_ADDR"}
if [ "$JBOSS_USER" = "RUNASIS" ]; then
SUBIT=""
else
SUBIT="su - $JBOSS_USER -c "
fi
if [ -n "$JBOSS_CONSOLE" -a ! -d "$JBOSS_CONSOLE" ]; then
# ensure the file exists
touch $JBOSS_CONSOLE
if [ ! -z "$SUBIT" ]; then
chown $JBOSS_USER $JBOSS_CONSOLE
fi
fi
if [ -n "$JBOSS_CONSOLE" -a ! -f "$JBOSS_CONSOLE" ]; then
echo "WARNING: location for saving console log invalid: $JBOSS_CONSOLE"
echo "WARNING: ignoring it and using /dev/null"
JBOSS_CONSOLE="/dev/null"
fi
#define what will be done with the console log
JBOSS_CONSOLE=${JBOSS_CONSOLE:-"/dev/null"}
JBOSS_CMD_START="cd $JBOSS_HOME/bin; $JBOSSSH"
JBOSS_CMD_STOP=${JBOSS_CMD_STOP:-"java -classpath $JBOSSCP org.jboss.Shutdown --shutdown"}
if [ -z "`echo $PATH | grep $JAVAPTH`" ]; then
export PATH=$PATH:$JAVAPTH
fi
if [ ! -d "$JBOSS_HOME" ]; then
echo JBOSS_HOME does not exist as a valid directory : $JBOSS_HOME
exit 1
fi
echo JBOSS_CMD_START = $JBOSS_CMD_START
case "$1" in
start)
cd $JBOSS_HOME/bin
if [ -z "$SUBIT" ]; then
eval $JBOSS_CMD_START >${JBOSS_CONSOLE} 2>&1 &
else
$SUBIT "$JBOSS_CMD_START >${JBOSS_CONSOLE} 2>&1 &"
fi
;;
stop)
if [ -z "$SUBIT" ]; then
$JBOSS_CMD_STOP
else
$SUBIT "$JBOSS_CMD_STOP"
fi
;;
restart)
$0 stop
$0 start
;;
*)
echo "usage: $0 (start|stop|restart|help)"
esac
If you change JBOSS_USER information to RUNASIS, it should work properly.

tomcat remote debug mode in linux

I am setting tomcat in debug mode. Tomcat server is running on different machine and I am working on different machine.
Before starting tomcat I am executing following linux command.
iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 9003 -j ACCEPT
export JPDA_ADDRESS=9003
export JPDA_TRANSPORT=dt_socket
export JPDA_SUSPEND=n
bin/catalina.sh jpda start
In eclipse I am providing IP address of remote machine and port number 9003.
My ./catalina.sh file is given below. But still I am not able to see green color debug pointers at breakpoint. What to do ? Eclipse doesn't throw any exception while connecting to remote machine. Earlier it was throwing 'Connection failed' but once I executed following command it was rectified, but not able to see breakpoints even after I have given breakpoints.
iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 9003 -j ACCEPT
my cataline.sh file.
#!/bin/sh
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -----------------------------------------------------------------------------
# Control Script for the CATALINA Server
#
# Environment Variable Prerequisites
#
# Do not set the variables in this script. Instead put them into a script
# setenv.sh in CATALINA_BASE/bin to keep your customizations separate.
#
# CATALINA_HOME May point at your Catalina "build" directory.
#
# CATALINA_BASE (Optional) Base directory for resolving dynamic portions
# of a Catalina installation. If not present, resolves to
# the same directory that CATALINA_HOME points to.
#
# CATALINA_OUT (Optional) Full path to a file where stdout and stderr
# will be redirected.
# Default is $CATALINA_BASE/logs/catalina.out
#
# CATALINA_OPTS (Optional) Java runtime options used when the "start",
# "run" or "debug" command is executed.
# Include here and not in JAVA_OPTS all options, that should
# only be used by Tomcat itself, not by the stop process,
# the version command etc.
# Examples are heap size, GC logging, JMX ports etc.
#
# CATALINA_TMPDIR (Optional) Directory path location of temporary directory
# the JVM should use (java.io.tmpdir). Defaults to
# $CATALINA_BASE/temp.
#
# JAVA_HOME Must point at your Java Development Kit installation.
# Required to run the with the "debug" argument.
#
# JRE_HOME Must point at your Java Runtime installation.
# Defaults to JAVA_HOME if empty. If JRE_HOME and JAVA_HOME
# are both set, JRE_HOME is used.
#
# JAVA_OPTS (Optional) Java runtime options used when any command
# is executed.
# Include here and not in CATALINA_OPTS all options, that
# should be used by Tomcat and also by the stop process,
# the version command etc.
# Most options should go into CATALINA_OPTS.
#
# JAVA_ENDORSED_DIRS (Optional) Lists of of colon separated directories
# containing some jars in order to allow replacement of APIs
# created outside of the JCP (i.e. DOM and SAX from W3C).
# It can also be used to update the XML parser implementation.
# Defaults to $CATALINA_HOME/endorsed.
#
# JPDA_TRANSPORT (Optional) JPDA transport used when the "jpda start"
# command is executed. The default is "dt_socket".
#
# JPDA_ADDRESS (Optional) Java runtime options used when the "jpda start"
# command is executed. The default is 8000.
#
# JPDA_SUSPEND (Optional) Java runtime options used when the "jpda start"
# command is executed. Specifies whether JVM should suspend
# execution immediately after startup. Default is "n".
#
# JPDA_OPTS (Optional) Java runtime options used when the "jpda start"
# command is executed. If used, JPDA_TRANSPORT, JPDA_ADDRESS,
# and JPDA_SUSPEND are ignored. Thus, all required jpda
# options MUST be specified. The default is:
#
# -agentlib:jdwp=transport=$JPDA_TRANSPORT,
# address=$JPDA_ADDRESS,server=y,suspend=$JPDA_SUSPEND
#
# CATALINA_PID (Optional) Path of the file which should contains the pid
# of the catalina startup java process, when start (fork) is
# used
#
# LOGGING_CONFIG (Optional) Override Tomcat's logging config file
# Example (all one line)
# LOGGING_CONFIG="-Djava.util.logging.config.file=$CATALINA_BASE/conf/logging.properties"
#
# LOGGING_MANAGER (Optional) Override Tomcat's logging manager
# Example (all one line)
# LOGGING_MANAGER="-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager"
# -----------------------------------------------------------------------------
# OS specific support. $var _must_ be set to either true or false.
cygwin=false
darwin=false
os400=false
case "`uname`" in
CYGWIN*) cygwin=true;;
Darwin*) darwin=true;;
OS400*) os400=true;;
esac
# resolve links - $0 may be a softlink
PRG="$0"
while [ -h "$PRG" ]; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`/"$link"
fi
done
# Get standard environment variables
PRGDIR=`dirname "$PRG"`
# Only set CATALINA_HOME if not already set
[ -z "$CATALINA_HOME" ] && CATALINA_HOME=`cd "$PRGDIR/.." >/dev/null; pwd`
# Copy CATALINA_BASE from CATALINA_HOME if not already set
[ -z "$CATALINA_BASE" ] && CATALINA_BASE="$CATALINA_HOME"
# Ensure that any user defined CLASSPATH variables are not used on startup,
# but allow them to be specified in setenv.sh, in rare case when it is needed.
CLASSPATH=
if [ -r "$CATALINA_BASE/bin/setenv.sh" ]; then
. "$CATALINA_BASE/bin/setenv.sh"
elif [ -r "$CATALINA_HOME/bin/setenv.sh" ]; then
. "$CATALINA_HOME/bin/setenv.sh"
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin; then
[ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$JRE_HOME" ] && JRE_HOME=`cygpath --unix "$JRE_HOME"`
[ -n "$CATALINA_HOME" ] && CATALINA_HOME=`cygpath --unix "$CATALINA_HOME"`
[ -n "$CATALINA_BASE" ] && CATALINA_BASE=`cygpath --unix "$CATALINA_BASE"`
[ -n "$CLASSPATH" ] && CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For OS400
if $os400; then
# Set job priority to standard for interactive (interactive - 6) by using
# the interactive priority - 6, the helper threads that respond to requests
# will be running at the same priority as interactive jobs.
COMMAND='chgjob job('$JOBNAME') runpty(6)'
system $COMMAND
# Enable multi threading
export QIBM_MULTI_THREADED=Y
fi
# Get standard Java environment variables
if $os400; then
# -r will Only work on the os400 if the files are:
# 1. owned by the user
# 2. owned by the PRIMARY group of the user
# this will not work if the user belongs in secondary groups
. "$CATALINA_HOME"/bin/setclasspath.sh
else
if [ -r "$CATALINA_HOME"/bin/setclasspath.sh ]; then
. "$CATALINA_HOME"/bin/setclasspath.sh
else
echo "Cannot find $CATALINA_HOME/bin/setclasspath.sh"
echo "This file is needed to run this program"
exit 1
fi
fi
# Add on extra jar files to CLASSPATH
if [ ! -z "$CLASSPATH" ] ; then
CLASSPATH="$CLASSPATH":
fi
CLASSPATH="$CLASSPATH""$CATALINA_HOME"/bin/bootstrap.jar
if [ -z "$CATALINA_OUT" ] ; then
CATALINA_OUT="$CATALINA_BASE"/logs/catalina.out
fi
if [ -z "$CATALINA_TMPDIR" ] ; then
# Define the java.io.tmpdir to use for Catalina
CATALINA_TMPDIR="$CATALINA_BASE"/temp
fi
# Add tomcat-juli.jar to classpath
# tomcat-juli.jar can be over-ridden per instance
if [ -r "$CATALINA_BASE/bin/tomcat-juli.jar" ] ; then
CLASSPATH=$CLASSPATH:$CATALINA_BASE/bin/tomcat-juli.jar
else
CLASSPATH=$CLASSPATH:$CATALINA_HOME/bin/tomcat-juli.jar
fi
# Bugzilla 37848: When no TTY is available, don't output to console
have_tty=0
if [ "`tty`" != "not a tty" ]; then
have_tty=1
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
JAVA_HOME=`cygpath --absolute --windows "$JAVA_HOME"`
JRE_HOME=`cygpath --absolute --windows "$JRE_HOME"`
CATALINA_HOME=`cygpath --absolute --windows "$CATALINA_HOME"`
CATALINA_BASE=`cygpath --absolute --windows "$CATALINA_BASE"`
CATALINA_TMPDIR=`cygpath --absolute --windows "$CATALINA_TMPDIR"`
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
JAVA_ENDORSED_DIRS=`cygpath --path --windows "$JAVA_ENDORSED_DIRS"`
fi
# Set juli LogManager config file if it is present and an override has not been issued
if [ -z "$LOGGING_CONFIG" ]; then
if [ -r "$CATALINA_BASE"/conf/logging.properties ]; then
LOGGING_CONFIG="-Djava.util.logging.config.file=$CATALINA_BASE/conf/logging.properties"
else
# Bugzilla 45585
LOGGING_CONFIG="-Dnop"
fi
fi
if [ -z "$LOGGING_MANAGER" ]; then
LOGGING_MANAGER="-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager"
fi
# Uncomment the following line to make the umask available when using the
# org.apache.catalina.security.SecurityListener
#JAVA_OPTS="$JAVA_OPTS -Dorg.apache.catalina.security.SecurityListener.UMASK=`umask`"
# ----- Execute The Requested Command -----------------------------------------
# Bugzilla 37848: only output this if we have a TTY
if [ $have_tty -eq 1 ]; then
echo "Using CATALINA_BASE: $CATALINA_BASE"
echo "Using CATALINA_HOME: $CATALINA_HOME"
echo "Using CATALINA_TMPDIR: $CATALINA_TMPDIR"
if [ "$1" = "debug" ] ; then
echo "Using JAVA_HOME: $JAVA_HOME"
else
echo "Using JRE_HOME: $JRE_HOME"
fi
echo "Using CLASSPATH: $CLASSPATH"
if [ ! -z "$CATALINA_PID" ]; then
echo "Using CATALINA_PID: $CATALINA_PID"
fi
fi
if [ "$1" = "jpda" ] ; then
if [ -z "$JPDA_TRANSPORT" ]; then
JPDA_TRANSPORT="dt_socket"
fi
if [ -z "$JPDA_ADDRESS" ]; then
JPDA_ADDRESS="8000"
fi
if [ -z "$JPDA_SUSPEND" ]; then
JPDA_SUSPEND="n"
fi
if [ -z "$JPDA_OPTS" ]; then
JPDA_OPTS="-agentlib:jdwp=transport=$JPDA_TRANSPORT,address=$JPDA_ADDRESS,server=y,suspend=$JPDA_SUSPEND"
fi
CATALINA_OPTS="$CATALINA_OPTS $JPDA_OPTS"
shift
fi
if [ "$1" = "debug" ] ; then
if $os400; then
echo "Debug command not available on OS400"
exit 1
else
shift
if [ "$1" = "-security" ] ; then
if [ $have_tty -eq 1 ]; then
echo "Using Security Manager"
fi
shift
exec "$_RUNJDB" "$LOGGING_CONFIG" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
-Djava.endorsed.dirs="$JAVA_ENDORSED_DIRS" -classpath "$CLASSPATH" \
-sourcepath "$CATALINA_HOME"/../../java \
-Djava.security.manager \
-Djava.security.policy=="$CATALINA_BASE"/conf/catalina.policy \
-Dcatalina.base="$CATALINA_BASE" \
-Dcatalina.home="$CATALINA_HOME" \
-Djava.io.tmpdir="$CATALINA_TMPDIR" \
org.apache.catalina.startup.Bootstrap "$#" start
else
exec "$_RUNJDB" "$LOGGING_CONFIG" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
-Djava.endorsed.dirs="$JAVA_ENDORSED_DIRS" -classpath "$CLASSPATH" \
-sourcepath "$CATALINA_HOME"/../../java \
-Dcatalina.base="$CATALINA_BASE" \
-Dcatalina.home="$CATALINA_HOME" \
-Djava.io.tmpdir="$CATALINA_TMPDIR" \
org.apache.catalina.startup.Bootstrap "$#" start
fi
fi
elif [ "$1" = "run" ]; then
shift
if [ "$1" = "-security" ] ; then
if [ $have_tty -eq 1 ]; then
echo "Using Security Manager"
fi
shift
eval exec "\"$_RUNJAVA\"" "\"$LOGGING_CONFIG\"" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
-Djava.endorsed.dirs="\"$JAVA_ENDORSED_DIRS\"" -classpath "\"$CLASSPATH\"" \
-Djava.security.manager \
-Djava.security.policy=="\"$CATALINA_BASE/conf/catalina.policy\"" \
-Dcatalina.base="\"$CATALINA_BASE\"" \
-Dcatalina.home="\"$CATALINA_HOME\"" \
-Djava.io.tmpdir="\"$CATALINA_TMPDIR\"" \
org.apache.catalina.startup.Bootstrap "$#" start
else
eval exec "\"$_RUNJAVA\"" "\"$LOGGING_CONFIG\"" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
-Djava.endorsed.dirs="\"$JAVA_ENDORSED_DIRS\"" -classpath "\"$CLASSPATH\"" \
-Dcatalina.base="\"$CATALINA_BASE\"" \
-Dcatalina.home="\"$CATALINA_HOME\"" \
-Djava.io.tmpdir="\"$CATALINA_TMPDIR\"" \
org.apache.catalina.startup.Bootstrap "$#" start
fi
elif [ "$1" = "start" ] ; then
if [ ! -z "$CATALINA_PID" ]; then
if [ -f "$CATALINA_PID" ]; then
if [ -s "$CATALINA_PID" ]; then
echo "Existing PID file found during start."
if [ -r "$CATALINA_PID" ]; then
PID=`cat "$CATALINA_PID"`
ps -p $PID >/dev/null 2>&1
if [ $? -eq 0 ] ; then
echo "Tomcat appears to still be running with PID $PID. Start aborted."
exit 1
else
echo "Removing/clearing stale PID file."
rm -f "$CATALINA_PID" >/dev/null 2>&1
if [ $? != 0 ]; then
if [ -w "$CATALINA_PID" ]; then
cat /dev/null > "$CATALINA_PID"
else
echo "Unable to remove or clear stale PID file. Start aborted."
exit 1
fi
fi
fi
else
echo "Unable to read PID file. Start aborted."
exit 1
fi
else
rm -f "$CATALINA_PID" >/dev/null 2>&1
if [ $? != 0 ]; then
if [ ! -w "$CATALINA_PID" ]; then
echo "Unable to remove or write to empty PID file. Start aborted."
exit 1
fi
fi
fi
fi
fi
shift
touch "$CATALINA_OUT"
if [ "$1" = "-security" ] ; then
if [ $have_tty -eq 1 ]; then
echo "Using Security Manager"
fi
shift
eval "\"$_RUNJAVA\"" "\"$LOGGING_CONFIG\"" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
-Djava.endorsed.dirs="\"$JAVA_ENDORSED_DIRS\"" -classpath "\"$CLASSPATH\"" \
-Djava.security.manager \
-Djava.security.policy=="\"$CATALINA_BASE/conf/catalina.policy\"" \
-Dcatalina.base="\"$CATALINA_BASE\"" \
-Dcatalina.home="\"$CATALINA_HOME\"" \
-Djava.io.tmpdir="\"$CATALINA_TMPDIR\"" \
org.apache.catalina.startup.Bootstrap "$#" start \
>> "$CATALINA_OUT" 2>&1 "&"
else
eval "\"$_RUNJAVA\"" "\"$LOGGING_CONFIG\"" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
-Djava.endorsed.dirs="\"$JAVA_ENDORSED_DIRS\"" -classpath "\"$CLASSPATH\"" \
-Dcatalina.base="\"$CATALINA_BASE\"" \
-Dcatalina.home="\"$CATALINA_HOME\"" \
-Djava.io.tmpdir="\"$CATALINA_TMPDIR\"" \
org.apache.catalina.startup.Bootstrap "$#" start \
>> "$CATALINA_OUT" 2>&1 "&"
fi
if [ ! -z "$CATALINA_PID" ]; then
echo $! > "$CATALINA_PID"
fi
echo "Tomcat started."
elif [ "$1" = "stop" ] ; then
shift
SLEEP=5
if [ ! -z "$1" ]; then
echo $1 | grep "[^0-9]" >/dev/null 2>&1
if [ $? -gt 0 ]; then
SLEEP=$1
shift
fi
fi
FORCE=0
if [ "$1" = "-force" ]; then
shift
FORCE=1
fi
if [ ! -z "$CATALINA_PID" ]; then
if [ -f "$CATALINA_PID" ]; then
if [ -s "$CATALINA_PID" ]; then
kill -0 `cat "$CATALINA_PID"` >/dev/null 2>&1
if [ $? -gt 0 ]; then
echo "PID file found but no matching process was found. Stop aborted."
exit 1
fi
else
echo "PID file is empty and has been ignored."
fi
else
echo "\$CATALINA_PID was set but the specified file does not exist. Is Tomcat running? Stop aborted."
exit 1
fi
fi
eval "\"$_RUNJAVA\"" $LOGGING_MANAGER $JAVA_OPTS \
-Djava.endorsed.dirs="\"$JAVA_ENDORSED_DIRS\"" -classpath "\"$CLASSPATH\"" \
-Dcatalina.base="\"$CATALINA_BASE\"" \
-Dcatalina.home="\"$CATALINA_HOME\"" \
-Djava.io.tmpdir="\"$CATALINA_TMPDIR\"" \
org.apache.catalina.startup.Bootstrap "$#" stop
# stop failed. Shutdown port disabled? Try a normal kill.
if [ $? != 0 ]; then
if [ ! -z "$CATALINA_PID" ]; then
echo "The stop command failed. Attempting to signal the process to stop through OS signal."
kill -15 `cat "$CATALINA_PID"` >/dev/null 2>&1
fi
fi
if [ ! -z "$CATALINA_PID" ]; then
if [ -f "$CATALINA_PID" ]; then
while [ $SLEEP -ge 0 ]; do
kill -0 `cat "$CATALINA_PID"` >/dev/null 2>&1
if [ $? -gt 0 ]; then
rm -f "$CATALINA_PID" >/dev/null 2>&1
if [ $? != 0 ]; then
if [ -w "$CATALINA_PID" ]; then
cat /dev/null > "$CATALINA_PID"
# If Tomcat has stopped don't try and force a stop with an empty PID file
FORCE=0
else
echo "The PID file could not be removed or cleared."
fi
fi
echo "Tomcat stopped."
break
fi
if [ $SLEEP -gt 0 ]; then
sleep 1
fi
if [ $SLEEP -eq 0 ]; then
if [ $FORCE -eq 0 ]; then
echo "Tomcat did not stop in time. PID file was not removed. To aid diagnostics a thread dump has been written to standard out."
kill -3 `cat "$CATALINA_PID"`
fi
fi
SLEEP=`expr $SLEEP - 1 `
done
fi
fi
KILL_SLEEP_INTERVAL=5
if [ $FORCE -eq 1 ]; then
if [ -z "$CATALINA_PID" ]; then
echo "Kill failed: \$CATALINA_PID not set"
else
if [ -f "$CATALINA_PID" ]; then
PID=`cat "$CATALINA_PID"`
echo "Killing Tomcat with the PID: $PID"
kill -9 $PID
while [ $KILL_SLEEP_INTERVAL -ge 0 ]; do
kill -0 `cat "$CATALINA_PID"` >/dev/null 2>&1
if [ $? -gt 0 ]; then
rm -f "$CATALINA_PID" >/dev/null 2>&1
if [ $? != 0 ]; then
if [ -w "$CATALINA_PID" ]; then
cat /dev/null > "$CATALINA_PID"
else
echo "The PID file could not be removed."
fi
fi
# Set this to zero else a warning will be issued about the process still running
KILL_SLEEP_INTERVAL=0
echo "The Tomcat process has been killed."
break
fi
if [ $KILL_SLEEP_INTERVAL -gt 0 ]; then
sleep 1
fi
KILL_SLEEP_INTERVAL=`expr $KILL_SLEEP_INTERVAL - 1 `
done
if [ $KILL_SLEEP_INTERVAL -gt 0 ]; then
echo "Tomcat has not been killed completely yet. The process might be waiting on some system call or might be UNINTERRUPTIBLE."
fi
fi
fi
fi
elif [ "$1" = "configtest" ] ; then
eval "\"$_RUNJAVA\"" $LOGGING_MANAGER $JAVA_OPTS \
-Djava.endorsed.dirs="\"$JAVA_ENDORSED_DIRS\"" -classpath "\"$CLASSPATH\"" \
-Dcatalina.base="\"$CATALINA_BASE\"" \
-Dcatalina.home="\"$CATALINA_HOME\"" \
-Djava.io.tmpdir="\"$CATALINA_TMPDIR\"" \
org.apache.catalina.startup.Bootstrap configtest
result=$?
if [ $result -ne 0 ]; then
echo "Configuration error detected!"
fi
exit $result
elif [ "$1" = "version" ] ; then
"$_RUNJAVA" \
-classpath "$CATALINA_HOME/lib/catalina.jar" \
org.apache.catalina.util.ServerInfo
else
echo "Usage: catalina.sh ( commands ... )"
echo "commands:"
if $os400; then
echo " debug Start Catalina in a debugger (not available on OS400)"
echo " debug -security Debug Catalina with a security manager (not available on OS400)"
else
echo " debug Start Catalina in a debugger"
echo " debug -security Debug Catalina with a security manager"
fi
echo " jpda start Start Catalina under JPDA debugger"
echo " run Start Catalina in the current window"
echo " run -security Start in the current window with security manager"
echo " start Start Catalina in a separate window"
echo " start -security Start in a separate window with security manager"
echo " stop Stop Catalina, waiting up to 5 seconds for the process to end"
echo " stop n Stop Catalina, waiting up to n seconds for the process to end"
echo " stop -force Stop Catalina, wait up to 5 seconds and then use kill -KILL if still running"
echo " stop n -force Stop Catalina, wait up to n seconds and then use kill -KILL if still running"
echo " configtest Run a basic syntax check on server.xml - check exit code for result"
echo " version What version of tomcat are you running?"
echo "Note: Waiting for the process to end and use of the -force option require that \$CATALINA_PID is defined"
exit 1
fi

How to start Apache Solr automatically? [duplicate]

At the moment I have to go to /usr/java/apache-solr-1.4.0/example and then do:
java -jar start.jar
How do I get this to start automatically on boot?
I'm on a shared Linux server.
As you're on a shared Linux box, you'll have to ask the system administrator to do the following, probably.
Create a startup script in /etc/init.d/solr.
Copy this code, my Solr startup script, into that file:
#!/bin/sh
# Prerequisites:
# 1. Solr needs to be installed at /usr/local/solr/example
# 2. daemon needs to be installed
# 3. Script needs to be executed by root
# This script will launch Solr in a mode that will automatically respawn if it
# crashes. Output will be sent to /var/log/solr/solr.log. A PID file will be
# created in the standard location.
start () {
echo -n "Starting solr..."
# Start daemon
daemon --chdir='/usr/local/solr/example' --command "java -jar start.jar" --respawn --output=/var/log/solr/solr.log --name=solr --verbose
RETVAL=$?
if [ $RETVAL = 0 ]
then
echo "done."
else
echo "failed. See error code for more information."
fi
return $RETVAL
}
stop () {
# Stop daemon
echo -n "Stopping solr..."
daemon --stop --name=solr --verbose
RETVAL=$?
if [ $RETVAL = 0 ]
then
echo "Done."
else
echo "Failed. See error code for more information."
fi
return $RETVAL
}
restart () {
daemon --restart --name=solr --verbose
}
status () {
# Report on the status of the daemon
daemon --running --verbose --name=solr
return $?
}
case "$1" in
start)
start
;;
status)
status
;;
stop)
stop
;;
restart)
restart
;;
*)
echo $"Usage: solr {start|status|stop|restart}"
exit 3
;;
esac
exit $RETVAL
Then run:
chkconfig --add solr
Or (on Ubuntu):
update-rc.d solr defaults
... or, if your Linux distribution doesn't have chkconfig (or update-rc.d), link /etc/init.d/solr to /etc/rc3.d/S99solr and /etc/rc5.d/S99solr and /etc/rc3.d/K01solr and /etc/rc5.d/K01solr:
% ln -s /etc/init.d/solr /etc/rc3.d/S99solr
% ln -s /etc/init.d/solr /etc/rc5.d/S99solr
% ln -s /etc/init.d/solr /etc/rc3.d/K01solr
% ln -s /etc/init.d/solr /etc/rc5.d/K01solr
Now on reboot Solr will startup in run levels 3 and 5 (console with network & full GUI).
To start solr manually run:
% /etc/init.d/solr start
If you have root access to your machine, there are a number of ways to do this based on your system's initialization flow (init scripts, systemd, etc.)
But if you don't have root, cron has a clean and consistent way to execute programs upon reboot.
First, find out where java is located on your machine. The command below will tell you where it is:
$ which java
Then, stick the following code into a shell script, replacing the java path below (/usr/bin) with the path you got from the above command.
#!/bin/bash
cd /usr/java/apache-solr-1.4.0/example
/usr/bin/java -jar start.jar
You can save this script in some location (e.g., $HOME) as start.sh. Give it world execute permission (to simplify) by running the following command:
$ chmod og+x start.sh
Now, test the script and ensure that it works correctly from the command line.
$ ./start.sh
If all works well, you need to add it to one of your machine's startup scripts. The simplest way to do this is to add the following line to the end of /etc/rc.local.
# ... snip contents of rc.local ...
# Start Solr upon boot.
/home/somedir/start.sh
Alternatively, if you don't have permission to edit rc.local, then you can add it to your user crontab as so. First type the following on the commandline:
$ crontab -e
This will bring up an editor. Add the following line to it:
#reboot /home/somedir/start.sh
If your Linux system supports it (which it usually does), this will ensure that your script is run upon startup.
If I don't have any typos above, it should work out well for you. Let me know how it goes.
Adding the following lines to my /etc/init.d/solr file works to support Red Hat Linux (I copied them from /etc/init.d/mysql after reading comments by others here).
# Comments to support chkconfig on Red Hat Linux
# chkconfig: 2345 64 36
# Description: A very fast and reliable search engine.
There are three steps that you need to do here:
Create the script, make it executable, and put it in the right place.
Make the script start up properly on reboot.
Bonus: Set up a logrotation script so logs don't get out of control.
For number one, I've tuned supermagic's script from above. It was OK, but had a number of typos, lacked some functionality (status, restart), didn't use the daemon utility very effectively.
Here's my version of the script (make sure you have daemon installed for it to work):
#!/bin/sh
# Prerequisites:
# 1. Solr needs to be installed at /usr/local/solr/example
# 2. daemon needs to be installed
# 3. Script needs to be executed by root
# This script will launch Solr in a mode that will automatically respawn if it
# crashes. Output will be sent to /var/log/solr/solr.log. A pid file will be
# created in the standard location.
start () {
echo -n "Starting solr..."
# start daemon
daemon --chdir='/usr/local/solr/example' --command "java -jar start.jar" --respawn --output=/var/log/solr/solr.log --name=solr --verbose
RETVAL=$?
if [ $RETVAL = 0 ]
then
echo "done."
else
echo "failed. See error code for more information."
fi
return $RETVAL
}
stop () {
# stop daemon
echo -n "Stopping solr..."
daemon --stop --name=solr --verbose
RETVAL=$?
if [ $RETVAL = 0 ]
then
echo "done."
else
echo "failed. See error code for more information."
fi
return $RETVAL
}
restart () {
daemon --restart --name=solr --verbose
}
status () {
# report on the status of the daemon
daemon --running --verbose --name=solr
return $?
}
case "$1" in
start)
start
;;
status)
status
;;
stop)
stop
;;
restart)
restart
;;
*)
echo $"Usage: solr {start|status|stop|restart}"
exit 3
;;
esac
exit $RETVAL
Place this script at /etc/init.d/solr, make it executable, and you should be good with step one. You can now start/stop/restart/status a solr daemon with /etc/init.d/solr start|stop|restart|status
For step two, run the following on an Ubuntu machine (don't know about Redhat):
update-rc.d solr defaults
Once this is done, you're in pretty good shape, but you probably want to rotate the logs properly at some point, so here's a good config for the logs:
/var/log/solr/*.log {
weekly
rotate 12
compress
delaycompress
create 640 root root
postrotate
/etc/init.d/solr restart
endscript
}
Place that file in /etc/logrotate.d/solr, and you should be good to go, assuming logrotate is running (it usually is).
I answered this question once already, but that answer was for operating systems that used SysV and this one is for newer operating systems that are increasingly using systemd.
As in my other answer, there are three things you'll need to do here:
Create the script and put it in the right place.
Make the script start up properly on reboot.
Bonus: Make systemd logs persistent.
1. Creating the script and putting it in the right place
Here's a systemd unit file that you can use (these replace the SysV init files). Name it solr.service.
[Unit]
Description=Apache Solr
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=simple
Environment="XMX=2G"
WorkingDirectory=/usr/local/solr/example
ExecStart=/usr/bin/java -jar -server -Xmx${XMX} start.jar
Restart=on-failure
LimitNOFILE=10000
[Install]
WantedBy=multi-user.target
Note that there's a configuration in there for Solr's memory. You'll probably want to tweak that to your own purposes. If you have a number of variables you're passing to systemd, you can do that with the EnvironmentFile directive.
More documentation for these files is here.
2. Make the script startup properly at boot
This is fairly simple, but there are rules. To make it start at boot, put the file in /etc/systemd/system/solr.service. You cannot use a symlink in this directory, do not try.
Once that's in there, you can enable the daemon to run at boot with:
sudo systemctl enable solr
And you can start, stop, status it with:
sudo systemctl {start|stop|status} solr
3. Making systemd logs persistent
By default, systemd logs are not persistent and they are lost whenever you reboot the system. If that's not what you desire, you can make them persistent by creating a directory:
sudo mkdir -p /var/log/journal/
And then restarting the systemd journaling daemon:
sudo systemctl restart systemd-journald
Once that's complete, systemd's journaling daemon will receive all the stdout and stderr that Solr creates and it will get stored in a binary format under /var/log/journal/.
The way systemd handles logging is pretty neat and is worth studying if you're not familiar with it. In the meantime, just know that to read your log entries you'll need to use a new tool called journalctl. For example, this will follow your solr logs:
journalctl -u solr -f
And there are also flags for doing date-based filtering and things like that.
3.1 Tweaking the log files
Bonus section! If you want to tweak the log files, you can read all about it in the documentation here, but the defaults are actually very safe and sane (logs are compressed by default, can't grow too large, are rate limited, and are written to disk in batches).
Follow supermagic's comments, then follow this
http://codingrecipes.com/service-x-does-not-support-chkconfig
He says,
1 – Copy your script into /etc/init.d folder
2 – cd /etc/init.d
3 – chmod +x myscript
4 – Add these lines, including #, right after #!/bin/bash or #!/bin/sh:
# chkconfig: 2345 95 20
# description: Some description
# What your script does (not sure if this is necessary though)
# processname: myscript
Then you can do
chkconfig --add myscript
init.d/solr script that's tested on Centos 6/Amazon Linux. It wraps solr's native CLI.
#!/bin/bash
# description: Starts and stops Solr production
PIDFILE=/var/run/solr.pid
SOLR_HOME=/usr/share/solr
START_COMMAND="$SOLR_HOME/bin/solr start -p 8984 -noprompt -m 1g"
NAME="Solr"
start() {
echo "Starting $NAME"
if [ -f $PIDFILE ]; then
echo -n "$PIDFILE exists. $NAME may be running."
else
str=`$START_COMMAND`
pid=`echo $str | grep -o "pid=[0-9]*" | grep -o "[0-9]*"`
if [ "$pid" == "" ];
then
echo "[FATAL ERROR] Failed to extract pid. Exiting!"
exit 1
fi
echo $pid > $PIDFILE
fi
return 0
}
case "$1" in
start)
start
;;
stop)
echo "Stopping $NAME .."
$SOLR_HOME/bin/solr stop
rm -f $PIDFILE
;;
status)
$SOLR_HOME/bin/solr status
;;
restart)
$0 stop
#sleep 2
$0 start
;;
*)
echo "Usage: $0 (start | stop | restart | status)"
exit 1
;;
esac
exit $?
Check
man 5 crontab
See if #reboot is supported on the Linux system you are using.

Java "java.util.logging.Logger" does not work when running with nohup

I created a Java application which is supposed to run as an ubuntu service. I followed this article: Running a Java program as a daemon in Ubuntu Linux
This is my script in /etc/init.d/ dir:
#!/bin/sh
### BEGIN INIT INFO
# Provides: myservice
# Required-Start: $local_fs $remote_fs $network $syslog
# Required-Stop: $local_fs $remote_fs $network $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# X-Interactive: true
# Short-Description: Start/stop myservice
### END INIT INFO
case $1 in
status)
if [ -f /opt/myservice/pid ]; then
PID=$(cat /opt/myservice/pid);
echo "myservice is running. PID="$PID
else
echo "myservice is not running."
fi
;;
start)
if [ ! -f /opt/myservice/pid ]; then
nohup java -jar /opt/myservice/billing_consumer.jar /opt/myservice 2>> /dev/null >> /dev/null &
echo $! > /opt/myservice/pid
echo "myservice started ..."
else
echo "myservice is already running ..."
fi
;;
stop)
if [ -f /opt/myservice/pid ]; then
PID=$(cat /opt/myservice/pid);
kill $PID;
echo "myservice stopped ..."
rm /opt/myservice/pid
else
echo "myservice is not running ..."
fi
;;
restart)
if [ -f /opt/myservice/pid ]; then
PID=$(cat /opt/myservice/pid);
echo "Stopping myservice ...";
kill $PID;
echo "myservice stopped ...";
rm /opt/myservice/pid
echo "Starting myservice ..."
nohup java -jar /opt/myservice/billing_consumer.jar /opt/myservice 2>> /dev/null >> /dev/null &
echo $! > /opt/myservice/pid
echo "myservice started ..."
else
echo "myservice is not running ..."
fi
;;
esac
It seems that this script closes the billing_consumer.jar standard input and redirects output to /dev/null; which, I read somewhere that it's the bitbucket which is used for redirecting console's output to that in this place. Also I don't have anything to be sent to stderr or stdout except some third party components which use those outputs. I myself use java's builting logging API (java.util.logging.Logger) to log information. I use the java.util.logging.FileHandler as the handler for logging outputs. But the problem is that, when I run the program as a service logging does not work. But when I run the program manually, I can see the logs written in the files. This is my logging.properties file used for logging configuration:
handlers = java.util.logging.FileHandler
config =
java.util.logging.FileHandler.level = ALL
java.util.logging.FileHandler.filter =
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter
java.util.logging.FileHandler.encoding =
java.util.logging.FileHandler.limit = 1048576
java.util.logging.FileHandler.count = 20
java.util.logging.FileHandler.append = true
java.util.logging.FileHandler.pattern = logs/billing-log.%u.%g.log
...
I don't think this has anything to do with the /etc/init.d/myservice script, Since I changed that to redirect the output to a file also and I could see that the third party components' outputs are written in the file. Although, I am not writing to terminals' output. Can anyone figure out what is the problem here. Do I have configured logging the wrong way?
In your logging properties you are using a relative path. When you run this as a service the current/working directory is probably different from when you run this manually. The FileHandler will fail to create a new log file if the directory path doesn't exist. Set the working directory or change the path to an absolute path.
The 'config =' line looks wrong since there is no value.
If that doesn't work you should modify the script to pipe the out/err streams to a file to debug what is going on.

Categories

Resources