@@ -22,6 +22,8 @@ import java.net.URI
2222import java .text .SimpleDateFormat
2323import java .util .{Date , Locale , Random }
2424
25+ import scala .util .control .NonFatal
26+
2527import org .apache .hadoop .fs .{FileSystem , Path }
2628import org .apache .hadoop .hive .common .FileUtils
2729import org .apache .hadoop .hive .ql .exec .TaskRunner
@@ -84,6 +86,7 @@ case class InsertIntoHiveTable(
8486 def output : Seq [Attribute ] = Seq .empty
8587
8688 val hadoopConf = sessionState.newHadoopConf()
89+ var createdTempDir : Option [Path ] = None
8790 val stagingDir = hadoopConf.get(" hive.exec.stagingdir" , " .hive-staging" )
8891 val scratchDir = hadoopConf.get(" hive.exec.scratchdir" , " /tmp/hive" )
8992
@@ -111,12 +114,12 @@ case class InsertIntoHiveTable(
111114 if (! FileUtils .mkdir(fs, dir, true , hadoopConf)) {
112115 throw new IllegalStateException (" Cannot create staging directory '" + dir.toString + " '" )
113116 }
117+ createdTempDir = Some (dir)
114118 fs.deleteOnExit(dir)
115119 } catch {
116120 case e : IOException =>
117121 throw new RuntimeException (
118122 " Cannot create staging directory '" + dir.toString + " ': " + e.getMessage, e)
119-
120123 }
121124 return dir
122125 }
@@ -163,11 +166,11 @@ case class InsertIntoHiveTable(
163166 if (! FileUtils .mkdir(fs, dirPath, true , hadoopConf)) {
164167 throw new IllegalStateException (" Cannot create staging directory: " + dirPath.toString)
165168 }
169+ createdTempDir = Some (dirPath)
166170 fs.deleteOnExit(dirPath)
167171 } catch {
168172 case e : IOException =>
169173 throw new RuntimeException (" Cannot create staging directory: " + dirPath.toString, e)
170-
171174 }
172175 dirPath
173176 }
@@ -376,6 +379,15 @@ case class InsertIntoHiveTable(
376379 holdDDLTime)
377380 }
378381
382+ // Attempt to delete the staging directory and the inclusive files. If failed, the files are
383+ // expected to be dropped at the normal termination of VM since deleteOnExit is used.
384+ try {
385+ createdTempDir.foreach { path => path.getFileSystem(hadoopConf).delete(path, true ) }
386+ } catch {
387+ case NonFatal (e) =>
388+ logWarning(s " Unable to delete staging directory: $stagingDir. \n " + e)
389+ }
390+
379391 // Invalidate the cache.
380392 sqlContext.sharedState.cacheManager.invalidateCache(table)
381393 sqlContext.sessionState.catalog.refreshTable(table.catalogTable.identifier)
0 commit comments