#!/bin/sh
#
# Initialize script for Apache Hadoop pseudo distributed mode.
#
# Copyright 2013, whitestar
#
# Licensed 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.
#

HADOOP_PREFIX=<%= node['grid']['app_root'] %>/hadoop
GRID_VOL_ROOT=<%= node['grid']['vol_root'] %>

echo 'Initializing Hadoop ...'

hostname --fqdn
if [ $? -ne 0 ]; then
  echo 'Unknown host! Check the /etc/hosts file and DNS lookup settings.'
  echo 'aborted.'
  exit 1
fi

<% if node['hadoop']['with_security'] then -%>
sudo -u hdfs kinit
<% end -%>
<%
case @major_version
when '3'
-%>
sudo -u hdfs hadoop namenode -format
echo 'Starting HDFS ...'
sudo service hadoop-0.20-namenode start
sudo service hadoop-0.20-datanode start
echo 'Waiting for HDFS to leave the safe mode ...'
sudo -u hdfs hadoop dfsadmin -safemode wait
echo 'Setup directories on HDFS ...'
sudo -u hdfs hadoop fs -chown hdfs:hdfs /
sudo -u hdfs hadoop fs -chmod 755 /
sudo -u hdfs hadoop fs -mkdir /user
sudo -u hdfs hadoop fs -mkdir ${GRID_VOL_ROOT}/0/var/lib/mapred
sudo -u hdfs hadoop fs -chown mapred:mapred ${GRID_VOL_ROOT}/0/var/lib/mapred
echo 'done.'
echo 'Stopping HDFS ...'
sudo service hadoop-0.20-datanode stop
sudo service hadoop-0.20-namenode stop
<%
when '4', '5'
-%>
sudo -u hdfs hdfs namenode -format
echo 'Starting HDFS ...'
sudo service hadoop-hdfs-namenode start
sudo service hadoop-hdfs-datanode start
echo 'Waiting for HDFS to leave the safe mode ...'
sudo -u hdfs hdfs dfsadmin -safemode wait
echo 'Setup directories on HDFS ...'
sudo -u hdfs hadoop fs -chown hdfs:hdfs /
sudo -u hdfs hadoop fs -chmod 755 /
sudo -u hdfs hadoop fs -mkdir /user
  <% if @resource_negotiator_framework == 'YARN' then -%>
sudo -u hdfs hadoop fs -mkdir -p ${GRID_VOL_ROOT}/0/var/log/yarn/nm
sudo -u hdfs hadoop fs -chown yarn:hadoop ${GRID_VOL_ROOT}/0/var/log/yarn/nm
sudo -u hdfs hadoop fs -chmod 1777        ${GRID_VOL_ROOT}/0/var/log/yarn/nm
  <% end -%>
sudo -u hdfs hadoop fs -mkdir -p ${GRID_VOL_ROOT}/0/var/lib/mapred/history
sudo -u hdfs hadoop fs -chown -R mapred:hadoop ${GRID_VOL_ROOT}/0/var/lib/mapred
sudo -u hdfs hadoop fs -chmod -R 755           ${GRID_VOL_ROOT}/0/var/lib/mapred
echo 'done.'
echo 'Stopping HDFS ...'
sudo service hadoop-hdfs-datanode stop
sudo service hadoop-hdfs-namenode stop
<%
end
-%>

echo 'Hadoop initialization complete.'
