You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafodion.apache.org by db...@apache.org on 2015/11/05 22:46:31 UTC

[1/2] incubator-trafodion git commit: [TRAFODION-1576] Performance improvement for backup-restore and reducing offline interval for backup.

Repository: incubator-trafodion
Updated Branches:
  refs/heads/master 514479fd9 -> c20a4bc1e


[TRAFODION-1576] Performance improvement for backup-restore and reducing offline interval for backup.

B/R scrpt now starts Trafodion after snapshots are taken
Large and small table handled differently to make export and import faster.


Project: http://git-wip-us.apache.org/repos/asf/incubator-trafodion/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-trafodion/commit/bd960ca3
Tree: http://git-wip-us.apache.org/repos/asf/incubator-trafodion/tree/bd960ca3
Diff: http://git-wip-us.apache.org/repos/asf/incubator-trafodion/diff/bd960ca3

Branch: refs/heads/master
Commit: bd960ca35630427d852c2a6c21de3287d0139f4e
Parents: 397e06b
Author: Suresh Subbiah <su...@apache.org>
Authored: Mon Nov 2 23:15:12 2015 +0000
Committer: Suresh Subbiah <su...@apache.org>
Committed: Mon Nov 2 23:15:12 2015 +0000

----------------------------------------------------------------------
 core/sqf/.gitignore                             |    5 +
 core/sqf/Makefile                               |    7 +-
 core/sqf/hbase_utilities/Makefile               |   46 +
 .../backup_restore_functions.sh                 |   34 +-
 .../run_full_trafodion_backup.sh                |   31 +-
 .../run_full_trafodion_restore.sh               |   17 +-
 core/sqf/hbase_utilities/pom.xml                |   71 ++
 .../backuprestore/TrafExportSnapshot.java       | 1076 ++++++++++++++++++
 core/sqf/sqenvcom.sh                            |    2 +
 core/sqf/sql/scripts/install_apache_hadoop      |    2 +-
 core/sqf/sql/scripts/install_local_hadoop       |    4 +-
 11 files changed, 1282 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/bd960ca3/core/sqf/.gitignore
----------------------------------------------------------------------
diff --git a/core/sqf/.gitignore b/core/sqf/.gitignore
index d8cb2e5..c5cca17 100644
--- a/core/sqf/.gitignore
+++ b/core/sqf/.gitignore
@@ -59,3 +59,8 @@ Linux-x86_64/
 
 # sql regressions
 /rundir/
+
+# hbase_utilities
+/hbase_utilities/src/main/resources/
+/hbase_utilities/target/
+

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/bd960ca3/core/sqf/Makefile
----------------------------------------------------------------------
diff --git a/core/sqf/Makefile b/core/sqf/Makefile
index 979380f..1a37f25 100644
--- a/core/sqf/Makefile
+++ b/core/sqf/Makefile
@@ -41,7 +41,7 @@ SQL_W=$(MY_SQROOT)/../sql
     DP2=se
 
 MISC = win misc_sec
-SQ_COMPONENTS := make_sqevlog seabed stfs $(MISC) tm $(SEAMONSTER_TARGET) make_sql make_monitor tools
+SQ_COMPONENTS := make_sqevlog seabed stfs $(MISC) tm $(SEAMONSTER_TARGET) make_sql make_monitor tools hbase_utilities
 
 .PHONY: $(SQ_COMPONENTS)
 
@@ -85,6 +85,9 @@ monitor_ib:
 make_sqevlog: 
 	cd sqevlog; $(MAKE) 2>&1 | sed -e "s/$$/	##(SQF)/" ; exit $${PIPESTATUS[0]}
 
+hbase_utilities:
+	cd hbase_utilities; $(MAKE) 2>&1 | sed -e "s/$$/  ##(HBASE_UTIL)/" ; exit $${PIPESTATUS[0]}
+
 .PHONY: conn
 conn:
 	cd ../conn/odbc/src/odbc; $(MAKE) clean; $(MAKE) all 2>&1 | sed -e "s/$$/	##(NDCS)/" ; exit $${PIPESTATUS[0]}
@@ -105,6 +108,7 @@ clean: setupdir_clean
 	-cd src/tm; $(MAKE) clean
 	-cd sql; $(MAKE) WROOT=$(SQL_W) clean
 	-cd sqevlog; $(MAKE) clean
+	-cd hbase_utilities; $(MAKE) clean
 	# from genverhdr.ksh
 	rm -f export/include/SCMBuildStr.h export/include/SCMBuildStr.java
 	# from makemsg.ksh
@@ -119,6 +123,7 @@ cleanall: setupdir_clean
 	-cd src/tm; $(MAKE) cleanall
 	-cd sql; $(MAKE) WROOT=$(SQL_W) clean
 	-cd sqevlog; $(MAKE) cleanall
+	-cd hbase_utilities; $(MAKE) clean
 	# from genverhdr.ksh
 	rm -f export/include/SCMBuildStr.h export/include/SCMBuildStr.java
 	# from makemsg.ksh

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/bd960ca3/core/sqf/hbase_utilities/Makefile
----------------------------------------------------------------------
diff --git a/core/sqf/hbase_utilities/Makefile b/core/sqf/hbase_utilities/Makefile
new file mode 100644
index 0000000..1311b07
--- /dev/null
+++ b/core/sqf/hbase_utilities/Makefile
@@ -0,0 +1,46 @@
+# @@@ START COPYRIGHT @@@
+#
+# 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.
+#
+# @@@ END COPYRIGHT @@@
+
+# This Makefile is just a thin shell to Maven, which is used to do the real build
+
+include ../macros.gmk #top level
+
+.NOTPARALLEL: all
+
+all: build_all
+
+build_all:	 
+	$(MAKE) mavenbuild
+	echo "$(MAVEN) site package -DskipTests"
+	echo "### For full Maven output, see file build_utility.log"
+
+mavenbuild:
+        # create a jar manifest file with the correct version information
+	mkdir -p src/main/resources
+	$(MY_SQROOT)/export/include/SCMBuildJava.sh 1.0.1 > src/main/resources/trafodion-utility.jar.mf
+        # run maven
+	set -o pipefail && $(MAVEN) package -DskipTests | tee maven_build.log | grep -e '\[INFO\] Building' -e '\[INFO\] BUILD SUCCESS' -e 'ERROR'
+	cp -pf target/trafodion-utility-*.jar $(MY_SQROOT)/export/lib
+
+clean:
+	$(MAVEN) clean
+	$(RM) build_utility.log
+	$(RM) -rf $(MY_SQROOT)/export/lib/trafodion-utility-*.jar

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/bd960ca3/core/sqf/hbase_utilities/backup_and_restore/backup_restore_functions.sh
----------------------------------------------------------------------
diff --git a/core/sqf/hbase_utilities/backup_and_restore/backup_restore_functions.sh b/core/sqf/hbase_utilities/backup_and_restore/backup_restore_functions.sh
index 0c4abc9..e3e350b 100755
--- a/core/sqf/hbase_utilities/backup_and_restore/backup_restore_functions.sh
+++ b/core/sqf/hbase_utilities/backup_and_restore/backup_restore_functions.sh
@@ -24,7 +24,7 @@
 default_trafodion_user="trafodion"
 default_hbase_user="hbase"
 default_hdfs_user="hdfs"
-mappers=2
+mappers=0
 date_str="$(date '+%Y%m%d-%H%M')"
 
 ###############################################################################
@@ -412,3 +412,35 @@ get_hdfs_uri()
     echo ${fs_defFs}
   fi
 }
+###############################################################################
+#start_trafodion
+###############################################################################
+start_trafodion()
+{
+  local traf_user=$1
+  ###
+  echo "Starting Trafodion..."  | tee -a $log_file
+  ##
+  which_environment
+  local env1=$?
+  local sqstart_rc=1
+  if [[ "$USER" -eq "$traf_user" ]]; then
+    env1=1
+  fi
+  if [[ $env1 -eq 1 ]]; then
+    $MY_SQROOT/sql/scripts/sqstart
+    sqstart_rc=$?
+  elif [[ $env1 -eq 2 ]]; then
+    sudo -n -u $traf_user sh -c ". /home/trafodion/.bashrc; sqstart"  
+    sqstart_rc=$?
+  else
+    sqstart_rc=1 
+  fi
+
+  if [[ $sqstart_rc -eq 0 ]]; then
+   echo "Trafodion started successfully. Continuing ..." | tee -a $log_file
+  else
+   echo "Trafodion not started. Please start Trafodion at your convinience." | tee -a $log_file
+  fi
+  return 0
+}

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/bd960ca3/core/sqf/hbase_utilities/backup_and_restore/run_full_trafodion_backup.sh
----------------------------------------------------------------------
diff --git a/core/sqf/hbase_utilities/backup_and_restore/run_full_trafodion_backup.sh b/core/sqf/hbase_utilities/backup_and_restore/run_full_trafodion_backup.sh
index 793388f..4ed4e7a 100755
--- a/core/sqf/hbase_utilities/backup_and_restore/run_full_trafodion_backup.sh
+++ b/core/sqf/hbase_utilities/backup_and_restore/run_full_trafodion_backup.sh
@@ -33,7 +33,7 @@ usage()
   echo "The $0 script performs full offline backup of all Trafodion tables"
   echo "and copies the backup files to an HDFS location"
   echo "The command to use the script is as follows:"
-  echo "$0 -b backup_folder -b backup_dir -u trafodion_user -h hbase_user -d hdfs_user -m mappers -n"
+  echo "$0 -b backup_folder -b backup_dir -u trafodion_user -h hbase_user -d hdfs_user -m mappers -l 10 -n -o"
   echo "where"
   echo "-b backup_folder"
   echo "     (Optional) HDFS path where all the Trafodion object are exported and saved"
@@ -58,11 +58,16 @@ usage()
   echo "     HDFS user 'hdfs'. Unless the -n option is specified, the user is asked to"
   echo "     confirm the selection afterwards."
   echo "-m mappers"
-  echo "     (Optional) Number of mappers. The default value is 2."
+  echo "     (Optional) Number of mappers. If unspecified each snapshot will use a number suitable for its size."
   echo "-n"
   echo "     (Optional) Non interactive mode. With this option the script does not prompt"
   echo "     the user to confirm the use of computed or default values when a parameter"
   echo "     like trafodion user, hbase user, hdfs user or backup path is not provided."
+  echo "-o"
+  echo "     (Optional) offline. With this option trafodion will not be restarted after"
+  echo "     snapshots are taken."
+  echo "-l"
+  echo "     (Optional) Snapshot size limit in MB above which map reduce is used for copy. Snapshots with size below this value will be copied using HDFS FileUtil.copy. Default value is 100 MB. FileUtil.copy is invoked through a class provided by Trafodion. Use 0 for this option to use HBase' ExportSnaphot class instead."
   echo " Example: $0  -b hdfs://<host>:<port>/<hdfs-path>  -m 4"
   exit 1
 }
@@ -96,8 +101,10 @@ trafodion_user=
 hbase_user=
 hdfs_user=
 confirm=1
+stay_offline=0
+mr_limit=100
 
-while getopts :b:u:m:h:d:n arguments
+while getopts b:u:m:h:d:l:no arguments
 do
   case $arguments in
   b)  hdfs_backup_location=$OPTARG;;
@@ -105,6 +112,8 @@ do
   u)  trafodion_user=$OPTARG;;
   h)  hbase_user=$OPTARG;;
   d)  hdfs_user=$OPTARG;;
+  l)  mr_limit=$OPTARG;;
+  o)  stay_offline=1;;
   n)  confirm=0;;
   *)  usage;;
   esac
@@ -229,17 +238,29 @@ if  [[ $? -eq 0 ]]; then
     exit 1;
 fi
 
+## Restart Trafodion
+if [[ ${stay_offline} -ne 1 ]]; then
+ start_trafodion $trafodion_user 
+else
+ echo "Trafodion can now be restarted at your convinience. Backup script does not need for it to be offline anymore."
+fi
 
 while read line
 do
   snapshot_name=$line
   echo "********************************************************************"
   echo "Exporting ${snapshot_name} ..."
-  #export--
-  hbase_cmd="$(get_hbase_cmd)  org.apache.hadoop.hbase.snapshot.ExportSnapshot"
+  if [[ ${mr_limit} -eq 0 ]]; then
+     hbase_cmd="$(get_hbase_cmd) org.apache.hadoop.hbase.snapshot.ExportSnapshot"
+  else 
+     hbase_cmd="$(get_hbase_cmd) org.trafodion.utility.backuprestore.TrafExportSnapshot"
+  fi
   hbase_cmd+=" -snapshot ${snapshot_name}"
   hbase_cmd+=" -copy-to ${hdfs_backup_location}/${snapshot_name}"
   hbase_cmd+=" -mappers $mappers"
+  if [[ ${mr_limit} -ne 0 ]]; then
+     hbase_cmd+=" -mr-lowlimit-mb ${mr_limit}"
+  fi
   echo "${hbase_cmd}" | tee -a ${log_file}
 
   do_sudo ${hbase_user} "${hbase_cmd}" 2>&1 | tee -a  ${log_file}

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/bd960ca3/core/sqf/hbase_utilities/backup_and_restore/run_full_trafodion_restore.sh
----------------------------------------------------------------------
diff --git a/core/sqf/hbase_utilities/backup_and_restore/run_full_trafodion_restore.sh b/core/sqf/hbase_utilities/backup_and_restore/run_full_trafodion_restore.sh
index 18ef4e7..80dd427 100755
--- a/core/sqf/hbase_utilities/backup_and_restore/run_full_trafodion_restore.sh
+++ b/core/sqf/hbase_utilities/backup_and_restore/run_full_trafodion_restore.sh
@@ -58,6 +58,8 @@ usage()
   echo "     (Optional) Non interactive mode. With this option the script does not prompt"
   echo "     the user to confirm the use of computed or default values when a parameter"
   echo "      like trafodion user, hbase user, hdfs user or backup path is not provided."
+  echo "-l"
+  echo "     (Optional) Snapshot size limit in MB above which map reduce is used for copy. Snapshots with size below this value will be copied using HDFS FileUtil.copy. Default value is 100 MB. FileUtil.copy is invoked through a class provided by Trafodion. Use 0 for this option to use HBase' ExportSnaphot class instead."
   echo " Example: $0  -b hdfs://<host>:<port>/<hdfs-path>  -m 4"
   exit 1
 }
@@ -72,6 +74,7 @@ hbase_root_dir=
 trafodion_user=
 confirm=1
 snapshot_name=
+mr_limit=100
 
 restore_run_id=${PWD}
 tmp_dir=$restore_run_id/tmp
@@ -86,7 +89,7 @@ hbase_delete_snapshots=${tmp_dir}/rstr_delete_snapshots.hbase
 
 
 
-while getopts :b:u:m:h:d:n arguments
+while getopts b:u:m:h:d:l:n arguments
 do
   case $arguments in
   b)  hdfs_backup_location=$OPTARG;;
@@ -94,6 +97,7 @@ do
   u)  trafodion_user=$OPTARG;;
   h)  hbase_user=$OPTARG;;
   d)  hdfs_user=$OPTARG;;
+  l)  mr_limit=$OPTARG;;
   n)  confirm=0;;
   *)  usage;;
   esac
@@ -197,11 +201,18 @@ do
   echo "restore_snapshot	'${snapshot_name}'" >>	$hbase_restore_snapshots
   echo "delete_snapshot	'${snapshot_name}'" >>	$hbase_delete_snapshots
   echo  "Importing Snapshot: ${snapshot_name}"   | tee -a $log_file
-  hbase_cmd="$(get_hbase_cmd)"
-  hbase_cmd+=" org.apache.hadoop.hbase.snapshot.ExportSnapshot"
+  if [[ ${mr_limit} -eq 0 ]]; then
+     hbase_cmd="$(get_hbase_cmd) org.apache.hadoop.hbase.snapshot.ExportSnapshot"
+  else 
+     hbase_cmd="$(get_hbase_cmd) org.trafodion.utility.backuprestore.TrafExportSnapshot"
+  fi
   hbase_cmd+=" -D hbase.rootdir=${hdfs_backup_location}/${snapshot_name}"
   hbase_cmd+=" -snapshot ${snapshot_name}"
   hbase_cmd+=" -copy-to ${hbase_root_dir}"
+  hbase_cmd+=" -mappers $mappers"
+  if [[ ${mr_limit} -ne 0 ]]; then
+     hbase_cmd+=" -mr-lowlimit-mb ${mr_limit}"
+  fi
   echo "${hbase_cmd}" | tee -a  $log_file
 
   do_sudo ${hbase_user} " ${hbase_cmd}" 2>&1 | tee -a  ${log_file}

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/bd960ca3/core/sqf/hbase_utilities/pom.xml
----------------------------------------------------------------------
diff --git a/core/sqf/hbase_utilities/pom.xml b/core/sqf/hbase_utilities/pom.xml
new file mode 100644
index 0000000..c1d0d5d
--- /dev/null
+++ b/core/sqf/hbase_utilities/pom.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <!--
+/**
+ * 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.
+ */
+-->
+  <repositories>
+    <repository>
+      <id>cloudera</id>
+      <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
+    </repository>
+  </repositories>
+
+  <properties>
+    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    <hadoop.version>2.5.0</hadoop.version>
+    <hbase.version>0.98.6-cdh5.3.0</hbase.version>
+    <java.version>1.7</java.version>
+  </properties>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.apache.hbase</groupId>
+      <artifactId>hbase-server</artifactId>
+      <version>${hbase.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hbase</groupId>
+      <artifactId>hbase-client</artifactId>
+      <version>${hbase.version}</version>
+    </dependency>
+  </dependencies>
+
+  <groupId>org.trafodion.utility</groupId>
+  <modelVersion>4.0.0</modelVersion>
+  <artifactId>trafodion-utility</artifactId>
+  <version>${env.TRAFODION_VER}</version>
+  <name>trafodion-utility</name>
+  <description>Java code for utilities used by Trafodion</description>
+
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-jar-plugin</artifactId>
+        <configuration>
+          <archive>
+            <manifestFile>
+              src/main/resources/trafodion-utility.jar.mf
+            </manifestFile>
+          </archive>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+</project>

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/bd960ca3/core/sqf/hbase_utilities/src/main/java/org/trafodion/utility/backuprestore/TrafExportSnapshot.java
----------------------------------------------------------------------
diff --git a/core/sqf/hbase_utilities/src/main/java/org/trafodion/utility/backuprestore/TrafExportSnapshot.java b/core/sqf/hbase_utilities/src/main/java/org/trafodion/utility/backuprestore/TrafExportSnapshot.java
new file mode 100644
index 0000000..7a5b4dd
--- /dev/null
+++ b/core/sqf/hbase_utilities/src/main/java/org/trafodion/utility/backuprestore/TrafExportSnapshot.java
@@ -0,0 +1,1076 @@
+/**
+ * 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.
+ */
+
+package org.trafodion.utility.backuprestore;
+
+import java.io.BufferedInputStream;
+import java.io.FileNotFoundException;
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Random;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.conf.Configured;
+import org.apache.hadoop.fs.FSDataInputStream;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileChecksum;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.FileUtil;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.hbase.TableName;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.HRegionInfo;
+import org.apache.hadoop.hbase.io.FileLink;
+import org.apache.hadoop.hbase.io.HFileLink;
+import org.apache.hadoop.hbase.io.HLogLink;
+import org.apache.hadoop.hbase.io.hadoopbackport.ThrottledInputStream;
+import org.apache.hadoop.hbase.mapreduce.JobUtil;
+import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
+import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
+import org.apache.hadoop.hbase.protobuf.generated.SnapshotProtos.SnapshotFileInfo;
+import org.apache.hadoop.hbase.protobuf.generated.SnapshotProtos.SnapshotRegionManifest;
+import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
+import org.apache.hadoop.hbase.util.FSUtils;
+import org.apache.hadoop.hbase.snapshot.*;
+import org.apache.hadoop.hbase.util.Pair;
+import org.apache.hadoop.io.BytesWritable;
+import org.apache.hadoop.io.NullWritable;
+import org.apache.hadoop.io.SequenceFile;
+import org.apache.hadoop.io.Writable;
+import org.apache.hadoop.mapreduce.Job;
+import org.apache.hadoop.mapreduce.JobContext;
+import org.apache.hadoop.mapreduce.Mapper;
+import org.apache.hadoop.mapreduce.InputFormat;
+import org.apache.hadoop.mapreduce.InputSplit;
+import org.apache.hadoop.mapreduce.RecordReader;
+import org.apache.hadoop.mapreduce.TaskAttemptContext;
+import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
+import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
+import org.apache.hadoop.mapreduce.security.TokenCache;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.Tool;
+import org.apache.hadoop.util.ToolRunner;
+
+/**
+ * Export the specified snapshot to a given FileSystem.
+ *
+ * The .snapshot/name folder is copied to the destination cluster
+ * and then all the hfiles/hlogs are copied using a Map-Reduce Job in the .archive/ location.
+ * When everything is done, the second cluster can restore the snapshot.
+ */
+@InterfaceAudience.Public
+@InterfaceStability.Evolving
+public class TrafExportSnapshot extends Configured implements Tool {
+  private static final Log LOG = LogFactory.getLog(TrafExportSnapshot.class);
+
+  private static final String MR_NUM_MAPS = "mapreduce.job.maps";
+  private static final String CONF_NUM_SPLITS = "snapshot.export.format.splits";
+  private static final String CONF_SNAPSHOT_NAME = "snapshot.export.format.snapshot.name";
+  private static final String CONF_SNAPSHOT_DIR = "snapshot.export.format.snapshot.dir";
+  private static final String CONF_FILES_USER = "snapshot.export.files.attributes.user";
+  private static final String CONF_FILES_GROUP = "snapshot.export.files.attributes.group";
+  private static final String CONF_FILES_MODE = "snapshot.export.files.attributes.mode";
+  private static final String CONF_CHECKSUM_VERIFY = "snapshot.export.checksum.verify";
+  private static final String CONF_OUTPUT_ROOT = "snapshot.export.output.root";
+  private static final String CONF_INPUT_ROOT = "snapshot.export.input.root";
+  private static final String CONF_BANDWIDTH_MB = "snapshot.export.map.bandwidth.mb";
+  private static final String CONF_BUFFER_SIZE = "snapshot.export.buffer.size";
+  private static final String CONF_MAP_GROUP = "snapshot.export.default.map.group";
+  protected static final String CONF_SKIP_TMP = "snapshot.export.skip.tmp";
+
+  static final String CONF_TEST_FAILURE = "test.snapshot.export.failure";
+  static final String CONF_TEST_RETRY = "test.snapshot.export.failure.retry";
+
+  private static final String INPUT_FOLDER_PREFIX = "export-files.";
+
+  // Export Map-Reduce Counters, to keep track of the progress
+  public enum Counter { MISSING_FILES, COPY_FAILED, BYTES_EXPECTED, BYTES_COPIED, FILES_COPIED };
+
+  private static class ExportMapper extends Mapper<BytesWritable, NullWritable,
+                                                   NullWritable, NullWritable> {
+    final static int REPORT_SIZE = 1 * 1024 * 1024;
+    final static int BUFFER_SIZE = 64 * 1024;
+
+    private boolean testFailures;
+    private Random random;
+
+    private boolean verifyChecksum;
+    private String filesGroup;
+    private String filesUser;
+    private short filesMode;
+    private int bufferSize;
+
+    private FileSystem outputFs;
+    private Path outputArchive;
+    private Path outputRoot;
+
+    private FileSystem inputFs;
+    private Path inputArchive;
+    private Path inputRoot;
+
+    @Override
+    public void setup(Context context) throws IOException {
+      Configuration conf = context.getConfiguration();
+      verifyChecksum = conf.getBoolean(CONF_CHECKSUM_VERIFY, true);
+
+      filesGroup = conf.get(CONF_FILES_GROUP);
+      filesUser = conf.get(CONF_FILES_USER);
+      filesMode = (short)conf.getInt(CONF_FILES_MODE, 0);
+      outputRoot = new Path(conf.get(CONF_OUTPUT_ROOT));
+      inputRoot = new Path(conf.get(CONF_INPUT_ROOT));
+
+      inputArchive = new Path(inputRoot, HConstants.HFILE_ARCHIVE_DIRECTORY);
+      outputArchive = new Path(outputRoot, HConstants.HFILE_ARCHIVE_DIRECTORY);
+
+      testFailures = conf.getBoolean(CONF_TEST_FAILURE, false);
+
+      try {
+        inputFs = FileSystem.get(inputRoot.toUri(), conf);
+      } catch (IOException e) {
+        throw new IOException("Could not get the input FileSystem with root=" + inputRoot, e);
+      }
+
+      try {
+        outputFs = FileSystem.get(outputRoot.toUri(), conf);
+      } catch (IOException e) {
+        throw new IOException("Could not get the output FileSystem with root="+ outputRoot, e);
+      }
+
+      // Use the default block size of the outputFs if bigger
+      int defaultBlockSize = Math.max((int) outputFs.getDefaultBlockSize(), BUFFER_SIZE);
+      bufferSize = conf.getInt(CONF_BUFFER_SIZE, defaultBlockSize);
+      LOG.info("Using bufferSize=" + StringUtils.humanReadableInt(bufferSize));
+    }
+
+    byte[] copyBytes(BytesWritable  bw) {
+      byte[] result = new byte[bw.getLength()];
+      System.arraycopy(bw.getBytes(), 0, result, 0, bw.getLength());
+      return result;
+    }
+
+    @Override
+    public void map(BytesWritable key, NullWritable value, Context context)
+        throws InterruptedException, IOException {
+      SnapshotFileInfo inputInfo = SnapshotFileInfo.parseFrom(copyBytes(key));
+      Path outputPath = getOutputPath(inputInfo);
+
+      copyFile(context, inputInfo, outputPath);
+    }
+
+    /**
+     * Returns the location where the inputPath will be copied.
+     */
+    private Path getOutputPath(final SnapshotFileInfo inputInfo) throws IOException {
+      Path path = null;
+      switch (inputInfo.getType()) {
+        case HFILE:
+          Path inputPath = new Path(inputInfo.getHfile());
+          String family = inputPath.getParent().getName();
+          TableName table =HFileLink.getReferencedTableName(inputPath.getName());
+          String region = HFileLink.getReferencedRegionName(inputPath.getName());
+          String hfile = HFileLink.getReferencedHFileName(inputPath.getName());
+          path = new Path(FSUtils.getTableDir(new Path("./"), table),
+              new Path(region, new Path(family, hfile)));
+          break;
+        case WAL:
+          Path oldLogsDir = new Path(outputRoot, HConstants.HREGION_OLDLOGDIR_NAME);
+          path = new Path(oldLogsDir, inputInfo.getWalName());
+          break;
+        default:
+          throw new IOException("Invalid File Type: " + inputInfo.getType().toString());
+      }
+      return new Path(outputArchive, path);
+    }
+
+    /*
+     * Used by TestExportSnapshot to simulate a failure
+     */
+    private void injectTestFailure(final Context context, final SnapshotFileInfo inputInfo)
+        throws IOException {
+      if (testFailures) {
+        if (context.getConfiguration().getBoolean(CONF_TEST_RETRY, false)) {
+          if (random == null) {
+            random = new Random();
+          }
+
+          // FLAKY-TEST-WARN: lower is better, we can get some runs without the
+          // retry, but at least we reduce the number of test failures due to
+          // this test exception from the same map task.
+          if (random.nextFloat() < 0.03) {
+            throw new IOException("TEST RETRY FAILURE: Unable to copy input=" + inputInfo
+                                  + " time=" + System.currentTimeMillis());
+          }
+        } else {
+          context.getCounter(Counter.COPY_FAILED).increment(1);
+          throw new IOException("TEST FAILURE: Unable to copy input=" + inputInfo);
+        }
+      }
+    }
+
+    private void copyFile(final Context context, final SnapshotFileInfo inputInfo,
+        final Path outputPath) throws IOException {
+      injectTestFailure(context, inputInfo);
+
+      // Get the file information
+      FileStatus inputStat = getSourceFileStatus(context, inputInfo);
+
+      // Verify if the output file exists and is the same that we want to copy
+      if (outputFs.exists(outputPath)) {
+        FileStatus outputStat = outputFs.getFileStatus(outputPath);
+        if (outputStat != null && sameFile(inputStat, outputStat)) {
+          LOG.info("Skip copy " + inputStat.getPath() + " to " + outputPath + ", same file.");
+          return;
+        }
+      }
+
+      InputStream in = openSourceFile(context, inputInfo);
+      int bandwidthMB = context.getConfiguration().getInt(CONF_BANDWIDTH_MB, 100);
+      if (Integer.MAX_VALUE != bandwidthMB) {
+        in = new ThrottledInputStream(new BufferedInputStream(in), bandwidthMB * 1024 * 1024);
+      }
+
+      try {
+        context.getCounter(Counter.BYTES_EXPECTED).increment(inputStat.getLen());
+
+        // Ensure that the output folder is there and copy the file
+        outputFs.mkdirs(outputPath.getParent());
+        FSDataOutputStream out = outputFs.create(outputPath, true);
+        try {
+          copyData(context, inputStat.getPath(), in, outputPath, out, inputStat.getLen());
+        } finally {
+          out.close();
+        }
+
+        // Try to Preserve attributes
+        if (!preserveAttributes(outputPath, inputStat)) {
+          LOG.warn("You may have to run manually chown on: " + outputPath);
+        }
+      } finally {
+        in.close();
+      }
+    }
+
+    /**
+     * Try to Preserve the files attribute selected by the user copying them from the source file
+     * This is only required when you are exporting as a different user than "hbase" or on a system
+     * that doesn't have the "hbase" user.
+     *
+     * This is not considered a blocking failure since the user can force a chmod with the user
+     * that knows is available on the system.
+     */
+    private boolean preserveAttributes(final Path path, final FileStatus refStat) {
+      FileStatus stat;
+      try {
+        stat = outputFs.getFileStatus(path);
+      } catch (IOException e) {
+        LOG.warn("Unable to get the status for file=" + path);
+        return false;
+      }
+
+      try {
+        if (filesMode > 0 && stat.getPermission().toShort() != filesMode) {
+          outputFs.setPermission(path, new FsPermission(filesMode));
+        } else if (refStat != null && !stat.getPermission().equals(refStat.getPermission())) {
+          outputFs.setPermission(path, refStat.getPermission());
+        }
+      } catch (IOException e) {
+        LOG.warn("Unable to set the permission for file="+ stat.getPath() +": "+ e.getMessage());
+        return false;
+      }
+
+      boolean hasRefStat = (refStat != null);
+      String user = stringIsNotEmpty(filesUser) || !hasRefStat ? filesUser : refStat.getOwner();
+      String group = stringIsNotEmpty(filesGroup) || !hasRefStat ? filesGroup : refStat.getGroup();
+      if (stringIsNotEmpty(user) || stringIsNotEmpty(group)) {
+        try {
+          if (!(user.equals(stat.getOwner()) && group.equals(stat.getGroup()))) {
+            outputFs.setOwner(path, user, group);
+          }
+        } catch (IOException e) {
+          LOG.warn("Unable to set the owner/group for file="+ stat.getPath() +": "+ e.getMessage());
+          LOG.warn("The user/group may not exist on the destination cluster: user=" +
+                   user + " group=" + group);
+          return false;
+        }
+      }
+
+      return true;
+    }
+
+    private boolean stringIsNotEmpty(final String str) {
+      return str != null && str.length() > 0;
+    }
+
+    private void copyData(final Context context,
+        final Path inputPath, final InputStream in,
+        final Path outputPath, final FSDataOutputStream out,
+        final long inputFileSize)
+        throws IOException {
+      final String statusMessage = "copied %s/" + StringUtils.humanReadableInt(inputFileSize) +
+                                   " (%.1f%%)";
+
+      try {
+        byte[] buffer = new byte[bufferSize];
+        long totalBytesWritten = 0;
+        int reportBytes = 0;
+        int bytesRead;
+
+        long stime = System.currentTimeMillis();
+        while ((bytesRead = in.read(buffer)) > 0) {
+          out.write(buffer, 0, bytesRead);
+          totalBytesWritten += bytesRead;
+          reportBytes += bytesRead;
+
+          if (reportBytes >= REPORT_SIZE) {
+            context.getCounter(Counter.BYTES_COPIED).increment(reportBytes);
+            context.setStatus(String.format(statusMessage,
+                              StringUtils.humanReadableInt(totalBytesWritten),
+                              (totalBytesWritten/(float)inputFileSize) * 100.0f) +
+                              " from " + inputPath + " to " + outputPath);
+            reportBytes = 0;
+          }
+        }
+        long etime = System.currentTimeMillis();
+
+        context.getCounter(Counter.BYTES_COPIED).increment(reportBytes);
+        context.setStatus(String.format(statusMessage,
+                          StringUtils.humanReadableInt(totalBytesWritten),
+                          (totalBytesWritten/(float)inputFileSize) * 100.0f) +
+                          " from " + inputPath + " to " + outputPath);
+
+        // Verify that the written size match
+        if (totalBytesWritten != inputFileSize) {
+          String msg = "number of bytes copied not matching copied=" + totalBytesWritten +
+                       " expected=" + inputFileSize + " for file=" + inputPath;
+          throw new IOException(msg);
+        }
+
+        LOG.info("copy completed for input=" + inputPath + " output=" + outputPath);
+        LOG.info("size=" + totalBytesWritten +
+            " (" + StringUtils.humanReadableInt(totalBytesWritten) + ")" +
+            " time=" + StringUtils.formatTimeDiff(etime, stime) +
+            String.format(" %.3fM/sec", (totalBytesWritten / ((etime - stime)/1000.0))/1048576.0));
+        context.getCounter(Counter.FILES_COPIED).increment(1);
+      } catch (IOException e) {
+        LOG.error("Error copying " + inputPath + " to " + outputPath, e);
+        context.getCounter(Counter.COPY_FAILED).increment(1);
+        throw e;
+      }
+    }
+
+    /**
+     * Try to open the "source" file.
+     * Throws an IOException if the communication with the inputFs fail or
+     * if the file is not found.
+     */
+    private FSDataInputStream openSourceFile(Context context, final SnapshotFileInfo fileInfo)
+        throws IOException {
+      try {
+        FileLink link = null;
+        switch (fileInfo.getType()) {
+          case HFILE:
+            Path inputPath = new Path(fileInfo.getHfile());
+            link = new HFileLink(inputRoot, inputArchive, inputPath);
+            break;
+          case WAL:
+            String serverName = fileInfo.getWalServer();
+            String logName = fileInfo.getWalName();
+            link = new HLogLink(inputRoot, serverName, logName);
+            break;
+          default:
+            throw new IOException("Invalid File Type: " + fileInfo.getType().toString());
+        }
+        return link.open(inputFs);
+      } catch (IOException e) {
+        context.getCounter(Counter.MISSING_FILES).increment(1);
+        LOG.error("Unable to open source file=" + fileInfo.toString(), e);
+        throw e;
+      }
+    }
+
+    private FileStatus getSourceFileStatus(Context context, final SnapshotFileInfo fileInfo)
+        throws IOException {
+      try {
+        FileLink link = null;
+        switch (fileInfo.getType()) {
+          case HFILE:
+            Path inputPath = new Path(fileInfo.getHfile());
+            link = new HFileLink(inputRoot, inputArchive, inputPath);
+            break;
+          case WAL:
+            link = new HLogLink(inputRoot, fileInfo.getWalServer(), fileInfo.getWalName());
+            break;
+          default:
+            throw new IOException("Invalid File Type: " + fileInfo.getType().toString());
+        }
+        return link.getFileStatus(inputFs);
+      } catch (FileNotFoundException e) {
+        context.getCounter(Counter.MISSING_FILES).increment(1);
+        LOG.error("Unable to get the status for source file=" + fileInfo.toString(), e);
+        throw e;
+      } catch (IOException e) {
+        LOG.error("Unable to get the status for source file=" + fileInfo.toString(), e);
+        throw e;
+      }
+    }
+
+    private FileChecksum getFileChecksum(final FileSystem fs, final Path path) {
+      try {
+        return fs.getFileChecksum(path);
+      } catch (IOException e) {
+        LOG.warn("Unable to get checksum for file=" + path, e);
+        return null;
+      }
+    }
+
+    /**
+     * Check if the two files are equal by looking at the file length,
+     * and at the checksum (if user has specified the verifyChecksum flag).
+     */
+    private boolean sameFile(final FileStatus inputStat, final FileStatus outputStat) {
+      // Not matching length
+      if (inputStat.getLen() != outputStat.getLen()) return false;
+
+      // Mark files as equals, since user asked for no checksum verification
+      if (!verifyChecksum) return true;
+
+      // If checksums are not available, files are not the same.
+      FileChecksum inChecksum = getFileChecksum(inputFs, inputStat.getPath());
+      if (inChecksum == null) return false;
+
+      FileChecksum outChecksum = getFileChecksum(outputFs, outputStat.getPath());
+      if (outChecksum == null) return false;
+
+      return inChecksum.equals(outChecksum);
+    }
+  }
+
+  // ==========================================================================
+  //  Input Format
+  // ==========================================================================
+
+  /**
+   * Extract the list of files (HFiles/WALs) to copy using Map-Reduce.
+   * @return list of files referenced by the snapshot (pair of path and size)
+   */
+  private static List<Pair<SnapshotFileInfo, Long>> getSnapshotFiles(final Configuration conf,
+      final FileSystem fs, final Path snapshotDir) throws IOException {
+    SnapshotDescription snapshotDesc = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDir);
+
+    final List<Pair<SnapshotFileInfo, Long>> files = new ArrayList<Pair<SnapshotFileInfo, Long>>();
+    final TableName table = TableName.valueOf(snapshotDesc.getTable());
+
+    // Get snapshot files
+    LOG.info("Loading Snapshot '" + snapshotDesc.getName() + "' hfile list");
+    SnapshotReferenceUtil.visitReferencedFiles(conf, fs, snapshotDir, snapshotDesc,
+      new SnapshotReferenceUtil.SnapshotVisitor() {
+        @Override
+        public void storeFile(final HRegionInfo regionInfo, final String family,
+            final SnapshotRegionManifest.StoreFile storeFile) throws IOException {
+          if (storeFile.hasReference()) {
+            // copied as part of the manifest
+          } else {
+            String region = regionInfo.getEncodedName();
+            String hfile = storeFile.getName();
+            Path path = HFileLink.createPath(table, region, family, hfile);
+
+            SnapshotFileInfo fileInfo = SnapshotFileInfo.newBuilder()
+              .setType(SnapshotFileInfo.Type.HFILE)
+              .setHfile(path.toString())
+              .build();
+
+            long size;
+            if (storeFile.hasFileSize()) {
+              size = storeFile.getFileSize();
+            } else {
+              size = new HFileLink(conf, path).getFileStatus(fs).getLen();
+            }
+            files.add(new Pair<SnapshotFileInfo, Long>(fileInfo, size));
+          }
+        }
+
+        @Override
+        public void logFile (final String server, final String logfile)
+            throws IOException {
+          SnapshotFileInfo fileInfo = SnapshotFileInfo.newBuilder()
+            .setType(SnapshotFileInfo.Type.WAL)
+            .setWalServer(server)
+            .setWalName(logfile)
+            .build();
+
+          long size = new HLogLink(conf, server, logfile).getFileStatus(fs).getLen();
+          files.add(new Pair<SnapshotFileInfo, Long>(fileInfo, size));
+        }
+    });
+
+    return files;
+  }
+
+  /**
+   * Given a list of file paths and sizes, create around ngroups in as balanced a way as possible.
+   * The groups created will have similar amounts of bytes.
+   * <p>
+   * The algorithm used is pretty straightforward; the file list is sorted by size,
+   * and then each group fetch the bigger file available, iterating through groups
+   * alternating the direction.
+   */
+  static List<List<Pair<SnapshotFileInfo, Long>>> getBalancedSplits(
+      final List<Pair<SnapshotFileInfo, Long>> files, final int ngroups) {
+    // Sort files by size, from small to big
+    Collections.sort(files, new Comparator<Pair<SnapshotFileInfo, Long>>() {
+      public int compare(Pair<SnapshotFileInfo, Long> a, Pair<SnapshotFileInfo, Long> b) {
+        long r = a.getSecond() - b.getSecond();
+        return (r < 0) ? -1 : ((r > 0) ? 1 : 0);
+      }
+    });
+
+    // create balanced groups
+    List<List<Pair<SnapshotFileInfo, Long>>> fileGroups =
+      new LinkedList<List<Pair<SnapshotFileInfo, Long>>>();
+    long[] sizeGroups = new long[ngroups];
+    int hi = files.size() - 1;
+    int lo = 0;
+
+    List<Pair<SnapshotFileInfo, Long>> group;
+    int dir = 1;
+    int g = 0;
+
+    while (hi >= lo) {
+      if (g == fileGroups.size()) {
+        group = new LinkedList<Pair<SnapshotFileInfo, Long>>();
+        fileGroups.add(group);
+      } else {
+        group = fileGroups.get(g);
+      }
+
+      Pair<SnapshotFileInfo, Long> fileInfo = files.get(hi--);
+
+      // add the hi one
+      sizeGroups[g] += fileInfo.getSecond();
+      group.add(fileInfo);
+
+      // change direction when at the end or the beginning
+      g += dir;
+      if (g == ngroups) {
+        dir = -1;
+        g = ngroups - 1;
+      } else if (g < 0) {
+        dir = 1;
+        g = 0;
+      }
+    }
+
+    if (LOG.isDebugEnabled()) {
+      for (int i = 0; i < sizeGroups.length; ++i) {
+        LOG.debug("export split=" + i + " size=" + StringUtils.humanReadableInt(sizeGroups[i]));
+      }
+    }
+
+    return fileGroups;
+  }
+
+  private static class ExportSnapshotInputFormat extends InputFormat<BytesWritable, NullWritable> {
+    @Override
+    public RecordReader<BytesWritable, NullWritable> createRecordReader(InputSplit split,
+        TaskAttemptContext tac) throws IOException, InterruptedException {
+      return new ExportSnapshotRecordReader(((ExportSnapshotInputSplit)split).getSplitKeys());
+    }
+
+    @Override
+    public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException {
+      Configuration conf = context.getConfiguration();
+      String snapshotName = conf.get(CONF_SNAPSHOT_NAME);
+      Path snapshotDir = new Path(conf.get(CONF_SNAPSHOT_DIR));
+      FileSystem fs = FileSystem.get(snapshotDir.toUri(), conf);
+
+      List<Pair<SnapshotFileInfo, Long>> snapshotFiles = getSnapshotFiles(conf, fs, snapshotDir);
+      int mappers = conf.getInt(CONF_NUM_SPLITS, 0);
+      if (mappers == 0 && snapshotFiles.size() > 0) {
+        mappers = 1 + (snapshotFiles.size() / conf.getInt(CONF_MAP_GROUP, 10));
+        mappers = Math.min(mappers, snapshotFiles.size());
+        conf.setInt(CONF_NUM_SPLITS, mappers);
+        conf.setInt(MR_NUM_MAPS, mappers);
+      }
+
+      List<List<Pair<SnapshotFileInfo, Long>>> groups = getBalancedSplits(snapshotFiles, mappers);
+      List<InputSplit> splits = new ArrayList(groups.size());
+      for (List<Pair<SnapshotFileInfo, Long>> files: groups) {
+        splits.add(new ExportSnapshotInputSplit(files));
+      }
+      return splits;
+    }
+
+    private static class ExportSnapshotInputSplit extends InputSplit implements Writable {
+      private List<Pair<BytesWritable, Long>> files;
+      private long length;
+
+      public ExportSnapshotInputSplit() {
+        this.files = null;
+      }
+
+      public ExportSnapshotInputSplit(final List<Pair<SnapshotFileInfo, Long>> snapshotFiles) {
+        this.files = new ArrayList(snapshotFiles.size());
+        for (Pair<SnapshotFileInfo, Long> fileInfo: snapshotFiles) {
+          this.files.add(new Pair<BytesWritable, Long>(
+            new BytesWritable(fileInfo.getFirst().toByteArray()), fileInfo.getSecond()));
+          this.length += fileInfo.getSecond();
+        }
+      }
+
+      private List<Pair<BytesWritable, Long>> getSplitKeys() {
+        return files;
+      }
+
+      @Override
+      public long getLength() throws IOException, InterruptedException {
+        return length;
+      }
+
+      @Override
+      public String[] getLocations() throws IOException, InterruptedException {
+        return new String[] {};
+      }
+
+      @Override
+      public void readFields(DataInput in) throws IOException {
+        int count = in.readInt();
+        files = new ArrayList<Pair<BytesWritable, Long>>(count);
+        length = 0;
+        for (int i = 0; i < count; ++i) {
+          BytesWritable fileInfo = new BytesWritable();
+          fileInfo.readFields(in);
+          long size = in.readLong();
+          files.add(new Pair<BytesWritable, Long>(fileInfo, size));
+          length += size;
+        }
+      }
+
+      @Override
+      public void write(DataOutput out) throws IOException {
+        out.writeInt(files.size());
+        for (final Pair<BytesWritable, Long> fileInfo: files) {
+          fileInfo.getFirst().write(out);
+          out.writeLong(fileInfo.getSecond());
+        }
+      }
+    }
+
+    private static class ExportSnapshotRecordReader
+        extends RecordReader<BytesWritable, NullWritable> {
+      private final List<Pair<BytesWritable, Long>> files;
+      private long totalSize = 0;
+      private long procSize = 0;
+      private int index = -1;
+
+      ExportSnapshotRecordReader(final List<Pair<BytesWritable, Long>> files) {
+        this.files = files;
+        for (Pair<BytesWritable, Long> fileInfo: files) {
+          totalSize += fileInfo.getSecond();
+        }
+      }
+
+      @Override
+      public void close() { }
+
+      @Override
+      public BytesWritable getCurrentKey() { return files.get(index).getFirst(); }
+
+      @Override
+      public NullWritable getCurrentValue() { return NullWritable.get(); }
+
+      @Override
+      public float getProgress() { return (float)procSize / totalSize; }
+
+      @Override
+      public void initialize(InputSplit split, TaskAttemptContext tac) { }
+
+      @Override
+      public boolean nextKeyValue() {
+        if (index >= 0) {
+          procSize += files.get(index).getSecond();
+        }
+        return(++index < files.size());
+      }
+    }
+  }
+
+  // ==========================================================================
+  //  Tool
+  // ==========================================================================
+
+  /**
+   * Run Map-Reduce Job to perform the files copy.
+   */
+  private void runCopyJob(final Path inputRoot, final Path outputRoot,
+      final String snapshotName, final Path snapshotDir, final boolean verifyChecksum,
+      final String filesUser, final String filesGroup, final int filesMode,
+      final int mappers, final int bandwidthMB)
+          throws IOException, InterruptedException, ClassNotFoundException {
+    Configuration conf = getConf();
+    if (filesGroup != null) conf.set(CONF_FILES_GROUP, filesGroup);
+    if (filesUser != null) conf.set(CONF_FILES_USER, filesUser);
+    if (mappers > 0) {
+      conf.setInt(CONF_NUM_SPLITS, mappers);
+      conf.setInt(MR_NUM_MAPS, mappers);
+    }
+    conf.setInt(CONF_FILES_MODE, filesMode);
+    conf.setBoolean(CONF_CHECKSUM_VERIFY, verifyChecksum);
+    conf.set(CONF_OUTPUT_ROOT, outputRoot.toString());
+    conf.set(CONF_INPUT_ROOT, inputRoot.toString());
+    conf.setInt(CONF_BANDWIDTH_MB, bandwidthMB);
+    conf.set(CONF_SNAPSHOT_NAME, snapshotName);
+    conf.set(CONF_SNAPSHOT_DIR, snapshotDir.toString());
+
+    Job job = new Job(conf);
+    job.setJobName("TrafExportSnapshot-" + snapshotName);
+    job.setJarByClass(TrafExportSnapshot.class);
+    TableMapReduceUtil.addDependencyJars(job);
+    job.setMapperClass(ExportMapper.class);
+    job.setInputFormatClass(ExportSnapshotInputFormat.class);
+    job.setOutputFormatClass(NullOutputFormat.class);
+    job.setMapSpeculativeExecution(false);
+    job.setNumReduceTasks(0);
+
+    // Acquire the delegation Tokens
+    TokenCache.obtainTokensForNamenodes(job.getCredentials(),
+      new Path[] { inputRoot, outputRoot }, conf);
+
+    // Run the MR Job
+    if (!job.waitForCompletion(true)) {
+      // TODO: Replace the fixed string with job.getStatus().getFailureInfo()
+      // when it will be available on all the supported versions.
+      throw new ExportSnapshotException("Copy Files Map-Reduce Job failed");
+    }
+  }
+
+  private void verifySnapshot(final Configuration baseConf,
+      final FileSystem fs, final Path rootDir, final Path snapshotDir) throws IOException {
+    // Update the conf with the current root dir, since may be a different cluster
+    Configuration conf = new Configuration(baseConf);
+    FSUtils.setRootDir(conf, rootDir);
+    FSUtils.setFsDefault(conf, FSUtils.getRootDir(conf));
+    SnapshotDescription snapshotDesc = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDir);
+    SnapshotReferenceUtil.verifySnapshot(conf, fs, snapshotDir, snapshotDesc);
+  }
+
+  /**
+   * Execute the export snapshot by copying the snapshot metadata, hfiles and hlogs.
+   * @return 0 on success, and != 0 upon failure.
+   */
+  @Override
+  public int run(String[] args) throws IOException {
+    boolean verifyTarget = true;
+    boolean verifyChecksum = true;
+    String snapshotName = null;
+    String targetName = null;
+    boolean overwrite = false;
+    String filesGroup = null;
+    String filesUser = null;
+    Path outputRoot = null;
+    int bandwidthMB = Integer.MAX_VALUE;
+    int filesMode = 0;
+    int mappers = 0;
+    int mrLowLimitMB = 100;
+
+    Configuration conf = getConf();
+    Path inputRoot = FSUtils.getRootDir(conf);
+
+    // Process command line args
+    for (int i = 0; i < args.length; i++) {
+      String cmd = args[i];
+      if (cmd.equals("-snapshot")) {
+        snapshotName = args[++i];
+      } else if (cmd.equals("-target")) {
+        targetName = args[++i];
+      } else if (cmd.equals("-copy-to")) {
+        outputRoot = new Path(args[++i]);
+      } else if (cmd.equals("-copy-from")) {
+        inputRoot = new Path(args[++i]);
+        FSUtils.setRootDir(conf, inputRoot);
+      } else if (cmd.equals("-no-checksum-verify")) {
+        verifyChecksum = false;
+      } else if (cmd.equals("-no-target-verify")) {
+        verifyTarget = false;
+      } else if (cmd.equals("-mappers")) {
+        mappers = Integer.parseInt(args[++i]);
+      } else if (cmd.equals("-chuser")) {
+        filesUser = args[++i];
+      } else if (cmd.equals("-chgroup")) {
+        filesGroup = args[++i];
+      } else if (cmd.equals("-bandwidth")) {
+        bandwidthMB = Integer.parseInt(args[++i]);
+      } else if (cmd.equals("-chmod")) {
+        filesMode = Integer.parseInt(args[++i], 8);
+      } else if (cmd.equals("-overwrite")) {
+        overwrite = true;
+      } else if (cmd.equals("-mr-lowlimit-mb")) {
+    		mrLowLimitMB = Integer.parseInt(args[++i]);
+      } else if (cmd.equals("-h") || cmd.equals("--help")) {
+        printUsageAndExit();
+      } else {
+        System.err.println("UNEXPECTED: " + cmd);
+        printUsageAndExit();
+      }
+    }
+
+    // Check user options
+    if (snapshotName == null) {
+      System.err.println("Snapshot name not provided.");
+      printUsageAndExit();
+    }
+
+    if (outputRoot == null) {
+      System.err.println("Destination file-system not provided.");
+      printUsageAndExit();
+    }
+
+    if (targetName == null) {
+      targetName = snapshotName;
+    }
+
+    FileSystem inputFs = FileSystem.get(inputRoot.toUri(), conf);
+    LOG.debug("inputFs=" + inputFs.getUri().toString() + " inputRoot=" + inputRoot);
+    FileSystem outputFs = FileSystem.get(outputRoot.toUri(), conf);
+    LOG.debug("outputFs=" + outputFs.getUri().toString() + " outputRoot=" + outputRoot.toString());
+
+    boolean skipTmp = conf.getBoolean(CONF_SKIP_TMP, false);
+    
+    conf.set(CONF_OUTPUT_ROOT, outputRoot.toString());
+    conf.set(CONF_INPUT_ROOT, inputRoot.toString());
+
+    Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, inputRoot);
+    Path snapshotTmpDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(targetName, outputRoot);
+    Path outputSnapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(targetName, outputRoot);
+    Path initialOutputSnapshotDir = skipTmp ? outputSnapshotDir : snapshotTmpDir;
+
+    // Check if the snapshot already exists
+    if (outputFs.exists(outputSnapshotDir)) {
+      if (overwrite) {
+        if (!outputFs.delete(outputSnapshotDir, true)) {
+          System.err.println("Unable to remove existing snapshot directory: " + outputSnapshotDir);
+          return 1;
+        }
+      } else {
+        System.err.println("The snapshot '" + targetName +
+          "' already exists in the destination: " + outputSnapshotDir);
+        return 1;
+      }
+    }
+
+    if (!skipTmp) {
+      // Check if the snapshot already in-progress
+      if (outputFs.exists(snapshotTmpDir)) {
+        if (overwrite) {
+          if (!outputFs.delete(snapshotTmpDir, true)) {
+            System.err.println("Unable to remove existing snapshot tmp directory: "+snapshotTmpDir);
+            return 1;
+          }
+        } else {
+          System.err.println("A snapshot with the same name '"+ targetName +"' may be in-progress");
+          System.err.println("Please check "+snapshotTmpDir+". If the snapshot has completed, ");
+          System.err.println("consider removing "+snapshotTmpDir+" by using the -overwrite option");
+          return 1;
+        }
+      }
+    }
+
+    // Step 1 - Copy fs1:/.snapshot/<snapshot> to  fs2:/.snapshot/.tmp/<snapshot>
+    // The snapshot references must be copied before the hfiles otherwise the cleaner
+    // will remove them because they are unreferenced.
+    try {
+      LOG.info("Copy Snapshot Manifest");
+      FileUtil.copy(inputFs, snapshotDir, outputFs, initialOutputSnapshotDir, false, false, conf);
+    } catch (IOException e) {
+      throw new ExportSnapshotException("Failed to copy the snapshot directory: from=" +
+        snapshotDir + " to=" + initialOutputSnapshotDir, e);
+    }
+
+    // Write a new .snapshotinfo if the target name is different from the source name
+    if (!targetName.equals(snapshotName)) {
+      SnapshotDescription snapshotDesc =
+        SnapshotDescriptionUtils.readSnapshotInfo(inputFs, snapshotDir)
+          .toBuilder()
+          .setName(targetName)
+          .build();
+      SnapshotDescriptionUtils.writeSnapshotInfo(snapshotDesc, snapshotTmpDir, outputFs);
+    }
+
+    List<Pair<SnapshotFileInfo, Long>> snapshotFiles = getSnapshotFiles(conf, inputFs, snapshotDir);
+    Long snapshotTotalDataSize = 0L;
+    boolean hasWALfiles = false;
+    SnapshotFileInfo inputInfo;
+    for (Pair<SnapshotFileInfo, Long> fileInfo: snapshotFiles) {
+    	snapshotTotalDataSize += fileInfo.getSecond();
+    	if (fileInfo.getFirst().getType() == SnapshotFileInfo.Type.WAL)
+    		hasWALfiles = true;
+    }
+    
+    
+
+    // Step 2 - Start MR Job to copy files
+    // The snapshot references must be copied before the files otherwise the files gets removed
+    // by the HFileArchiver, since they have no references.
+    try {
+    	if ((snapshotTotalDataSize/(1024*1024) > mrLowLimitMB) || hasWALfiles) {
+    	    runCopyJob(inputRoot, outputRoot, snapshotName, snapshotDir, verifyChecksum,
+    		       filesUser, filesGroup, filesMode, mappers, bandwidthMB);
+    	}
+    	else {
+    	     	LOG.info("Copy Snapshot Data Files");
+    	     	for (Pair<SnapshotFileInfo, Long> fileInfo: snapshotFiles) {
+    	     		inputInfo = fileInfo.getFirst();
+    	     		Path outputPath = getCopyOutputPath(conf, inputInfo);
+    	     		Path inputPath = getCopyInputPath(conf, inputInfo, inputFs);
+    	     		FileUtil.copy(inputFs, inputPath, outputFs, outputPath, false, false, conf);
+    	     	}	
+    	}	
+
+
+      LOG.info("Finalize the Snapshot Export");
+      if (!skipTmp) {
+        // Step 3 - Rename fs2:/.snapshot/.tmp/<snapshot> fs2:/.snapshot/<snapshot>
+        if (!outputFs.rename(snapshotTmpDir, outputSnapshotDir)) {
+          throw new ExportSnapshotException("Unable to rename snapshot directory from=" +
+            snapshotTmpDir + " to=" + outputSnapshotDir);
+        }
+      }
+
+      // Step 4 - Verify snapshot integrity
+      if (verifyTarget) {
+        LOG.info("Verify snapshot integrity");
+        verifySnapshot(conf, outputFs, outputRoot, outputSnapshotDir);
+      }
+
+      LOG.info("Export Completed: " + targetName);
+      return 0;
+    } catch (Exception e) {
+      LOG.error("Snapshot export failed", e);
+      if (!skipTmp) {
+        outputFs.delete(snapshotTmpDir, true);
+      }
+      outputFs.delete(outputSnapshotDir, true);
+      return 1;
+    }
+  }
+  
+  
+   private Path getCopyOutputPath(final Configuration conf, final SnapshotFileInfo inputInfo) 
+   throws IOException {
+      Path path = null;
+      Path outputRoot = new Path(conf.get(CONF_OUTPUT_ROOT));
+      Path outputArchive = new Path(outputRoot, HConstants.HFILE_ARCHIVE_DIRECTORY);
+      switch (inputInfo.getType()) {
+        case HFILE:
+          Path inputPath = new Path(inputInfo.getHfile());
+          String family = inputPath.getParent().getName();
+          TableName table =HFileLink.getReferencedTableName(inputPath.getName());
+          String region = HFileLink.getReferencedRegionName(inputPath.getName());
+          String hfile = HFileLink.getReferencedHFileName(inputPath.getName());
+          path = new Path(FSUtils.getTableDir(new Path("./"), table),
+              new Path(region, new Path(family, hfile)));
+          break;
+        default:
+          throw new IOException("Invalid File Type: " + inputInfo.getType().toString());
+      }
+      return new Path(outputArchive, path);
+    }
+
+    private Path getCopyInputPath(final Configuration conf, final SnapshotFileInfo inputInfo, final FileSystem inputFs)
+    throws IOException {
+       FileLink link = null;
+       Path inputRoot = new Path(conf.get(CONF_INPUT_ROOT));
+       Path inputArchive = new Path(inputRoot, HConstants.HFILE_ARCHIVE_DIRECTORY);
+       try {
+	   switch (inputInfo.getType()) {
+	   case HFILE:
+	       Path inputPath = new Path(inputInfo.getHfile());
+	       link = new HFileLink(inputRoot, inputArchive, inputPath);
+	       break;
+	   default:
+	       throw new IOException("Invalid File Type: " + inputInfo.getType().toString());
+	   }
+       } 
+       catch (IOException e) 
+       {
+	   LOG.error("Unable to open source file=" + inputInfo.toString(), e);
+	   throw e;
+       }
+       return link.getAvailablePath(inputFs);
+    }
+    
+  // ExportSnapshot
+  private void printUsageAndExit() {
+    System.err.printf("Usage: bin/hbase %s [options]%n", getClass().getName());
+    System.err.println(" where [options] are:");
+    System.err.println("  -h|-help                Show this help and exit.");
+    System.err.println("  -snapshot NAME          Snapshot to restore.");
+    System.err.println("  -copy-to NAME           Remote destination hdfs://");
+    System.err.println("  -copy-from NAME         Input folder hdfs:// (default hbase.rootdir)");
+    System.err.println("  -no-checksum-verify     Do not verify checksum, use name+length only.");
+    System.err.println("  -no-target-verify       Do not verify the integrity of the \\" +
+        "exported snapshot.");
+    System.err.println("  -overwrite              Rewrite the snapshot manifest if already exists");
+    System.err.println("  -chuser USERNAME        Change the owner of the files to the specified one.");
+    System.err.println("  -chgroup GROUP          Change the group of the files to the specified one.");
+    System.err.println("  -chmod MODE             Change the permission of the files to the specified one.");
+    System.err.println("  -mappers                Number of mappers to use during the copy (mapreduce.job.maps).");
+	System.err.println("  -mr-lowlimit-mb         Use file copy command instead of MR copy for files \\" +
+	    		"smaller than this size.");
+    System.err.println();
+    System.err.println("Examples:");
+    System.err.println("  hbase " + getClass().getName() + " \\");
+    System.err.println("    -snapshot MySnapshot -copy-to hdfs://srv2:8082/hbase \\");
+    System.err.println("    -chuser MyUser -chgroup MyGroup -chmod 700 -mappers 16");
+    System.err.println();
+    System.err.println("  hbase " + getClass().getName() + " \\");
+    System.err.println("    -snapshot MySnapshot -copy-from hdfs://srv2:8082/hbase \\");
+    System.err.println("    -copy-to hdfs://srv1:50070/hbase \\");
+    System.exit(1);
+  }
+
+  /**
+   * The guts of the {@link #main} method.
+   * Call this method to avoid the {@link #main(String[])} System.exit.
+   * @param args
+   * @return errCode
+   * @throws Exception
+   */
+  static int innerMain(final Configuration conf, final String [] args) throws Exception {
+    return ToolRunner.run(conf, new TrafExportSnapshot(), args);
+  }
+
+  public static void main(String[] args) throws Exception {
+	  LOG.info("Trafodion Export Snapshot Utility");
+    System.exit(innerMain(HBaseConfiguration.create(), args));
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/bd960ca3/core/sqf/sqenvcom.sh
----------------------------------------------------------------------
diff --git a/core/sqf/sqenvcom.sh b/core/sqf/sqenvcom.sh
index ea9e28a..b5b85da 100644
--- a/core/sqf/sqenvcom.sh
+++ b/core/sqf/sqenvcom.sh
@@ -142,6 +142,7 @@ export SQ_HOME=$PWD
 
 export HBASE_TRXDIR=$MY_SQROOT/export/lib
 export HBASE_TRX_JAR=hbase-trx-cdh5_3-${TRAFODION_VER}.jar
+export UTIL_JAR=trafodion-utility-${TRAFODION_VER}.jar
 if [[ "$SQ_HBASE_DISTRO" = "HDP" ]]; then
     export HBASE_TRX_JAR=hbase-trx-hdp2_2-${TRAFODION_VER}.jar
 fi
@@ -852,6 +853,7 @@ if [[ -n "$SQ_CLASSPATH"   ]]; then SQ_CLASSPATH="$SQ_CLASSPATH:";   fi
 SQ_CLASSPATH=${SQ_CLASSPATH}${HBASE_TRXDIR}:\
 ${HBASE_TRXDIR}/${HBASE_TRX_JAR}:\
 $MY_SQROOT/export/lib/trafodion-sql-${TRAFODION_VER}.jar:\
+$MY_SQROOT/export/lib/trafodion-utility-${TRAFODION_VER}.jar:\
 $MY_SQROOT/export/lib/trafodion-dtm-${TRAFODION_VER}.jar:\
 $MY_SQROOT/export/lib/jdbcT4.jar:\
 $MY_SQROOT/export/lib/jdbcT2.jar

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/bd960ca3/core/sqf/sql/scripts/install_apache_hadoop
----------------------------------------------------------------------
diff --git a/core/sqf/sql/scripts/install_apache_hadoop b/core/sqf/sql/scripts/install_apache_hadoop
index 8d766ea..9fdc5ff 100755
--- a/core/sqf/sql/scripts/install_apache_hadoop
+++ b/core/sqf/sql/scripts/install_apache_hadoop
@@ -1410,7 +1410,7 @@ else
   cd $MY_SW_ROOT
 
   # Setup HBase TRX JAR in HBase' CLASSPATH
-  echo "export HBASE_CLASSPATH=${MY_SQROOT}/export/lib/\${HBASE_TRX_JAR}" >> ${HBASE_ENV_FILE}
+  echo "export HBASE_CLASSPATH=${MY_SQROOT}/export/lib/\${HBASE_TRX_JAR}:${MY_SQROOT}/export/lib/\${UTIL_JAR}" >> ${HBASE_ENV_FILE}
 
   echo "Updating file $HBASE_CONFIG_FILE ..."
 

http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/bd960ca3/core/sqf/sql/scripts/install_local_hadoop
----------------------------------------------------------------------
diff --git a/core/sqf/sql/scripts/install_local_hadoop b/core/sqf/sql/scripts/install_local_hadoop
index 66e5494..97d9976 100755
--- a/core/sqf/sql/scripts/install_local_hadoop
+++ b/core/sqf/sql/scripts/install_local_hadoop
@@ -1422,8 +1422,8 @@ else
 
   cd $MY_SW_ROOT
 
-  # Setup HBase TRX JAR in HBase' CLASSPATH
-  echo "export HBASE_CLASSPATH=${MY_SQROOT}/export/lib/\${HBASE_TRX_JAR}" >> ${HBASE_ENV_FILE}
+  # Setup HBase TRX JAR and utility JAR in HBase' CLASSPATH
+  echo "export HBASE_CLASSPATH=${MY_SQROOT}/export/lib/\${HBASE_TRX_JAR}:${MY_SQROOT}/export/lib/\${UTIL_JAR}" >> ${HBASE_ENV_FILE}
 
   echo "Updating file $HBASE_CONFIG_FILE ..."
 


[2/2] incubator-trafodion git commit: Merge [TRAFODION-1576] PR 158 B/R performance improvements

Posted by db...@apache.org.
Merge [TRAFODION-1576] PR 158 B/R performance improvements


Project: http://git-wip-us.apache.org/repos/asf/incubator-trafodion/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-trafodion/commit/c20a4bc1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-trafodion/tree/c20a4bc1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-trafodion/diff/c20a4bc1

Branch: refs/heads/master
Commit: c20a4bc1e462f7141888baef63d2af364ef34e71
Parents: 514479f bd960ca
Author: Dave Birdsall <db...@apache.org>
Authored: Thu Nov 5 21:45:46 2015 +0000
Committer: Dave Birdsall <db...@apache.org>
Committed: Thu Nov 5 21:45:46 2015 +0000

----------------------------------------------------------------------
 core/sqf/.gitignore                             |    5 +
 core/sqf/Makefile                               |    7 +-
 core/sqf/hbase_utilities/Makefile               |   46 +
 .../backup_restore_functions.sh                 |   34 +-
 .../run_full_trafodion_backup.sh                |   31 +-
 .../run_full_trafodion_restore.sh               |   17 +-
 core/sqf/hbase_utilities/pom.xml                |   71 ++
 .../backuprestore/TrafExportSnapshot.java       | 1076 ++++++++++++++++++
 core/sqf/sqenvcom.sh                            |    2 +
 core/sqf/sql/scripts/install_apache_hadoop      |    2 +-
 core/sqf/sql/scripts/install_local_hadoop       |    4 +-
 11 files changed, 1282 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-trafodion/blob/c20a4bc1/core/sqf/sqenvcom.sh
----------------------------------------------------------------------