Ubuntu – How to set JAVA_HOME for all users for “elasticsearch” program

bashenvironment-variables

I'm trying to set JAVA_HOME for elasticsearch but no luck till now.

I tried to set it in .bashrc, etc/environment, etc/.profile all fail.

this is the command I use to run elasticsearch:

sudo /etc/init.d/elasticsearch start

I tried debug the JAVA_HOME variable in terminal like this:

  1. echo $JAVA_HOME
  2. sudo echo $JAVA_HOME

I got the result /home/mockie/softwares/jdk1.8.0_45 for the both which is correct path for my JAVA.

I also tried debug /etc/init.d/elasticsearch like this:

echo "$JAVA_HOME/dodol"
exit 1

and the result was empty and only return "/dodol".

this is full code for etc/init.d/elasticsearch :
https://gist.github.com/mockiemockiz/c9547aee791ee04c2e1d

and this is my etc/environment:

    PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"

    JAVA_HOME=/home/mockie/softwares/jdk1.8.0_45

but when I try this :

$ sudo su
$ /etc/init.d/elasticsearch start

and it works! but what I want is to use sudo /etc/init.d/elasticsearch start without sudo su first. is it possible?

Best Answer

The problem turned out to be the SysV script /etc/init.d/elasticsearch itself.

In the script the PID_DIR variable is set as :

PID_DIR=/var/run/elasticsearch 

but there is no such directory exists and there is command to create it in the script too.

The NAME and PID_FILE are set as:

NAME=elasticsearch
PID_FILE="$PID_DIR/$NAME.pid" 

So when the PID_FILE is trying to create a file "$PID_DIR/$NAME.pid" (/var/run/elasticsearch/elasticseach.pid) in $PID_DIR (/var/run/elasticsearch/), it is getting:

touch: cannot touch ‘/var/run/elasticsearch/elasticsearch.pid’: No such file or directory 

error as the directory /var/run/elasticsearch does not exists already.

About the JAVA_HOME variable, the script /etc/init.d/elasticsearch is not using the system's variable rather using/creating its own version of the variable that is well defined in the script.

According to the script, if JAVA_HOME is not set in /etc/default/elasticsearch it will try to set it manually by searching for certain files in certain directories, otherwise it will left it blank.

Related Question