public static void main(String[] args) throws Exception {
    try {
      LogUtils.initHiveLog4j();
    } catch (LogInitializationException e) {
    }
    Options opts = createOptions();
    CommandLine cli = new GnuParser().parse(opts, args);

    if (cli.hasOption('h')) {
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("cleardanglingscratchdir"
          + " (clear scratch dir left behind by dead HiveCli or HiveServer2)", opts);
      return;
    }

    boolean dryRun = false;
    boolean verbose = false;

    if (cli.hasOption("r")) {
      dryRun = true;
      SessionState.getConsole().printInfo("dry-run mode on");
    }

    if (cli.hasOption("v")) {
      verbose = true;
    }

    HiveConf conf = new HiveConf();

    String rootHDFSDir;
    if (cli.hasOption("s")) {
      rootHDFSDir = cli.getOptionValue("s");
    } else {
      rootHDFSDir = HiveConf.getVar(conf, HiveConf.ConfVars.SCRATCH_DIR);
    }
    ClearDanglingScratchDir clearDanglingScratchDirMain = new ClearDanglingScratchDir(dryRun,
        verbose, true, rootHDFSDir, conf);
    clearDanglingScratchDirMain.run();
  }
A tool to remove dangling scratch directory. A scratch directory could be left behind
in some cases, such as when vm restarts and leave no chance for Hive to run shutdown hook.
The tool will test a scratch directory is use, if not, remove it.
We rely on HDFS write lock for to detect if a scratch directory is in use:
1. A HDFS client open HDFS file ($scratchdir/inuse.lck) for write and only close
   it at the time the session is closed
2. cleardanglingscratchDir can try to open $scratchdir/inuse.lck for write. If the
   corresponding HiveCli/HiveServer2 is still running, we will get exception.
   Otherwise, we know the session is dead
3. If the HiveCli/HiveServer2 dies without closing the HDFS file, NN will reclaim the
   lease after 10 min, ie, the HDFS file hold by the dead HiveCli/HiveServer2 is writable
   again after 10 min. Once it become writable, cleardanglingscratchDir will be able to
   remove it
4. Additional functionality; once it is decided which session scratch dirs are residual,
   while removing them from hdfs, we will remove them from local tmp location as well.
   Please see {@link ClearDanglingScratchDir#removeLocalTmpFiles(String, String)}.
ql/src/java/org/apache/hadoop/hive/ql/session/ClearDanglingScratchDir.java