You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2021/06/16 09:05:09 UTC
[GitHub] [spark] xuanyuanking opened a new pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
xuanyuanking opened a new pull request #32928:
URL: https://github.com/apache/spark/pull/32928
### What changes were proposed in this pull request?
The implementation for the RocksDB instance, which is used in the RocksDB state store. It plays a role as a handler for the RocksDB instance and RocksDBFileManager.
### Why are the changes needed?
Part of the RocksDB state store implementation.
### Does this PR introduce _any_ user-facing change?
No.
### How was this patch tested?
New UT added.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659732879
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/util/RocksDBLoader.scala
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.apache.spark.sql.util
Review comment:
Make sense, moved to streaming module.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] dongjoon-hyun commented on a change in pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
dongjoon-hyun commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r654049392
##########
File path: sql/core/pom.xml
##########
@@ -35,6 +35,11 @@
</properties>
<dependencies>
+ <dependency>
+ <groupId>org.rocksdb</groupId>
+ <artifactId>rocksdbjni</artifactId>
+ <version>6.2.2</version>
Review comment:
Shall we use the latest version?
- https://mvnrepository.com/artifact/org.rocksdb/rocksdbjni/6.20.3
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865653998
I'd rather say the version bump would be a no-go till we figure out either it is backward compatible, or quite easy way to migrate the old one to the new one. This applies to the changes on LevelDB to RocksDB.
Given the importance, I'd like to see the efforts in different JIRA and be orthogonal efforts with RocksDB state store provider.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660331043
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
+ }
+ }
+
+ var dbLogLevel = InfoLogLevel.ERROR_LEVEL
+ if (log.isWarnEnabled) dbLogLevel = InfoLogLevel.WARN_LEVEL
+ if (log.isInfoEnabled) dbLogLevel = InfoLogLevel.INFO_LEVEL
+ if (log.isDebugEnabled) dbLogLevel = InfoLogLevel.DEBUG_LEVEL
+ dbOptions.setLogger(dbLogger)
+ dbOptions.setInfoLogLevel(dbLogLevel)
+ logInfo(s"Set DB native logging level to $dbLogLevel")
Review comment:
Sure, done in the next commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660297030
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
Review comment:
Rethink about it, I can get what it means. So it is not actually straightforward.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659628370
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def getDBProperty(property: String): Long = {
Review comment:
Yea, it's used in the metrics-related PR. I delete it in the next commit.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/util/RocksDBLoader.scala
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.apache.spark.sql.util
+
+import org.rocksdb._
Review comment:
Make sense, only one, fixed in the next commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r654942339
##########
File path: sql/core/pom.xml
##########
@@ -35,6 +35,11 @@
</properties>
<dependencies>
+ <dependency>
+ <groupId>org.rocksdb</groupId>
+ <artifactId>rocksdbjni</artifactId>
+ <version>6.2.2</version>
Review comment:
@dongjoon-hyun Thanks for taking care. Following the comments from Yikun in http://apache-spark-developers-list.1001551.n3.nabble.com/DISCUSS-Add-RocksDB-StateStore-tt30645.html, I planned to upgrade the rocksdb version after all the code shipped. At least >=6.4.6 for the Arm64 support.
Personally, I think it's good to keep the 6.2.2 since this is well tested in the production environment and it's safe to use it in the first stage. I believe the latest RocksDB versions are stable enough, but the state store implementation has its own design on the snapshot/checkpoint file architecture, it's good to spend more time on testing whether we can safely upgrade it to the latest RocksDB version. WDYT?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-862194866
**[Test build #139867 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/139867/testReport)** for PR 32928 at commit [`bbb534e`](https://github.com/apache/spark/commit/bbb534e841d4c32c821fc0ae85ceb5b077e0dad0).
* This patch **fails to build**.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `class RocksDB(`
* `class ByteArrayPair(var key: Array[Byte] = null, var value: Array[Byte] = null) `
* `case class RocksDBConf(`
* `case class AcquiredThreadInfo(`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865216767
Kubernetes integration test status failure
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/44614/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660300861
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
+ }
+ }
+
+ var dbLogLevel = InfoLogLevel.ERROR_LEVEL
+ if (log.isWarnEnabled) dbLogLevel = InfoLogLevel.WARN_LEVEL
+ if (log.isInfoEnabled) dbLogLevel = InfoLogLevel.INFO_LEVEL
+ if (log.isDebugEnabled) dbLogLevel = InfoLogLevel.DEBUG_LEVEL
+ dbOptions.setLogger(dbLogger)
+ dbOptions.setInfoLogLevel(dbLogLevel)
+ logInfo(s"Set DB native logging level to $dbLogLevel")
Review comment:
We can be more specified. `DB` -> `RocksDB`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-868507000
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/44854/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660365487
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
Review comment:
Here "all" seems to make confusion. The number only represents for "one" version, hence the confusion.
Now I think it'd be nice if we can rename the field name to represent these fields are representing the number of keys per certain version. I guess below candidates could help avoiding confusion:
* numKeysOnLoadedVersion - numKeysOnWritingVersion
* numKeysOnCommittedVersion - numKeysOnUncommittedCommittingVersion
* or better names
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
Review comment:
Here "all" seems to make confusion. The number only represents for "one" version, hence the confusion.
Now I think it'd be nice if we can rename the field name to represent these fields are representing the number of keys per certain version. I guess below candidates could help avoiding confusion:
* numKeysOnLoadedVersion - numKeysOnWritingVersion
* numKeysOnCommittedVersion - numKeysOnUncommittedCommittingVersion
* or better names
even without code comment.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865150190
@dongjoon-hyun Thanks for the information!
```
Please fix Scala 2.13 build, @xuanyuanking .
```
Sure
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865216800
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/44614/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on a change in pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r655964610
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDBFileManager.scala
##########
@@ -153,6 +156,49 @@ class RocksDBFileManager(
logInfo(s"Saved checkpoint file for version $version")
}
+ /**
+ * Load all necessary files for specific checkpoint version from DFS to given local directory.
+ * If version is 0, then it will deleted all files in the directory. For other versions, it
+ * ensures that only the exact files generated during checkpointing will be present in the
+ * local directory.
+ */
+ def loadCheckpointFromDfs(version: Long, localDir: File): RocksDBCheckpointMetadata = {
Review comment:
If I understand correctly, commit 80154b2 should be the only change we need to review here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-868491577
Kubernetes integration test status success
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/44854/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r655929725
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/util/RocksDBLoader.scala
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.apache.spark.sql.util
Review comment:
`sql.util`? why not in `org.apache.spark.sql.execution.streaming`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/util/RocksDBLoader.scala
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.apache.spark.sql.util
+
+import org.rocksdb._
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.UninterruptibleThread
+
+/**
+ * A wrapper for RocksDB library loading using an uninterruptible thread, as the native RocksDB
+ * code will throw an error when interrupted.
+ */
+object RocksDBLoader extends Logging {
+ /**
+ * Keep tracks of the exception thrown from the loading thread, if any.
+ */
+ private var exception: Option[Throwable] = null
+
+ private val loadLibraryThread = new UninterruptibleThread("RocksDB") {
Review comment:
RocksDB -> RocksDBLoader
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDBFileManager.scala
##########
@@ -153,6 +156,49 @@ class RocksDBFileManager(
logInfo(s"Saved checkpoint file for version $version")
}
+ /**
+ * Load all necessary files for specific checkpoint version from DFS to given local directory.
+ * If version is 0, then it will deleted all files in the directory. For other versions, it
+ * ensures that only the exact files generated during checkpointing will be present in the
+ * local directory.
+ */
+ def loadCheckpointFromDfs(version: Long, localDir: File): RocksDBCheckpointMetadata = {
Review comment:
Is this basically the same as #32767, right?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
Review comment:
`and return the last written value`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
Review comment:
Same here, if the value could be from committed db, how can we always decrease `numUncommittedKeys`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo(s"Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion in $checkpointDir")
Review comment:
`in $checkpointDir` -> "to DFS"?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
Review comment:
`openDB()` will close DB. This looks redundant.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
Review comment:
Can these options be configured in the future?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo(s"Compacting")
Review comment:
nit: don't need s"".
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
Review comment:
manager -> fileManager?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
Review comment:
`createTempDir` will mkdir, no?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
Review comment:
If old value is not null, couldn't it be from committed db? How do we know it must be uncommitted one (and skipping increasing `numUncommittedKeys`)?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
Review comment:
This looks confusing. Why committed and uncommitted keys are both `numKeys`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
Review comment:
So it first looks at uncommitted value, if not exist, then looks for committed value?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR edited a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
HeartSaVioR edited a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865653998
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659548996
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
Review comment:
Thanks, done in f928820
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-868470606
Kubernetes integration test starting
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/44854/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r658824970
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
Review comment:
Thanks, deleted in 606a38b
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/util/RocksDBLoader.scala
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.apache.spark.sql.util
+
+import org.rocksdb._
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.UninterruptibleThread
+
+/**
+ * A wrapper for RocksDB library loading using an uninterruptible thread, as the native RocksDB
+ * code will throw an error when interrupted.
+ */
+object RocksDBLoader extends Logging {
+ /**
+ * Keep tracks of the exception thrown from the loading thread, if any.
+ */
+ private var exception: Option[Throwable] = null
+
+ private val loadLibraryThread = new UninterruptibleThread("RocksDB") {
Review comment:
Done in 606a38b
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660330823
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
Review comment:
Thanks, done in the next commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] dongjoon-hyun commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
dongjoon-hyun commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660235291
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
Review comment:
~After we re-throw this, `loadedVersion` is used for some purpose in the upper layer? I'm wondering if this is recoverable error and `loadedVersion` is a valuable information to be used later in that case.~ Never mind.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-864464770
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/44553/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865216800
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] dongjoon-hyun commented on pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
dongjoon-hyun commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-871012152
No other comments. Thank you for asking, @viirya .
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660299140
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
Review comment:
`stopping` -> `closing RocksDB`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-862194908
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/139867/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r655925921
##########
File path: sql/core/pom.xml
##########
@@ -35,6 +35,11 @@
</properties>
<dependencies>
+ <dependency>
+ <groupId>org.rocksdb</groupId>
+ <artifactId>rocksdbjni</artifactId>
+ <version>6.2.2</version>
Review comment:
Sounds good to have well tested version first.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/util/RocksDBLoader.scala
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.apache.spark.sql.util
Review comment:
`sql.util`? why not in `org.apache.spark.sql.execution.streaming`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/util/RocksDBLoader.scala
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.apache.spark.sql.util
+
+import org.rocksdb._
+
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.UninterruptibleThread
+
+/**
+ * A wrapper for RocksDB library loading using an uninterruptible thread, as the native RocksDB
+ * code will throw an error when interrupted.
+ */
+object RocksDBLoader extends Logging {
+ /**
+ * Keep tracks of the exception thrown from the loading thread, if any.
+ */
+ private var exception: Option[Throwable] = null
+
+ private val loadLibraryThread = new UninterruptibleThread("RocksDB") {
Review comment:
RocksDB -> RocksDBLoader
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDBFileManager.scala
##########
@@ -153,6 +156,49 @@ class RocksDBFileManager(
logInfo(s"Saved checkpoint file for version $version")
}
+ /**
+ * Load all necessary files for specific checkpoint version from DFS to given local directory.
+ * If version is 0, then it will deleted all files in the directory. For other versions, it
+ * ensures that only the exact files generated during checkpointing will be present in the
+ * local directory.
+ */
+ def loadCheckpointFromDfs(version: Long, localDir: File): RocksDBCheckpointMetadata = {
Review comment:
Is this basically the same as #32767, right?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
Review comment:
`and return the last written value`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
Review comment:
Same here, if the value could be from committed db, how can we always decrease `numUncommittedKeys`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo(s"Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion in $checkpointDir")
Review comment:
`in $checkpointDir` -> "to DFS"?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
Review comment:
`openDB()` will close DB. This looks redundant.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
Review comment:
Can these options be configured in the future?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo(s"Compacting")
Review comment:
nit: don't need s"".
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
Review comment:
manager -> fileManager?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
Review comment:
`createTempDir` will mkdir, no?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
Review comment:
If old value is not null, couldn't it be from committed db? How do we know it must be uncommitted one (and skipping increasing `numUncommittedKeys`)?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
Review comment:
This looks confusing. Why committed and uncommitted keys are both `numKeys`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
Review comment:
So it first looks at uncommitted value, if not exist, then looks for committed value?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865286343
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/140087/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-870963619
**[Test build #140374 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140374/testReport)** for PR 32928 at commit [`21e1728`](https://github.com/apache/spark/commit/21e1728cddab0fcd39886d914190a899aaac6d59).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660365487
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
Review comment:
Here "all" seems to make confusion. The number only represents for "one" version, hence the confusion.
Now I think it'd be nice if we can rename the field name to represent these fields are representing the number of keys per certain version. I guess below candidates could help avoiding confusion:
* numKeysOnLoadedVersion - numKeysOnWritingVersion
* numKeysOnCommittedVersion - numKeysOnUncommittedCommittingVersion
* or better names
even without code comment.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660365487
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
Review comment:
Here "all" seems to make confusion. The number only represents for "one" version, hence the confusion.
Now I think it'd be nice if we can rename the field name to represent these fields are representing the number of keys per certain version. I guess below candidates could help avoiding confusion:
* numKeysOnLoadedVersion - numKeysOnWritingVersion
* numKeysOnCommittedVersion - numKeysOnUncommittedCommittingVersion
* or better names
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660321111
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
Review comment:
Thanks, changed in the next commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660330089
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
Review comment:
Thanks, done in the next commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA removed a comment on pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-870825069
**[Test build #140374 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140374/testReport)** for PR 32928 at commit [`21e1728`](https://github.com/apache/spark/commit/21e1728cddab0fcd39886d914190a899aaac6d59).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659599074
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
Review comment:
We should consider the `num[Unc/C]ommittedKeys` as a kind of status here, the number here means the absolute value from the beginning(version 0) to now. So that's also why there's no place we set the `numUncommittedKeys` to 0.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA removed a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-862190762
**[Test build #139867 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/139867/testReport)** for PR 32928 at commit [`bbb534e`](https://github.com/apache/spark/commit/bbb534e841d4c32c821fc0ae85ceb5b077e0dad0).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-868438682
**[Test build #140322 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140322/testReport)** for PR 32928 at commit [`606a38b`](https://github.com/apache/spark/commit/606a38b8cf50827d5728ff70b89d25395c268696).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] dongjoon-hyun commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
dongjoon-hyun commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660244079
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
Review comment:
nit. Could you add `@GuardedBy("acquireLock")`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-870964481
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/140374/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660300690
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
Review comment:
`Native` -> `NativeRocksDB`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660329648
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
Review comment:
It's also used in the `commit` operation, which will be introduced in the next commit: https://github.com/apache/spark/pull/32933/files#diff-4663b8349511dc040c3d5204bb6868064002d0b45aadaf1f1795a683897a5c7dR224
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660295530
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
Review comment:
why it is for "all committed versions"? In `load`, we just overwrite it `numCommittedKeys = metadata.numKeys`. So looks like it is only for the loaded version.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
Review comment:
I see. Makes sense.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
Review comment:
Maybe be `numKeysInCurrentVersion`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
Review comment:
Rethink about it, I can get what it means. So it is not actually straightforward.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
Review comment:
`finished committing $newVersion`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
Review comment:
`stopping` -> `closing RocksDB`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
Review comment:
`Native` -> `NativeRocksDB`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
+ }
+ }
+
+ var dbLogLevel = InfoLogLevel.ERROR_LEVEL
+ if (log.isWarnEnabled) dbLogLevel = InfoLogLevel.WARN_LEVEL
+ if (log.isInfoEnabled) dbLogLevel = InfoLogLevel.INFO_LEVEL
+ if (log.isDebugEnabled) dbLogLevel = InfoLogLevel.DEBUG_LEVEL
+ dbOptions.setLogger(dbLogger)
+ dbOptions.setInfoLogLevel(dbLogLevel)
+ logInfo(s"Set DB native logging level to $dbLogLevel")
Review comment:
We can be more specified. `DB` -> `RocksDB`
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
+ }
+ }
+
+ var dbLogLevel = InfoLogLevel.ERROR_LEVEL
+ if (log.isWarnEnabled) dbLogLevel = InfoLogLevel.WARN_LEVEL
+ if (log.isInfoEnabled) dbLogLevel = InfoLogLevel.INFO_LEVEL
+ if (log.isDebugEnabled) dbLogLevel = InfoLogLevel.DEBUG_LEVEL
+ dbOptions.setLogger(dbLogger)
+ dbOptions.setInfoLogLevel(dbLogLevel)
+ logInfo(s"Set DB native logging level to $dbLogLevel")
+ dbLogger
+ }
+
+ /** Create a temp directory inside the local root directory */
+ private def createTempDir(prefix: String): File = {
+ Utils.createDirectory(localRootDir.getAbsolutePath, prefix)
+ }
+
+ /** Attempt to delete recursively, and log the error if any */
+ private def silentDeleteRecursively(file: File, msg: String): Unit = {
+ try {
+ Utils.deleteRecursively(file)
+ } catch {
+ case e: Exception =>
+ logWarning(s"Error recursively deleting local dir $file while $msg", e)
+ }
+ }
+
+ /** Records the duration of running `body` for the next query progress update. */
+ protected def timeTakenMs(body: => Unit): Long = Utils.timeTakenMs(body)._2
+
+ override protected def logName: String = s"${super.logName} $loggingId"
+}
+
+
+/** Mutable and reusable pair of byte arrays */
+class ByteArrayPair(var key: Array[Byte] = null, var value: Array[Byte] = null) {
+ def set(key: Array[Byte], value: Array[Byte]): ByteArrayPair = {
+ this.key = key
+ this.value = value
+ this
+ }
+}
+
+
+/**
+ * Configurations for optimizing RocksDB
+ *
+ * @param compactOnCommit Whether to compact RocksDB data before commit / checkpointing
+ */
+case class RocksDBConf(
+ minVersionsToRetain: Int,
+ compactOnCommit: Boolean,
+ pauseBackgroundWorkForCommit: Boolean,
+ blockSizeKB: Long,
+ blockCacheSizeMB: Long,
+ lockAcquireTimeoutMs: Long)
+
+object RocksDBConf {
+ /** Common prefix of all confs in SQLConf that affects RocksDB */
+ val ROCKSDB_CONF_NAME_PREFIX = "spark.sql.streaming.stateStore.rocksdb"
+
+ private case class ConfEntry(name: String, default: String) {
+ def fullName: String = s"$ROCKSDB_CONF_NAME_PREFIX.${name}".toLowerCase(Locale.ROOT)
+ }
+
+ // Configuration that specifies whether to compact the RocksDB data every time data is committed
+ private val COMPACT_ON_COMMIT_CONF = ConfEntry("compactOnCommit", "false")
+ private val PAUSE_BG_WORK_FOR_COMMIT_CONF = ConfEntry("pauseBackgroundWorkForCommit", "true")
+ private val BLOCK_SIZE_KB_CONF = ConfEntry("blockSizeKB", "4")
+ private val BLOCK_CACHE_SIZE_MB_CONF = ConfEntry("blockCacheSizeMB", "8")
+ private val LOCK_ACQUIRE_TIMEOUT_MS_CONF = ConfEntry("lockAcquireTimeoutMs", "60000")
Review comment:
Note that we should document these configs at the end.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-870825069
**[Test build #140374 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140374/testReport)** for PR 32928 at commit [`21e1728`](https://github.com/apache/spark/commit/21e1728cddab0fcd39886d914190a899aaac6d59).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-868547677
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/140322/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-862194908
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/139867/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659544499
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/util/RocksDBLoader.scala
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.apache.spark.sql.util
Review comment:
You may find the loader only related to the library loading work and not streaming only, so that's why I put it into `sql.util`.
Ether way is OK to me, WDYT?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865176623
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR edited a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
HeartSaVioR edited a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865653998
I'd rather say the version bump would be a no-go till we figure out either it is backward compatible (with RocksDB 6.2.2 as it has been used for production), or quite easy way to migrate the old one to the new one. This applies to the changes on LevelDB to RocksDB as well (SPARK-35782).
Given the importance, I'd like to see the efforts in different JIRA and be orthogonal efforts with RocksDB state store provider.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865653998
I'd rather say the version bump would be a no-go till we figure out either it is backward compatible, or quite easy way to migrate the old one to the new one. This applies to the changes on LevelDB to RocksDB.
Given the importance, I'd like to see the efforts in different JIRA and be orthogonal efforts with RocksDB state store provider.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659599307
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo(s"Compacting")
Review comment:
Thanks, done in f928820
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-869643429
All comments addressed done. Ready for another round of review.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r658456215
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
Review comment:
As the functionality of `getFromBatchAndDB`, it will get the key in both write batch and committed db.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya closed pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya closed pull request #32928:
URL: https://github.com/apache/spark/pull/32928
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659548852
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
Review comment:
Because for `load` operation, the numCommittedKeys should be the version loaded. The uncommitted key is `numKeys` because we may change or add new keys for the loaded version.
Considering the `rollback` operation together, it may easy to understand, we use `numCommittedKeys` to reset `numUncommittedKeys` when calling rollback.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] dongjoon-hyun commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
dongjoon-hyun commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660244934
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
Review comment:
maybe, `that the RocksDB inside running` -> `that the RocksDB is running`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-864457596
Kubernetes integration test starting
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/44553/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-870192493
Thanks @HeartSaVioR. I will take another look.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659588623
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
Review comment:
if we couldn't find a better name, we need to add code comment at least to explain this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-871043411
Thanks all for the review! I'll rebase the other PRs soon.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660296809
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
Review comment:
Maybe be `numKeysInCurrentVersion`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] dongjoon-hyun commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
dongjoon-hyun commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660238107
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
Review comment:
If you don't mind, shall we use a full name instead of `Bg`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r655925921
##########
File path: sql/core/pom.xml
##########
@@ -35,6 +35,11 @@
</properties>
<dependencies>
+ <dependency>
+ <groupId>org.rocksdb</groupId>
+ <artifactId>rocksdbjni</artifactId>
+ <version>6.2.2</version>
Review comment:
Sounds good to have well tested version first.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-868547677
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/140322/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-871015278
Thanks @xuanyuanking for this work! Merging to master.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-864461091
Kubernetes integration test status success
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/44553/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-868507000
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/44854/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-869643429
All comments addressed done. Ready for another round of review.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659633003
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def getDBProperty(property: String): Long = {
+ db.getProperty(property).toLong
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
+ }
+ }
+
+ var dbLogLevel = InfoLogLevel.ERROR_LEVEL
+ if (log.isWarnEnabled) dbLogLevel = InfoLogLevel.WARN_LEVEL
+ if (log.isInfoEnabled) dbLogLevel = InfoLogLevel.INFO_LEVEL
+ if (log.isDebugEnabled) dbLogLevel = InfoLogLevel.DEBUG_LEVEL
+ dbOptions.setLogger(dbLogger)
+ dbOptions.setInfoLogLevel(dbLogLevel)
+ logInfo(s"Set DB native logging level to $dbLogLevel")
+ dbLogger
+ }
+
+ /** Create a temp directory inside the local root directory */
+ private def createTempDir(prefix: String): File = {
+ Utils.createDirectory(localRootDir.getAbsolutePath, prefix)
+ }
+
+ /** Attempt to delete recursively, and log the error if any */
+ private def silentDeleteRecursively(file: File, msg: String): Unit = {
+ try {
+ Utils.deleteRecursively(file)
+ } catch {
+ case e: Exception =>
+ logWarning(s"Error recursively deleting local dir $file while $msg", e)
+ }
+ }
+
+ /** Records the duration of running `body` for the next query progress update. */
+ protected def timeTakenMs(body: => Unit): Long = Utils.timeTakenMs(body)._2
+
+ override protected def logName: String = s"${super.logName} $loggingId"
+}
+
+
+/** Mutable and reusable pair of byte arrays */
+class ByteArrayPair(var key: Array[Byte] = null, var value: Array[Byte] = null) {
+ def set(key: Array[Byte], value: Array[Byte]): ByteArrayPair = {
+ this.key = key
+ this.value = value
+ this
+ }
+}
+
+
+/**
+ * Configurations for optimizing RocksDB
+ *
+ * @param compactOnCommit Whether to compact RocksDB data before commit / checkpointing
+ */
+case class RocksDBConf(
+ minVersionsToRetain: Int,
+ compactOnCommit: Boolean,
+ pauseBackgroundWorkForCommit: Boolean,
+ blockSizeKB: Long,
+ blockCacheSizeMB: Long,
+ lockAcquireTimeoutMs: Long)
+
+object RocksDBConf {
+ /** Common prefix of all confs in SQLConf that affects RocksDB */
+ val ROCKSDB_CONF_NAME_PREFIX = "spark.sql.streaming.stateStore.rocksdb"
+
+ private case class ConfEntry(name: String, default: String) {
+ def fullName: String = s"$ROCKSDB_CONF_NAME_PREFIX.${name}".toLowerCase(Locale.ROOT)
+ }
+
+ // Configuration that specifies whether to compact the RocksDB data every time data is committed
+ private val COMPACT_ON_COMMIT_CONF = ConfEntry("compactOnCommit", "false")
+ private val PAUSE_BG_WORK_FOR_COMMIT_CONF = ConfEntry("pauseBackgroundWorkForCommit", "true")
+ private val BLOCK_SIZE_KB_CONF = ConfEntry("blockSizeKB", "4")
+ private val BLOCK_CACHE_SIZE_MB_CONF = ConfEntry("blockCacheSizeMB", "8")
+ private val LOCK_ACQUIRE_TIMEOUT_MS_CONF = ConfEntry("lockAcquireTimeoutMs", "60000")
+
+ def apply(storeConf: StateStoreConf): RocksDBConf = {
+ val confs = CaseInsensitiveMap[String](storeConf.confs)
+
+ def getBooleanConf(conf: ConfEntry): Boolean = {
+ Try { confs.getOrElse(conf.fullName, conf.default).toBoolean } getOrElse {
+ throw new IllegalArgumentException(s"Invalid value for '${conf.fullName}', must be boolean")
+ }
+ }
+
+ def getPositiveLongConf(conf: ConfEntry): Long = {
+ Try { confs.getOrElse(conf.fullName, conf.default).toLong } filter { _ >= 0 } getOrElse {
+ throw new IllegalArgumentException(
+ s"Invalid value for '${conf.fullName}', must be a positive integer")
+ }
+ }
+
+ RocksDBConf(
+ storeConf.minVersionsToRetain,
+ getBooleanConf(COMPACT_ON_COMMIT_CONF),
+ getBooleanConf(PAUSE_BG_WORK_FOR_COMMIT_CONF),
+ getPositiveLongConf(BLOCK_SIZE_KB_CONF),
+ getPositiveLongConf(BLOCK_CACHE_SIZE_MB_CONF),
+ getPositiveLongConf(LOCK_ACQUIRE_TIMEOUT_MS_CONF))
+ }
+
+ def apply(): RocksDBConf = apply(new StateStoreConf())
+}
+
+case class AcquiredThreadInfo(
+ threadRef: WeakReference[Thread] = new WeakReference[Thread](Thread.currentThread()),
Review comment:
No. Make `threadRef` and `tc` as public member in the next commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA removed a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865176623
**[Test build #140087 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140087/testReport)** for PR 32928 at commit [`80154b2`](https://github.com/apache/spark/commit/80154b2fdb3370b7c7b4b1b18fef074e4ea865cb).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] dongjoon-hyun commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
dongjoon-hyun commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660240992
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
Review comment:
If we want to do logging only at all `Exception`, `Utils.tryLogNonFatalError` might be better.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] dongjoon-hyun commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
dongjoon-hyun commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660235291
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
Review comment:
After we re-throw this, `loadedVersion` is used for some purpose in the upper layer? I'm wondering if this is recoverable error and `loadedVersion` is a valuable information to be used later in that case.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r658437554
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDBFileManager.scala
##########
@@ -153,6 +156,49 @@ class RocksDBFileManager(
logInfo(s"Saved checkpoint file for version $version")
}
+ /**
+ * Load all necessary files for specific checkpoint version from DFS to given local directory.
+ * If version is 0, then it will deleted all files in the directory. For other versions, it
+ * ensures that only the exact files generated during checkpointing will be present in the
+ * local directory.
+ */
+ def loadCheckpointFromDfs(version: Long, localDir: File): RocksDBCheckpointMetadata = {
Review comment:
Yep. We only need to review the latest commit for all the WIP pr related to the RocksDB state store.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865211168
Kubernetes integration test starting
URL: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder-K8s/44614/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865176623
**[Test build #140087 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140087/testReport)** for PR 32928 at commit [`80154b2`](https://github.com/apache/spark/commit/80154b2fdb3370b7c7b4b1b18fef074e4ea865cb).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865216800
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/44614/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865216800
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] dongjoon-hyun commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
dongjoon-hyun commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660244934
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
Review comment:
maybe, `RocksDB inside running` -> `RocksDB is running`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659599409
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo(s"Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion in $checkpointDir")
Review comment:
Thanks, done in f928820
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659629188
##########
File path: sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/RocksDBSuite.scala
##########
@@ -167,6 +236,26 @@ class RocksDBSuite extends SparkFunSuite {
// scalastyle:on line.size.limit
}
+ def withDB[T](
+ remoteDir: String,
+ version: Int = 0,
+ conf: RocksDBConf = RocksDBConf().copy(compactOnCommit = false, minVersionsToRetain = 100),
Review comment:
No usage for the default value, delete the default value in the next commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659546597
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
Review comment:
The options from line 59-62 should not configurable since it's mainly for binding the sync mode of RocksDB. For the tableFormatConfig, I think they can be configured in the future if user have more performance requirements.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659546708
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
Review comment:
Thanks, done in f928820
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
HeartSaVioR commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659469996
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
Review comment:
nit: checkpoin`tin`g
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/util/RocksDBLoader.scala
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.apache.spark.sql.util
Review comment:
RocksDB is only used for RocksDB state store provider, hence better to put it in same place. We may want to move this to other place like core if we replace LevelDB with RocksDB, but moving this doesn't break anything so no need to consider in advance.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
Review comment:
This also works as well regardless of where it comes. If it's removed from write batch, it should either from committed RocksDB (key is going to be removed) or uncommitted write batch (numUncommittedKeys should be increased in prior).
##########
File path: sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/RocksDBSuite.scala
##########
@@ -33,6 +33,75 @@ import org.apache.spark.util.Utils
class RocksDBSuite extends SparkFunSuite {
+ test("RocksDB: get, put, iterator, commit, load") {
+ def testOps(compactOnCommit: Boolean): Unit = {
+ val remoteDir = Utils.createTempDir().toString
+ new File(remoteDir).delete() // to make sure that the directory gets created
+
+ val conf = RocksDBConf().copy(compactOnCommit = true)
Review comment:
This should use `compactOnCommit` param, not `true`.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/util/RocksDBLoader.scala
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.apache.spark.sql.util
Review comment:
It'd be nice if we can place to the package RocksDB state store provider has/will be placed, which I guess either `org.apache.spark.sql.execution.streaming` or `org.apache.spark.sql.execution.streaming.state`.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
Review comment:
This can ensure that new key appears regardless of where it comes; so looks accurate to add 1.
##########
File path: sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/RocksDBSuite.scala
##########
@@ -167,6 +236,26 @@ class RocksDBSuite extends SparkFunSuite {
// scalastyle:on line.size.limit
}
+ def withDB[T](
+ remoteDir: String,
+ version: Int = 0,
+ conf: RocksDBConf = RocksDBConf().copy(compactOnCommit = false, minVersionsToRetain = 100),
Review comment:
Here the `conf` param is always provided - is there usage on using default value?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/util/RocksDBLoader.scala
##########
@@ -0,0 +1,61 @@
+/*
+ * 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.apache.spark.sql.util
+
+import org.rocksdb._
Review comment:
How many classes we import from this line? Let's avoid using wildcard unless the number of classes to import are quite a lot of.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
Review comment:
just wondering; where it is being used? this is only defined as val hence the question.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
Review comment:
The name is actually confusing. This made me think we are tracking committed keys vs uncommitted keys (not including committed keys), but the reality is, we are tracking the number of keys in committed RocksDB, and the number of keys in (committed + uncommitted) which will be committed.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
Review comment:
We're modifying workingDir so looks safer to close DB first before modifying the dir.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def getDBProperty(property: String): Long = {
+ db.getProperty(property).toLong
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
+ }
+ }
+
+ var dbLogLevel = InfoLogLevel.ERROR_LEVEL
+ if (log.isWarnEnabled) dbLogLevel = InfoLogLevel.WARN_LEVEL
+ if (log.isInfoEnabled) dbLogLevel = InfoLogLevel.INFO_LEVEL
+ if (log.isDebugEnabled) dbLogLevel = InfoLogLevel.DEBUG_LEVEL
+ dbOptions.setLogger(dbLogger)
+ dbOptions.setInfoLogLevel(dbLogLevel)
+ logInfo(s"Set DB native logging level to $dbLogLevel")
+ dbLogger
+ }
+
+ /** Create a temp directory inside the local root directory */
+ private def createTempDir(prefix: String): File = {
+ Utils.createDirectory(localRootDir.getAbsolutePath, prefix)
+ }
+
+ /** Attempt to delete recursively, and log the error if any */
+ private def silentDeleteRecursively(file: File, msg: String): Unit = {
+ try {
+ Utils.deleteRecursively(file)
+ } catch {
+ case e: Exception =>
+ logWarning(s"Error recursively deleting local dir $file while $msg", e)
+ }
+ }
+
+ /** Records the duration of running `body` for the next query progress update. */
+ protected def timeTakenMs(body: => Unit): Long = Utils.timeTakenMs(body)._2
+
+ override protected def logName: String = s"${super.logName} $loggingId"
+}
+
+
+/** Mutable and reusable pair of byte arrays */
+class ByteArrayPair(var key: Array[Byte] = null, var value: Array[Byte] = null) {
+ def set(key: Array[Byte], value: Array[Byte]): ByteArrayPair = {
+ this.key = key
+ this.value = value
+ this
+ }
+}
+
+
+/**
+ * Configurations for optimizing RocksDB
+ *
+ * @param compactOnCommit Whether to compact RocksDB data before commit / checkpointing
+ */
+case class RocksDBConf(
+ minVersionsToRetain: Int,
+ compactOnCommit: Boolean,
+ pauseBackgroundWorkForCommit: Boolean,
+ blockSizeKB: Long,
+ blockCacheSizeMB: Long,
+ lockAcquireTimeoutMs: Long)
+
+object RocksDBConf {
+ /** Common prefix of all confs in SQLConf that affects RocksDB */
+ val ROCKSDB_CONF_NAME_PREFIX = "spark.sql.streaming.stateStore.rocksdb"
+
+ private case class ConfEntry(name: String, default: String) {
+ def fullName: String = s"$ROCKSDB_CONF_NAME_PREFIX.${name}".toLowerCase(Locale.ROOT)
+ }
+
+ // Configuration that specifies whether to compact the RocksDB data every time data is committed
+ private val COMPACT_ON_COMMIT_CONF = ConfEntry("compactOnCommit", "false")
+ private val PAUSE_BG_WORK_FOR_COMMIT_CONF = ConfEntry("pauseBackgroundWorkForCommit", "true")
+ private val BLOCK_SIZE_KB_CONF = ConfEntry("blockSizeKB", "4")
+ private val BLOCK_CACHE_SIZE_MB_CONF = ConfEntry("blockCacheSizeMB", "8")
+ private val LOCK_ACQUIRE_TIMEOUT_MS_CONF = ConfEntry("lockAcquireTimeoutMs", "60000")
+
+ def apply(storeConf: StateStoreConf): RocksDBConf = {
+ val confs = CaseInsensitiveMap[String](storeConf.confs)
+
+ def getBooleanConf(conf: ConfEntry): Boolean = {
+ Try { confs.getOrElse(conf.fullName, conf.default).toBoolean } getOrElse {
+ throw new IllegalArgumentException(s"Invalid value for '${conf.fullName}', must be boolean")
+ }
+ }
+
+ def getPositiveLongConf(conf: ConfEntry): Long = {
+ Try { confs.getOrElse(conf.fullName, conf.default).toLong } filter { _ >= 0 } getOrElse {
+ throw new IllegalArgumentException(
+ s"Invalid value for '${conf.fullName}', must be a positive integer")
+ }
+ }
+
+ RocksDBConf(
+ storeConf.minVersionsToRetain,
+ getBooleanConf(COMPACT_ON_COMMIT_CONF),
+ getBooleanConf(PAUSE_BG_WORK_FOR_COMMIT_CONF),
+ getPositiveLongConf(BLOCK_SIZE_KB_CONF),
+ getPositiveLongConf(BLOCK_CACHE_SIZE_MB_CONF),
+ getPositiveLongConf(LOCK_ACQUIRE_TIMEOUT_MS_CONF))
+ }
+
+ def apply(): RocksDBConf = apply(new StateStoreConf())
+}
+
+case class AcquiredThreadInfo(
+ threadRef: WeakReference[Thread] = new WeakReference[Thread](Thread.currentThread()),
Review comment:
Is there any caller providing these parameters manually?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def getDBProperty(property: String): Long = {
Review comment:
unused
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r658454913
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
Review comment:
That's right, these 2 things are done together in the `getFromBatchAndDB`. Here's part of the function description:
```
This function will query both this batch and the DB and then merge
the results using the DB's merge operator (if the batch contains any
merge requests).
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660332246
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
+ }
+ }
+
+ var dbLogLevel = InfoLogLevel.ERROR_LEVEL
+ if (log.isWarnEnabled) dbLogLevel = InfoLogLevel.WARN_LEVEL
+ if (log.isInfoEnabled) dbLogLevel = InfoLogLevel.INFO_LEVEL
+ if (log.isDebugEnabled) dbLogLevel = InfoLogLevel.DEBUG_LEVEL
+ dbOptions.setLogger(dbLogger)
+ dbOptions.setInfoLogLevel(dbLogLevel)
+ logInfo(s"Set DB native logging level to $dbLogLevel")
+ dbLogger
+ }
+
+ /** Create a temp directory inside the local root directory */
+ private def createTempDir(prefix: String): File = {
+ Utils.createDirectory(localRootDir.getAbsolutePath, prefix)
+ }
+
+ /** Attempt to delete recursively, and log the error if any */
+ private def silentDeleteRecursively(file: File, msg: String): Unit = {
+ try {
+ Utils.deleteRecursively(file)
+ } catch {
+ case e: Exception =>
+ logWarning(s"Error recursively deleting local dir $file while $msg", e)
+ }
+ }
+
+ /** Records the duration of running `body` for the next query progress update. */
+ protected def timeTakenMs(body: => Unit): Long = Utils.timeTakenMs(body)._2
+
+ override protected def logName: String = s"${super.logName} $loggingId"
+}
+
+
+/** Mutable and reusable pair of byte arrays */
+class ByteArrayPair(var key: Array[Byte] = null, var value: Array[Byte] = null) {
+ def set(key: Array[Byte], value: Array[Byte]): ByteArrayPair = {
+ this.key = key
+ this.value = value
+ this
+ }
+}
+
+
+/**
+ * Configurations for optimizing RocksDB
+ *
+ * @param compactOnCommit Whether to compact RocksDB data before commit / checkpointing
+ */
+case class RocksDBConf(
+ minVersionsToRetain: Int,
+ compactOnCommit: Boolean,
+ pauseBackgroundWorkForCommit: Boolean,
+ blockSizeKB: Long,
+ blockCacheSizeMB: Long,
+ lockAcquireTimeoutMs: Long)
+
+object RocksDBConf {
+ /** Common prefix of all confs in SQLConf that affects RocksDB */
+ val ROCKSDB_CONF_NAME_PREFIX = "spark.sql.streaming.stateStore.rocksdb"
+
+ private case class ConfEntry(name: String, default: String) {
+ def fullName: String = s"$ROCKSDB_CONF_NAME_PREFIX.${name}".toLowerCase(Locale.ROOT)
+ }
+
+ // Configuration that specifies whether to compact the RocksDB data every time data is committed
+ private val COMPACT_ON_COMMIT_CONF = ConfEntry("compactOnCommit", "false")
+ private val PAUSE_BG_WORK_FOR_COMMIT_CONF = ConfEntry("pauseBackgroundWorkForCommit", "true")
+ private val BLOCK_SIZE_KB_CONF = ConfEntry("blockSizeKB", "4")
+ private val BLOCK_CACHE_SIZE_MB_CONF = ConfEntry("blockCacheSizeMB", "8")
+ private val LOCK_ACQUIRE_TIMEOUT_MS_CONF = ConfEntry("lockAcquireTimeoutMs", "60000")
Review comment:
Yea, I planned to document all the config for RocksDB in the user guide. If we have the configurable requirement in the future, people can easily be referenced.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660296038
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
Review comment:
I see. Makes sense.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-864464770
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder-K8s/44553/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660319242
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
Review comment:
Thanks, done in the next commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659627745
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
Review comment:
Thanks! Done in next commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659628751
##########
File path: sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/RocksDBSuite.scala
##########
@@ -33,6 +33,75 @@ import org.apache.spark.util.Utils
class RocksDBSuite extends SparkFunSuite {
+ test("RocksDB: get, put, iterator, commit, load") {
+ def testOps(compactOnCommit: Boolean): Unit = {
+ val remoteDir = Utils.createTempDir().toString
+ new File(remoteDir).delete() // to make sure that the directory gets created
+
+ val conf = RocksDBConf().copy(compactOnCommit = true)
Review comment:
Nice catch, done in the next commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865286343
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/140087/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] dongjoon-hyun commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
dongjoon-hyun commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660235291
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
Review comment:
After we re-throw this, `loadedVersion` is used for some purpose in the upper layer? I'm wondering if this is recoverable error and `loadedVersion` is a valuable information to be used later in that case.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
Review comment:
~After we re-throw this, `loadedVersion` is used for some purpose in the upper layer? I'm wondering if this is recoverable error and `loadedVersion` is a valuable information to be used later in that case.~ Never mind.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
Review comment:
If you don't mind, shall we use a full name instead of `Bg`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
Review comment:
If we want to do logging only at all `Exception`, `Utils.tryLogNonFatalError` might be better.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
Review comment:
nit. Could you add `@GuardedBy("acquireLock")`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
Review comment:
maybe, `RocksDB inside running` -> `RocksDB is running`?
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
Review comment:
maybe, `that the RocksDB inside running` -> `that the RocksDB is running`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865271451
**[Test build #140087 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140087/testReport)** for PR 32928 at commit [`80154b2`](https://github.com/apache/spark/commit/80154b2fdb3370b7c7b4b1b18fef074e4ea865cb).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `class RocksDB(`
* `class ByteArrayPair(var key: Array[Byte] = null, var value: Array[Byte] = null) `
* `case class RocksDBConf(`
* `case class AcquiredThreadInfo(`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] AmplabJenkins removed a comment on pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
AmplabJenkins removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-870964481
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/140374/
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660301446
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
+ }
+ }
+
+ var dbLogLevel = InfoLogLevel.ERROR_LEVEL
+ if (log.isWarnEnabled) dbLogLevel = InfoLogLevel.WARN_LEVEL
+ if (log.isInfoEnabled) dbLogLevel = InfoLogLevel.INFO_LEVEL
+ if (log.isDebugEnabled) dbLogLevel = InfoLogLevel.DEBUG_LEVEL
+ dbOptions.setLogger(dbLogger)
+ dbOptions.setInfoLogLevel(dbLogLevel)
+ logInfo(s"Set DB native logging level to $dbLogLevel")
+ dbLogger
+ }
+
+ /** Create a temp directory inside the local root directory */
+ private def createTempDir(prefix: String): File = {
+ Utils.createDirectory(localRootDir.getAbsolutePath, prefix)
+ }
+
+ /** Attempt to delete recursively, and log the error if any */
+ private def silentDeleteRecursively(file: File, msg: String): Unit = {
+ try {
+ Utils.deleteRecursively(file)
+ } catch {
+ case e: Exception =>
+ logWarning(s"Error recursively deleting local dir $file while $msg", e)
+ }
+ }
+
+ /** Records the duration of running `body` for the next query progress update. */
+ protected def timeTakenMs(body: => Unit): Long = Utils.timeTakenMs(body)._2
+
+ override protected def logName: String = s"${super.logName} $loggingId"
+}
+
+
+/** Mutable and reusable pair of byte arrays */
+class ByteArrayPair(var key: Array[Byte] = null, var value: Array[Byte] = null) {
+ def set(key: Array[Byte], value: Array[Byte]): ByteArrayPair = {
+ this.key = key
+ this.value = value
+ this
+ }
+}
+
+
+/**
+ * Configurations for optimizing RocksDB
+ *
+ * @param compactOnCommit Whether to compact RocksDB data before commit / checkpointing
+ */
+case class RocksDBConf(
+ minVersionsToRetain: Int,
+ compactOnCommit: Boolean,
+ pauseBackgroundWorkForCommit: Boolean,
+ blockSizeKB: Long,
+ blockCacheSizeMB: Long,
+ lockAcquireTimeoutMs: Long)
+
+object RocksDBConf {
+ /** Common prefix of all confs in SQLConf that affects RocksDB */
+ val ROCKSDB_CONF_NAME_PREFIX = "spark.sql.streaming.stateStore.rocksdb"
+
+ private case class ConfEntry(name: String, default: String) {
+ def fullName: String = s"$ROCKSDB_CONF_NAME_PREFIX.${name}".toLowerCase(Locale.ROOT)
+ }
+
+ // Configuration that specifies whether to compact the RocksDB data every time data is committed
+ private val COMPACT_ON_COMMIT_CONF = ConfEntry("compactOnCommit", "false")
+ private val PAUSE_BG_WORK_FOR_COMMIT_CONF = ConfEntry("pauseBackgroundWorkForCommit", "true")
+ private val BLOCK_SIZE_KB_CONF = ConfEntry("blockSizeKB", "4")
+ private val BLOCK_CACHE_SIZE_MB_CONF = ConfEntry("blockCacheSizeMB", "8")
+ private val LOCK_ACQUIRE_TIMEOUT_MS_CONF = ConfEntry("lockAcquireTimeoutMs", "60000")
Review comment:
Note that we should document these configs at the end.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660318575
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
Review comment:
Thanks for the advice. But since NonFatal doesn't include `InterruptedException` which is also an Exception, maybe we'd better not change to use `Utils.tryLogNonFatalError` here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660295530
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
Review comment:
why it is for "all committed versions"? In `load`, we just overwrite it `numCommittedKeys = metadata.numKeys`. So looks like it is only for the loaded version.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] HeartSaVioR edited a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
HeartSaVioR edited a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865653998
I'd rather say the version bump would be a no-go till we figure out either it is backward compatible, or quite easy way to migrate the old one to the new one. This applies to the changes on LevelDB to RocksDB as well (SPARK-35782).
Given the importance, I'd like to see the efforts in different JIRA and be orthogonal efforts with RocksDB state store provider.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659627986
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
Review comment:
It's mainly used in the UT.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660848165
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
Review comment:
looks good to me.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-862190762
**[Test build #139867 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/139867/testReport)** for PR 32928 at commit [`bbb534e`](https://github.com/apache/spark/commit/bbb534e841d4c32c821fc0ae85ceb5b077e0dad0).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660335182
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
Review comment:
Changed to `pause` in 641a91e
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865150190
@dongjoon-hyun Thanks for the information!
```
Please fix Scala 2.13 build, @xuanyuanking .
```
Sure
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-870192493
Thanks @HeartSaVioR. I will take another look.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660314758
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
Review comment:
"pauseBackground" might be a little bit longer, how about change it to a simple "pause"? Actually this is only for the internal temp map key, we'll have a detailed metrics name in the later PR.
```
val CUSTOM_METRIC_PAUSE_TIME = StateStoreCustomTimingMetric(
"rocksdbCommitPauseLatency", "RocksDB: commit - pause background time")
```
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
Review comment:
Thanks for the advice. But since NonFatal doesn't include `InterruptedException` which is also an Exception, maybe we'd better not change to use `Utils.tryLogNonFatalError` here.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
Review comment:
Thanks, done in the next commit.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
Review comment:
Thanks, changed in the next commit.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
Review comment:
It's also used in the `commit` operation, which will be introduced in the next commit: https://github.com/apache/spark/pull/32933/files#diff-4663b8349511dc040c3d5204bb6868064002d0b45aadaf1f1795a683897a5c7dR224
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
Review comment:
Thanks, done in the next commit.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
Review comment:
Thanks, done in the next commit.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
+ }
+ }
+
+ var dbLogLevel = InfoLogLevel.ERROR_LEVEL
+ if (log.isWarnEnabled) dbLogLevel = InfoLogLevel.WARN_LEVEL
+ if (log.isInfoEnabled) dbLogLevel = InfoLogLevel.INFO_LEVEL
+ if (log.isDebugEnabled) dbLogLevel = InfoLogLevel.DEBUG_LEVEL
+ dbOptions.setLogger(dbLogger)
+ dbOptions.setInfoLogLevel(dbLogLevel)
+ logInfo(s"Set DB native logging level to $dbLogLevel")
Review comment:
Sure, done in the next commit.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
+ release()
+ }
+ }
+
+ /**
+ * Drop uncommitted changes, and roll back to previous version.
+ */
+ def rollback(): Unit = {
+ writeBatch.clear()
+ numUncommittedKeys = numCommittedKeys
+ release()
+ logInfo(s"Rolled back to $loadedVersion")
+ }
+
+ /** Release all resources */
+ def close(): Unit = {
+ try {
+ closeDB()
+
+ // Release all resources related to native RockDB objects
+ writeBatch.clear()
+ writeBatch.close()
+ readOptions.close()
+ writeOptions.close()
+ flushOptions.close()
+ dbOptions.close()
+ dbLogger.close()
+ silentDeleteRecursively(localRootDir, "stopping")
+ } catch {
+ case e: Exception =>
+ logWarning("Error closing RocksDB", e)
+ }
+ }
+
+ /** Get the latest version available in the DFS */
+ def getLatestVersion(): Long = fileManager.getLatestVersion()
+
+ private def acquire(): Unit = acquireLock.synchronized {
+ val newAcquiredThreadInfo = AcquiredThreadInfo()
+ val waitStartTime = System.currentTimeMillis
+ def timeWaitedMs = System.currentTimeMillis - waitStartTime
+ def isAcquiredByDifferentThread = acquiredThreadInfo != null &&
+ acquiredThreadInfo.threadRef.get.isDefined &&
+ newAcquiredThreadInfo.threadRef.get.get.getId != acquiredThreadInfo.threadRef.get.get.getId
+
+ while (isAcquiredByDifferentThread && timeWaitedMs < conf.lockAcquireTimeoutMs) {
+ acquireLock.wait(10)
+ }
+ if (isAcquiredByDifferentThread) {
+ val stackTraceOutput = acquiredThreadInfo.threadRef.get.get.getStackTrace.mkString("\n")
+ val msg = s"RocksDB instance could not be acquired by $newAcquiredThreadInfo as it " +
+ s"was not released by $acquiredThreadInfo after $timeWaitedMs ms.\n" +
+ s"Thread holding the lock has trace: $stackTraceOutput"
+ logError(msg)
+ throw new IllegalStateException(s"$loggingId: $msg")
+ } else {
+ acquiredThreadInfo = newAcquiredThreadInfo
+ // Add a listener to always release the lock when the task (if active) completes
+ Option(TaskContext.get).foreach(_.addTaskCompletionListener[Unit] { _ => this.release() })
+ logInfo(s"RocksDB instance was acquired by $acquiredThreadInfo")
+ }
+ }
+
+ private def release(): Unit = acquireLock.synchronized {
+ acquiredThreadInfo = null
+ acquireLock.notifyAll()
+ }
+
+ private def openDB(): Unit = {
+ assert(db == null)
+ db = NativeRocksDB.open(dbOptions, workingDir.toString)
+ logInfo(s"Opened DB with conf ${conf}")
+ }
+
+ private def closeDB(): Unit = {
+ if (db != null) {
+ db.close()
+ db = null
+ }
+ }
+
+ /** Create a native RocksDB logger that forwards native logs to log4j with correct log levels. */
+ private def createLogger(): Logger = {
+ val dbLogger = new Logger(dbOptions) {
+ override def log(infoLogLevel: InfoLogLevel, logMsg: String) = {
+ // Map DB log level to log4j levels
+ // Warn is mapped to info because RocksDB warn is too verbose
+ // (e.g. dumps non-warning stuff like stats)
+ val loggingFunc: ( => String) => Unit = infoLogLevel match {
+ case InfoLogLevel.FATAL_LEVEL | InfoLogLevel.ERROR_LEVEL => logError(_)
+ case InfoLogLevel.WARN_LEVEL | InfoLogLevel.INFO_LEVEL => logInfo(_)
+ case InfoLogLevel.DEBUG_LEVEL => logDebug(_)
+ case _ => logTrace(_)
+ }
+ loggingFunc(s"[Native-${infoLogLevel.getValue}] $logMsg")
+ }
+ }
+
+ var dbLogLevel = InfoLogLevel.ERROR_LEVEL
+ if (log.isWarnEnabled) dbLogLevel = InfoLogLevel.WARN_LEVEL
+ if (log.isInfoEnabled) dbLogLevel = InfoLogLevel.INFO_LEVEL
+ if (log.isDebugEnabled) dbLogLevel = InfoLogLevel.DEBUG_LEVEL
+ dbOptions.setLogger(dbLogger)
+ dbOptions.setInfoLogLevel(dbLogLevel)
+ logInfo(s"Set DB native logging level to $dbLogLevel")
+ dbLogger
+ }
+
+ /** Create a temp directory inside the local root directory */
+ private def createTempDir(prefix: String): File = {
+ Utils.createDirectory(localRootDir.getAbsolutePath, prefix)
+ }
+
+ /** Attempt to delete recursively, and log the error if any */
+ private def silentDeleteRecursively(file: File, msg: String): Unit = {
+ try {
+ Utils.deleteRecursively(file)
+ } catch {
+ case e: Exception =>
+ logWarning(s"Error recursively deleting local dir $file while $msg", e)
+ }
+ }
+
+ /** Records the duration of running `body` for the next query progress update. */
+ protected def timeTakenMs(body: => Unit): Long = Utils.timeTakenMs(body)._2
+
+ override protected def logName: String = s"${super.logName} $loggingId"
+}
+
+
+/** Mutable and reusable pair of byte arrays */
+class ByteArrayPair(var key: Array[Byte] = null, var value: Array[Byte] = null) {
+ def set(key: Array[Byte], value: Array[Byte]): ByteArrayPair = {
+ this.key = key
+ this.value = value
+ this
+ }
+}
+
+
+/**
+ * Configurations for optimizing RocksDB
+ *
+ * @param compactOnCommit Whether to compact RocksDB data before commit / checkpointing
+ */
+case class RocksDBConf(
+ minVersionsToRetain: Int,
+ compactOnCommit: Boolean,
+ pauseBackgroundWorkForCommit: Boolean,
+ blockSizeKB: Long,
+ blockCacheSizeMB: Long,
+ lockAcquireTimeoutMs: Long)
+
+object RocksDBConf {
+ /** Common prefix of all confs in SQLConf that affects RocksDB */
+ val ROCKSDB_CONF_NAME_PREFIX = "spark.sql.streaming.stateStore.rocksdb"
+
+ private case class ConfEntry(name: String, default: String) {
+ def fullName: String = s"$ROCKSDB_CONF_NAME_PREFIX.${name}".toLowerCase(Locale.ROOT)
+ }
+
+ // Configuration that specifies whether to compact the RocksDB data every time data is committed
+ private val COMPACT_ON_COMMIT_CONF = ConfEntry("compactOnCommit", "false")
+ private val PAUSE_BG_WORK_FOR_COMMIT_CONF = ConfEntry("pauseBackgroundWorkForCommit", "true")
+ private val BLOCK_SIZE_KB_CONF = ConfEntry("blockSizeKB", "4")
+ private val BLOCK_CACHE_SIZE_MB_CONF = ConfEntry("blockCacheSizeMB", "8")
+ private val LOCK_ACQUIRE_TIMEOUT_MS_CONF = ConfEntry("lockAcquireTimeoutMs", "60000")
Review comment:
Yea, I planned to document all the config for RocksDB in the user guide. If we have the configurable requirement in the future, people can easily be referenced.
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
Review comment:
Yea. It's might hard to explain all the meaning in the name. So I prefer to have a long comment here :joy:
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
Review comment:
Changed to `pause` in 641a91e
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] SparkQA removed a comment on pull request #32928: [WIP][SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
SparkQA removed a comment on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-865176623
**[Test build #140087 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/140087/testReport)** for PR 32928 at commit [`80154b2`](https://github.com/apache/spark/commit/80154b2fdb3370b7c7b4b1b18fef074e4ea865cb).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659599639
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,455 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("manager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ workingDir.mkdirs()
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
Review comment:
Make sense, I delete the closeDB in `openDB` in f928820
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660298585
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
+ "checkpoint" -> checkpointTimeMs,
+ "fileSync" -> fileSyncTimeMs
+ )
+ loadedVersion
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded version
+ throw t
+ } finally {
+ db.continueBackgroundWork()
+ silentDeleteRecursively(checkpointDir, s"committing $newVersion")
Review comment:
`finished committing $newVersion`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r659641813
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
Review comment:
Agree, add more comment in the next commit.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660815271
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
Review comment:
+1 for the `numKeysOnLoadedVersion - numKeysOnWritingVersion`. Reviewed the new name in all the places (includes the further PRs) and it has a clear meaning. Thanks for the advice!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660314758
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,451 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpointing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf,
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ // number of keys in all committed versions before
+ @volatile private var numCommittedKeys = 0L
+ // number of keys which will be committed in the next version
+ @volatile private var numUncommittedKeys = 0L
+ @volatile private var acquiredThreadInfo: AcquiredThreadInfo = _
+
+ /**
+ * Load the given version of data in a native RocksDB instance.
+ * Note that this will copy all the necessary file from DFS to local disk as needed,
+ * and possibly restart the native RocksDB instance.
+ */
+ def load(version: Long): RocksDB = {
+ assert(version >= 0)
+ acquire()
+ logInfo(s"Loading $version")
+ try {
+ if (loadedVersion != version) {
+ closeDB()
+ val metadata = fileManager.loadCheckpointFromDfs(version, workingDir)
+ openDB()
+ numUncommittedKeys = metadata.numKeys
+ numCommittedKeys = metadata.numKeys
+ loadedVersion = version
+ }
+ writeBatch.clear()
+ logInfo(s"Loaded $version")
+ } catch {
+ case t: Throwable =>
+ loadedVersion = -1 // invalidate loaded data
+ throw t
+ }
+ this
+ }
+
+ /**
+ * Get the value for the given key if present, or null.
+ * @note This will return the last written value even if it was uncommitted.
+ */
+ def get(key: Array[Byte]): Array[Byte] = {
+ writeBatch.getFromBatchAndDB(db, readOptions, key)
+ }
+
+ /**
+ * Put the given value for the given key and return the last written value.
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def put(key: Array[Byte], value: Array[Byte]): Array[Byte] = {
+ val oldValue = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ writeBatch.put(key, value)
+ if (oldValue == null) {
+ numUncommittedKeys += 1
+ }
+ oldValue
+ }
+
+ /**
+ * Remove the key if present, and return the previous value if it was present (null otherwise).
+ * @note This update is not committed to disk until commit() is called.
+ */
+ def remove(key: Array[Byte]): Array[Byte] = {
+ val value = writeBatch.getFromBatchAndDB(db, readOptions, key)
+ if (value != null) {
+ writeBatch.remove(key)
+ numUncommittedKeys -= 1
+ }
+ value
+ }
+
+ /**
+ * Get an iterator of all committed and uncommitted key-value pairs.
+ */
+ def iterator(): Iterator[ByteArrayPair] = {
+ val iter = writeBatch.newIteratorWithBase(db.newIterator())
+ logInfo(s"Getting iterator from version $loadedVersion")
+ iter.seekToFirst()
+
+ // Attempt to close this iterator if there is a task failure, or a task interruption.
+ // This is a hack because it assumes that the RocksDB inside running in a task.
+ Option(TaskContext.get()).foreach { tc =>
+ tc.addTaskCompletionListener[Unit] { _ => iter.close() }
+ }
+
+ new NextIterator[ByteArrayPair] {
+ override protected def getNext(): ByteArrayPair = {
+ if (iter.isValid) {
+ byteArrayPair.set(iter.key, iter.value)
+ iter.next()
+ byteArrayPair
+ } else {
+ finished = true
+ iter.close()
+ null
+ }
+ }
+ override protected def close(): Unit = { iter.close() }
+ }
+ }
+
+ /**
+ * Commit all the updates made as a version to DFS. The steps it needs to do to commits are:
+ * - Write all the updates to the native RocksDB
+ * - Flush all changes to disk
+ * - Create a RocksDB checkpoint in a new local dir
+ * - Sync the checkpoint dir files to DFS
+ */
+ def commit(): Long = {
+ val newVersion = loadedVersion + 1
+ val checkpointDir = createTempDir("checkpoint")
+ try {
+ // Make sure the directory does not exist. Native RocksDB fails if the directory to
+ // checkpoint exists.
+ Utils.deleteRecursively(checkpointDir)
+
+ logInfo(s"Writing updates for $newVersion")
+ val writeTimeMs = timeTakenMs { db.write(writeOptions, writeBatch) }
+
+ logInfo(s"Flushing updates for $newVersion")
+ val flushTimeMs = timeTakenMs { db.flush(flushOptions) }
+
+ val compactTimeMs = if (conf.compactOnCommit) {
+ logInfo("Compacting")
+ timeTakenMs { db.compactRange() }
+ } else 0
+ logInfo("Pausing background work")
+
+ val pauseTimeMs = timeTakenMs {
+ db.pauseBackgroundWork() // To avoid files being changed while committing
+ }
+
+ logInfo(s"Creating checkpoint for $newVersion in $checkpointDir")
+ val checkpointTimeMs = timeTakenMs {
+ val cp = Checkpoint.create(db)
+ cp.createCheckpoint(checkpointDir.toString)
+ }
+
+ logInfo(s"Syncing checkpoint for $newVersion to DFS")
+ val fileSyncTimeMs = timeTakenMs {
+ fileManager.saveCheckpointToDfs(checkpointDir, newVersion, numUncommittedKeys)
+ }
+ numCommittedKeys = numUncommittedKeys
+ loadedVersion = newVersion
+ commitLatencyMs ++= Map(
+ "writeBatch" -> writeTimeMs,
+ "flush" -> flushTimeMs,
+ "compact" -> compactTimeMs,
+ "pauseBg" -> pauseTimeMs,
Review comment:
"pauseBackground" might be a little bit longer, how about change it to a simple "pause"? Actually this is only for the internal temp map key, we'll have a detailed metrics name in the later PR.
```
val CUSTOM_METRIC_PAUSE_TIME = StateStoreCustomTimingMetric(
"rocksdbCommitPauseLatency", "RocksDB: commit - pause background time")
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] xuanyuanking commented on a change in pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
xuanyuanking commented on a change in pull request #32928:
URL: https://github.com/apache/spark/pull/32928#discussion_r660334977
##########
File path: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/state/RocksDB.scala
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.apache.spark.sql.execution.streaming.state
+
+import java.io.File
+import java.util.Locale
+
+import scala.collection.{mutable, Map}
+import scala.ref.WeakReference
+import scala.util.Try
+
+import org.apache.hadoop.conf.Configuration
+import org.rocksdb.{RocksDB => NativeRocksDB, _}
+
+import org.apache.spark.TaskContext
+import org.apache.spark.internal.Logging
+import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
+import org.apache.spark.sql.util.RocksDBLoader
+import org.apache.spark.util.{NextIterator, Utils}
+
+/**
+ * Class representing a RocksDB instance that checkpoints version of data to DFS.
+ * After a set of updates, a new version can be committed by calling `commit()`.
+ * Any past version can be loaded by calling `load(version)`.
+ *
+ * @note This class is not thread-safe, so use it only from one thread.
+ * @see [[RocksDBFileManager]] to see how the files are laid out in local disk and DFS.
+ * @param dfsRootDir Remote directory where checkpoints are going to be written
+ * @param conf Configuration for RocksDB
+ * @param localRootDir Root directory in local disk that is used to working and checkpoing dirs
+ * @param hadoopConf Hadoop configuration for talking to the remote file system
+ * @param loggingId Id that will be prepended in logs for isolating concurrent RocksDBs
+ */
+class RocksDB(
+ dfsRootDir: String,
+ val conf: RocksDBConf = RocksDBConf(),
+ localRootDir: File = Utils.createTempDir(),
+ hadoopConf: Configuration = new Configuration,
+ loggingId: String = "") extends Logging {
+
+ RocksDBLoader.loadLibrary()
+
+ // Java wrapper objects linking to native RocksDB objects
+ private val readOptions = new ReadOptions() // used for gets
+ private val writeOptions = new WriteOptions().setSync(true) // wait for batched write to complete
+ private val flushOptions = new FlushOptions().setWaitForFlush(true) // wait for flush to complete
+ private val writeBatch = new WriteBatchWithIndex(true) // overwrite multiple updates to a key
+
+ private val bloomFilter = new BloomFilter()
+ private val tableFormatConfig = new BlockBasedTableConfig()
+ tableFormatConfig.setBlockSize(conf.blockSizeKB * 1024)
+ tableFormatConfig.setBlockCache(new LRUCache(conf.blockCacheSizeMB * 1024 * 1024))
+ tableFormatConfig.setFilterPolicy(bloomFilter)
+
+ private val dbOptions = new Options() // options to open the RocksDB
+ dbOptions.setCreateIfMissing(true)
+ dbOptions.setTableFormatConfig(tableFormatConfig)
+ private val dbLogger = createLogger() // for forwarding RocksDB native logs to log4j
+ dbOptions.setStatistics(new Statistics())
+
+ private val workingDir = createTempDir("workingDir")
+ private val fileManager = new RocksDBFileManager(
+ dfsRootDir, createTempDir("fileManager"), hadoopConf, loggingId = loggingId)
+ private val byteArrayPair = new ByteArrayPair()
+ private val commitLatencyMs = new mutable.HashMap[String, Long]()
+ private val acquireLock = new Object
+
+ @volatile private var db: NativeRocksDB = _
+ @volatile private var loadedVersion = -1L // -1 = nothing valid is loaded
+ @volatile private var numCommittedKeys = 0L
+ @volatile private var numUncommittedKeys = 0L
Review comment:
Yea. It's might hard to explain all the meaning in the name. So I prefer to have a long comment here :joy:
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] [spark] viirya commented on pull request #32928: [SPARK-35784][SS] Implementation for RocksDB instance
Posted by GitBox <gi...@apache.org>.
viirya commented on pull request #32928:
URL: https://github.com/apache/spark/pull/32928#issuecomment-871015203
Thank you @dongjoon-hyun.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org