├── README.md ├── .gitignore ├── pom.xml ├── LICENSE └── src └── AlluxioBlockManager.scala /README.md: -------------------------------------------------------------------------------- 1 | # Spark-alluxio-blockstore 2 | Apache Spark off heap cache block manager over alluxio. 3 | ## Configuration 4 | `spark.externalBlockStore.blockManager=org.apache.spark.storage.AlluxioBlockManager` 5 | `spark.externalBlockStore.url=alluxio://localhost:19998` 6 | ## Details 7 | Because the api in Alluxio1.0 is quite different with Tachyon, the old TachyonBlockManager cannot work with the Alluxio1.0. 8 | AlluxioBlockManager can replace the default TachyonBlockManager. 9 | The detail: https://github.com/chengqiangboy/blog/blob/master/spark/spark-off_heap.md 10 | The way using AlluxioBlockManager is the same as default. 11 | ```scala 12 | myRdd.persist(StorageLevel.OFF_HEAP) 13 | myDataFrame.persist(StorageLevel.OFF_HEAP) 14 | ``` 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.#* 3 | *#*# 4 | *.swp 5 | *.ipr 6 | *.iml 7 | *.iws 8 | *.pyc 9 | *.pyo 10 | .idea/ 11 | .idea_modules/ 12 | build/*.jar 13 | .settings 14 | .cache 15 | cache 16 | .generated-mima* 17 | work/ 18 | out/ 19 | .DS_Store 20 | third_party/libmesos.so 21 | third_party/libmesos.dylib 22 | build/apache-maven* 23 | build/zinc* 24 | build/scala* 25 | conf/java-opts 26 | conf/*.sh 27 | conf/*.cmd 28 | conf/*.properties 29 | conf/*.conf 30 | conf/*.xml 31 | conf/slaves 32 | docs/_site 33 | docs/api 34 | target/ 35 | reports/ 36 | .project 37 | .classpath 38 | .scala_dependencies 39 | lib_managed/ 40 | src_managed/ 41 | project/boot/ 42 | project/plugins/project/build.properties 43 | project/build/target/ 44 | project/plugins/target/ 45 | project/plugins/lib_managed/ 46 | project/plugins/src_managed/ 47 | logs/ 48 | log/ 49 | spark-tests.log 50 | streaming-tests.log 51 | dependency-reduced-pom.xml 52 | .ensime 53 | .ensime_cache/ 54 | .ensime_lucene 55 | checkpoint 56 | derby.log 57 | dist/ 58 | dev/create-release/*txt 59 | dev/create-release/*final 60 | spark-*-bin-*.tgz 61 | unit-tests.log 62 | /lib/ 63 | ec2/lib/ 64 | rat-results.txt 65 | scalastyle.txt 66 | scalastyle-output.xml 67 | R-unit-tests.log 68 | R/unit-tests.out 69 | python/lib/pyspark.zip 70 | lint-r-report.log 71 | 72 | # For Hive 73 | metastore_db/ 74 | metastore/ 75 | warehouse/ 76 | TempStatsStore/ 77 | sql/hive-thriftserver/test_warehouses 78 | 79 | # For R session data 80 | .RHistory 81 | .RData 82 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | cq 4 | spark-alluxio-blockstore 5 | 0.0.1-SNAPSHOT 6 | 7 | 8 | 9 | 10 | org.apache.spark 11 | spark-core_2.10 12 | 1.6.2 13 | provided 14 | 15 | 16 | 17 | org.alluxio 18 | alluxio-core-client 19 | 1.0.1 20 | 21 | 22 | 23 | org.scala-lang 24 | scala-library 25 | 2.10.5 26 | compile 27 | 28 | 29 | 30 | org.scala-lang 31 | scala-compiler 32 | 2.10.5 33 | compile 34 | 35 | 36 | 37 | 38 | 39 | src 40 | 41 | 42 | net.alchim31.maven 43 | scala-maven-plugin 44 | 3.2.2 45 | 46 | 47 | 48 | add-source 49 | compile 50 | 51 | 52 | 53 | 54 | 55 | 56 | maven-assembly-plugin 57 | 2.6 58 | 59 | 60 | jar-with-dependencies 61 | 62 | 63 | 64 | 65 | make-assembly 66 | package 67 | 68 | single 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/AlluxioBlockManager.scala: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one or more 3 | * contributor license agreements. See the NOTICE file distributed with 4 | * this work for additional information regarding copyright ownership. 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 6 | * (the "License"); you may not use this file except in compliance with 7 | * the License. You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | package org.apache.spark.storage 19 | 20 | import java.io.{IOException, OutputStream} 21 | import java.nio.ByteBuffer 22 | import java.text.SimpleDateFormat 23 | import java.util.{Date, Random} 24 | 25 | import scala.util.control.NonFatal 26 | import com.google.common.io.ByteStreams 27 | import alluxio.{AlluxioURI, Constants} 28 | import alluxio.client.ClientContext 29 | import alluxio.client.file.{FileOutStream, FileSystem} 30 | import alluxio.client.file.FileSystem.Factory 31 | import alluxio.client.file.options.{CreateDirectoryOptions, DeleteOptions} 32 | import alluxio.exception.{FileAlreadyExistsException, FileDoesNotExistException} 33 | import org.apache.spark.Logging 34 | import org.apache.spark.executor.ExecutorExitCode 35 | import org.apache.spark.util.Utils 36 | 37 | 38 | /** 39 | * Creates and maintains the logical mapping between logical blocks and alluxio fs locations. By 40 | * default, one block is mapped to one file with a name given by its BlockId. 41 | * 42 | */ 43 | private[spark] class AlluxioBlockManager() extends ExternalBlockManager with Logging { 44 | 45 | var rootDirs: String = _ 46 | var master: String = _ 47 | var client: FileSystem = _ 48 | private var subDirsPerAlluxioDir: Int = _ 49 | 50 | // Create one Alluxio directory for each path mentioned in spark.alluxioStore.folderName; 51 | // then, inside this directory, create multiple subdirectories that we will hash files into, 52 | // in order to avoid having really large inodes at the top level in Alluxio. 53 | private var alluxioDirs: Array[AlluxioURI] = _ 54 | private var subDirs: Array[Array[AlluxioURI]] = _ 55 | private val shutdownDeleteAlluxioPaths = new scala.collection.mutable.HashSet[String]() 56 | 57 | override def init(blockManager: BlockManager, executorId: String): Unit = { 58 | super.init(blockManager, executorId) 59 | val storeDir = blockManager.conf.get(ExternalBlockStore.BASE_DIR, "/tmp_spark_alluxio") 60 | val appFolderName = blockManager.conf.get(ExternalBlockStore.FOLD_NAME) 61 | 62 | rootDirs = s"$storeDir/$appFolderName/$executorId" 63 | master = blockManager.conf.get(ExternalBlockStore.MASTER_URL, "alluxio://localhost:19998") 64 | val value = master.replace("/", "").split(":") 65 | client = if (master != null && master != "") { 66 | ClientContext.getConf.set(Constants.MASTER_HOSTNAME, value(1)) 67 | ClientContext.init() 68 | Factory.get() 69 | } else { 70 | null 71 | } 72 | // original implementation call System.exit, we change it to run without extblkstore support 73 | if (client == null) { 74 | logError("Failed to connect to the Alluxio as the master address is not configured") 75 | throw new IOException("Failed to connect to the Alluxio as the master " + 76 | "address is not configured") 77 | } 78 | subDirsPerAlluxioDir = blockManager.conf.get("spark.externalBlockStore.subDirectories", 79 | ExternalBlockStore.SUB_DIRS_PER_DIR).toInt 80 | 81 | // Create one Alluxio directory for each path mentioned in spark.alluxioStore.folderName; 82 | // then, inside this directory, create multiple subdirectories that we will hash files into, 83 | // in order to avoid having really large inodes at the top level in Alluxio. 84 | alluxioDirs = createAlluxioDirs() 85 | subDirs = Array.fill(alluxioDirs.length)(new Array[AlluxioURI](subDirsPerAlluxioDir)) 86 | alluxioDirs.foreach(registerShutdownDeleteDir) 87 | } 88 | 89 | override def toString: String = {"ExternalBlockStore-Alluxio"} 90 | 91 | override def removeBlock(blockId: BlockId): Boolean = { 92 | val file = getFile(blockId) 93 | if (fileExists(file)) { 94 | removeFile(file) 95 | true 96 | } else { 97 | false 98 | } 99 | } 100 | 101 | override def blockExists(blockId: BlockId): Boolean = { 102 | val file = getFile(blockId) 103 | fileExists(file) 104 | } 105 | 106 | 107 | def writeByteBuffer(bb: ByteBuffer, out: OutputStream): Unit = { 108 | if (bb.hasArray) { 109 | out.write(bb.array(), bb.arrayOffset() + bb.position(), bb.remaining()) 110 | } else { 111 | val bbval = new Array[Byte](bb.remaining()) 112 | bb.get(bbval) 113 | out.write(bbval) 114 | } 115 | } 116 | 117 | override def putBytes(blockId: BlockId, bytes: ByteBuffer): Unit = { 118 | val file = getFile(blockId) 119 | var os: FileOutStream = null 120 | try { 121 | os = client.createFile(file) 122 | writeByteBuffer(bytes, os) 123 | } catch { 124 | case NonFatal(e) => 125 | logWarning(s"Failed to put bytes of block $blockId into Alluxio", e) 126 | os.cancel() 127 | case _: FileAlreadyExistsException => file 128 | } finally { 129 | os.close() 130 | } 131 | } 132 | 133 | override def putValues(blockId: BlockId, values: Iterator[_]): Unit = { 134 | val file = getFile(blockId) 135 | var os: FileOutStream = null 136 | try { 137 | os = client.createFile(file) 138 | blockManager.dataSerializeStream(blockId, os, values) 139 | } catch { 140 | case NonFatal(e) => 141 | logWarning(s"Failed to put values of block $blockId into Alluxio", e) 142 | os.cancel() 143 | case _: FileAlreadyExistsException => file 144 | } finally { 145 | os.close() 146 | } 147 | } 148 | 149 | override def getBytes(blockId: BlockId): Option[ByteBuffer] = { 150 | val file = getFile(blockId) 151 | if (file == null) { 152 | return None 153 | } 154 | val is = try { 155 | client.openFile(file) 156 | } catch { 157 | case _: FileDoesNotExistException => 158 | return None 159 | } 160 | try { 161 | val size = getSize(blockId) 162 | val bs = new Array[Byte](size.asInstanceOf[Int]) 163 | ByteStreams.readFully(is, bs) 164 | Some(ByteBuffer.wrap(bs)) 165 | } catch { 166 | case NonFatal(e) => 167 | logWarning(s"Failed to get bytes of block $blockId from Alluxio", e) 168 | None 169 | } finally { 170 | is.close() 171 | } 172 | } 173 | 174 | override def getValues(blockId: BlockId): Option[Iterator[_]] = { 175 | val file = getFile(blockId) 176 | if (file == null) { 177 | return None 178 | } 179 | val is = try { 180 | client.openFile(file) 181 | } catch { 182 | case _: FileDoesNotExistException => 183 | return None 184 | } 185 | try { 186 | Some(blockManager.dataDeserializeStream(blockId, is)) 187 | } catch{ 188 | case NonFatal(e) => 189 | logWarning(s"Failed to get values of block $blockId from Alluxio", e) 190 | None 191 | }finally { 192 | //is.close() 193 | } 194 | } 195 | 196 | override def getSize(blockId: BlockId): Long = { 197 | client.getStatus(getFile(blockId)).getLength 198 | } 199 | 200 | def removeFile(file: AlluxioURI): Unit = { 201 | client.delete(file) 202 | } 203 | 204 | def fileExists(file: AlluxioURI): Boolean = { 205 | try { 206 | client.exists(file) 207 | } catch { 208 | case _: FileDoesNotExistException => false 209 | } 210 | } 211 | 212 | def getFile(filename: String): AlluxioURI = { 213 | // Figure out which alluxio directory it hashes to, and which subdirectory in that 214 | val hash = Utils.nonNegativeHash(filename) 215 | val dirId = hash % alluxioDirs.length 216 | val subDirId = (hash / alluxioDirs.length) % subDirsPerAlluxioDir 217 | 218 | // Create the subdirectory if it doesn't already exist 219 | var subDir = subDirs(dirId)(subDirId) 220 | if (subDir == null) { 221 | subDir = subDirs(dirId).synchronized { 222 | val old = subDirs(dirId)(subDirId) 223 | if (old != null) { 224 | old 225 | } else { 226 | val path = new AlluxioURI(s"${alluxioDirs(dirId)}/${"%02x".format(subDirId)}") 227 | client.createDirectory(path, CreateDirectoryOptions.defaults().setRecursive(true)) 228 | subDirs(dirId)(subDirId) = path 229 | path 230 | } 231 | } 232 | } 233 | new AlluxioURI(s"$subDir/$filename") 234 | } 235 | 236 | def getFile(blockId: BlockId): AlluxioURI = getFile(blockId.name) 237 | 238 | // TODO: Some of the logic here could be consolidated/de-duplicated with that in the DiskStore. 239 | private def createAlluxioDirs(): Array[AlluxioURI] = { 240 | logDebug("Creating alluxio directories at root dirs '" + rootDirs + "'") 241 | val dateFormat = new SimpleDateFormat("yyyyMMddHHmmss") 242 | rootDirs.split(",").map { rootDir => 243 | var foundLocalDir = false 244 | var alluxioDir: AlluxioURI = null 245 | var alluxioDirId: String = null 246 | var tries = 0 247 | val rand = new Random() 248 | while (!foundLocalDir && tries < ExternalBlockStore.MAX_DIR_CREATION_ATTEMPTS) { 249 | tries += 1 250 | try { 251 | alluxioDirId = "%s-%04x".format(dateFormat.format(new Date), rand.nextInt(65536)) 252 | val path = new AlluxioURI(s"$rootDir/spark-alluxio-$alluxioDirId") 253 | try { 254 | client.createDirectory(path, CreateDirectoryOptions.defaults().setRecursive(true)) 255 | alluxioDir = path 256 | foundLocalDir = true 257 | } catch { 258 | case _: FileAlreadyExistsException => // continue 259 | } 260 | } catch { 261 | case NonFatal(e) => 262 | logWarning("Attempt " + tries + " to create alluxio dir " + alluxioDir + " failed", e) 263 | } 264 | } 265 | if (!foundLocalDir) { 266 | logError("Failed " + ExternalBlockStore.MAX_DIR_CREATION_ATTEMPTS 267 | + " attempts to create alluxio dir in " + rootDir) 268 | System.exit(ExecutorExitCode.EXTERNAL_BLOCK_STORE_FAILED_TO_CREATE_DIR) 269 | } 270 | logInfo("Created alluxio directory at " + alluxioDir) 271 | alluxioDir 272 | } 273 | } 274 | 275 | override def shutdown() { 276 | logDebug("Shutdown hook called") 277 | alluxioDirs.foreach { alluxioDir => 278 | try { 279 | if (!hasRootAsShutdownDeleteDir(alluxioDir)) { 280 | deleteRecursively(alluxioDir, client) 281 | } 282 | } catch { 283 | case NonFatal(e) => 284 | logError("Exception while deleting alluxio spark dir: " + alluxioDir, e) 285 | } 286 | } 287 | } 288 | 289 | /** 290 | * Delete a file or directory and its contents recursively. 291 | */ 292 | private def deleteRecursively(dir: AlluxioURI, client: FileSystem) { 293 | client.delete(dir, DeleteOptions.defaults().setRecursive(true)) 294 | } 295 | 296 | // Register the alluxio path to be deleted via shutdown hook 297 | private def registerShutdownDeleteDir(file: AlluxioURI) { 298 | val absolutePath = file.toString 299 | shutdownDeleteAlluxioPaths.synchronized { 300 | shutdownDeleteAlluxioPaths += absolutePath 301 | } 302 | } 303 | 304 | // Remove the alluxio path to be deleted via shutdown hook 305 | private def removeShutdownDeleteDir(file: AlluxioURI) { 306 | val absolutePath = file.toString 307 | shutdownDeleteAlluxioPaths.synchronized { 308 | shutdownDeleteAlluxioPaths -= absolutePath 309 | } 310 | } 311 | 312 | // Is the path already registered to be deleted via a shutdown hook ? 313 | private def hasShutdownDeleteAlluxioDir(file: AlluxioURI): Boolean = { 314 | val absolutePath = file.toString 315 | shutdownDeleteAlluxioPaths.synchronized { 316 | shutdownDeleteAlluxioPaths.contains(absolutePath) 317 | } 318 | } 319 | 320 | // Note: if file is child of some registered path, while not equal to it, then return true; 321 | // else false. This is to ensure that two shutdown hooks do not try to delete each others 322 | // paths - resulting in Exception and incomplete cleanup. 323 | private def hasRootAsShutdownDeleteDir(file: AlluxioURI): Boolean = { 324 | val absolutePath = file.toString 325 | val hasRoot = shutdownDeleteAlluxioPaths.synchronized { 326 | shutdownDeleteAlluxioPaths.exists( 327 | path => !absolutePath.equals(path) && absolutePath.startsWith(path)) 328 | } 329 | if (hasRoot) { 330 | logInfo(s"path = $absolutePath, already present as root for deletion.") 331 | } 332 | hasRoot 333 | } 334 | 335 | } 336 | --------------------------------------------------------------------------------