Building Enterprise JavaScript Applications
上QQ阅读APP看书,第一时间看更新

Ensuring Elasticsearch is running

Our API server depends on an active instance of Elasticsearch. Therefore, before we start our API server, let's make sure our Elasticsearch service is active. Add the following check under the shebang line:

RETRY_INTERVAL=${RETRY_INTERVAL:-0.2}
if ! systemctl --quiet is-active elasticsearch.service; then
sudo systemctl start elasticsearch.service
# Wait until Elasticsearch is ready to respond
until curl --silent $ELASTICSEARCH_HOSTNAME:$ELASTICSEARCH_PORT -w "" -o /dev/null; do
sleep $RETRY_INTERVAL
done
fi

First, we use the is-active command of systemctl to check whether the Elasticsearch service is active; the command will exit with a 0 if it is active, and a non-zero value if not.

Generally, when a process successfully executes, it will exit with a status of zero (0); otherwise, it will exit with a non-zero status code. Inside an if block, the exit codes have special meaning—a 0 exit code means true, and a non-zero exit code means false.

This means that if the service is not active, we'd use the start command of systemctl to start it. However, Elasticsearch takes time to initiate before it can respond to requests. Therefore, we are polling its endpoint with curl, and blocking downstream execution until Elasticsearch is ready.

If you're curious what the flags mean on the commands, you can get detailed documentation on them by using the man command. Try running man systemctl, man curl, and even man man! Some commands also support a -h or --help flag, which contains less information but is usually easier to digest.

We will retry the endpoint every 0.2 seconds. This is set in the RETRY_INTERVAL environment variable. The ${RETRY_INTERVAL:-0.2} syntax means we should only use the 0.2 value if the environment variable is not already set; in other words, the 0.2 value should be used as a default.