You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by tdas <gi...@git.apache.org> on 2018/04/11 23:00:33 UTC

[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

GitHub user tdas opened a pull request:

    https://github.com/apache/spark/pull/21048

    [SPARK-23966][SS] Refactoring all checkpoint file writing logic in a common CheckpointFileManager interface

    ## What changes were proposed in this pull request?
    
    Checkpoint files (offset log files, state store files) in Structured Streaming must be written atomically such that no partial files are generated (would break fault-tolerance guarantees). Currently, there are 3 locations which try to do this individually, and in some cases, incorrectly.
    
    1. HDFSOffsetMetadataLog - This uses a FileManager interface to use any implementation of `FileSystem` or `FileContext` APIs. It preferably loads `FileContext` implementation as FileContext of HDFS has atomic renames.
    1. HDFSBackedStateStore (aka in-memory state store)
      - Writing a version.delta file - This uses FileSystem APIs only to perform a rename. This is incorrect as rename is not atomic in HDFS FileSystem implementation.
      - Writing a snapshot file - Same as above.
    
    #### Current problems:
    1. State Store behavior is incorrect - 
    1. Inflexible - Some file systems provide mechanisms other than write-to-temp-file-and-rename for writing atomically and more efficiently. For example, with S3 you can write directly to the final file and it will be made visible only when the entire file is written and closed correctly. Any failure can be made to terminate the writing without making any partial files visible in S3. The current code does not abstract out this mechanism enough that it can be customized. 
    
    #### Solution:
    
    1. Introduce a common interface that all 3 cases above can use to write checkpoint files atomically. 
    2. This interface must provide the necessary interfaces that allow customization of the write-and-rename mechanism.
    
    This PR does that by introducing the interface `CheckpointFileManager` and modifying `HDFSMetadataLog` and `HDFSBackedStateStore` to use the interface. Similar to earlier `FileManager`, there are implementations based on `FileSystem` and `FileContext` APIs, and the latter implementation is preferred to make it work correctly with HDFS.
    
    The key method this interface has is `createAtomic(path, overwrite)` which returns a `CancellableFSDataOutputStream` that has the method `cancel()`. All users of this method need to either call `close()` to successfully write the file, or `cancel()` in case of an error.
    
    
    ## How was this patch tested?
    New tests in `CheckpointFileManagerSuite` and slightly modified existing tests.


You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/tdas/spark SPARK-23966

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/spark/pull/21048.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #21048
    
----
commit df7b339d73097b8501fe0937f770b8b2ded1b63e
Author: Tathagata Das <ta...@...>
Date:   2018-04-11T04:21:14Z

    CheckpointFileManager

----


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r217407633
  
    --- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala ---
    @@ -930,6 +930,13 @@ object SQLConf {
           .intConf
           .createWithDefault(100)
     
    +  val STREAMING_CHECKPOINT_FILE_MANAGER_CLASS =
    +    buildConf("spark.sql.streaming.checkpointFileManagerClass")
    +      .doc("The class used to write checkpoint files atomically. This class must be a subclass " +
    +        "of the interface CheckpointFileManager.")
    +      .internal()
    +      .stringConf
    --- End diff --
    
    `createOptional`? cc @zsxwing @tdas 


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/testing-k8s-prb-make-spark-distribution/2229/
    Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181480351
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,347 @@
    +/*
    + * 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
    +
    +import java.io.{FileNotFoundException, IOException, OutputStream}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def createTempFile(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.createTempFile(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        try {
    +          fm.renameTempFile(tempPath, finalPath, overwriteIfPossible)
    +        } catch {
    +          case fe: FileAlreadyExistsException =>
    +            logWarning(
    +              s"Failed to rename temp file $tempPath to $finalPath because file exists", fe)
    +            if (!overwriteIfPossible) throw fe
    +        }
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def createTempFile(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path,
    +      overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    +  }
    +
    +  override def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit = {
    +    if (!overwriteIfPossible && fs.exists(dstPath)) {
    +      throw new FileAlreadyExistsException(
    +        s"Failed to rename $srcPath to $dstPath as destination already exists")
    +    }
    +
    +    if (!fs.rename(srcPath, dstPath)) {
    +      // If overwriteIfPossible = false, then we want to find out why the rename failed and
    +      // try to throw the right error.
    +      if (fs.exists(dstPath)) {
    +        // Some implementations of FileSystem may only return false instead of throwing
    +        // FileAlreadyExistsException. In that case, explicitly throw the error the error
    +        // if overwriteIfPossible = false. Note that this is definitely not atomic.
    +        // This is only a best-effort attempt to identify the situation when rename returned
    +        // false.
    +        if (!overwriteIfPossible) {
    +          throw new FileAlreadyExistsException(s"$dstPath already exists")
    +        }
    +      } else {
    +        val msg = s"Failed to rename temp file $srcPath to $dstPath as rename returned false"
    +        logWarning(msg)
    +        throw new IOException(msg)
    +      }
    +    }
    +  }
    +
    +  override def delete(path: Path): Unit = {
    +    try {
    +      fs.delete(path, true)
    +    } catch {
    +      case e: FileNotFoundException =>
    +        logInfo(s"Failed to delete $path as it does not exist")
    --- End diff --
    
    Not really. This is just precautionary, as I really havent seen all the code of FileSystem implementations. Doesn't add any overhead by adding this.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89287/
    Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by steveloughran <gi...@git.apache.org>.
Github user steveloughran commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181672758
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,347 @@
    +/*
    + * 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
    +
    +import java.io.{FileNotFoundException, IOException, OutputStream}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def createTempFile(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.createTempFile(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        try {
    +          fm.renameTempFile(tempPath, finalPath, overwriteIfPossible)
    +        } catch {
    +          case fe: FileAlreadyExistsException =>
    +            logWarning(
    +              s"Failed to rename temp file $tempPath to $finalPath because file exists", fe)
    +            if (!overwriteIfPossible) throw fe
    +        }
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def createTempFile(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path,
    +      overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    --- End diff --
    
    yeah, tough call. Having looked through much of the spark/hive/ etc code, they to often do that exists() before delete, getFilestatus, ... which is why tag it as deprecated: to make clear that often the workflow is inefficient on non-HDFS, non-Posix stores (Where it's fine)


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181153863
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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
    +
    +import java.io.{FileSystem => _, _}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.commons.io.IOUtils
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def create(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def rename(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.create(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    --- End diff --
    
    I was thinking of having it as logInfo, so that we can debug stuff if the renaming goes wrong in some way. 


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181267497
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,347 @@
    +/*
    + * 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
    +
    +import java.io.{FileNotFoundException, IOException, OutputStream}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def createTempFile(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.createTempFile(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        try {
    +          fm.renameTempFile(tempPath, finalPath, overwriteIfPossible)
    +        } catch {
    +          case fe: FileAlreadyExistsException =>
    +            logWarning(
    +              s"Failed to rename temp file $tempPath to $finalPath because file exists", fe)
    +            if (!overwriteIfPossible) throw fe
    +        }
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def createTempFile(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path,
    +      overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    +  }
    +
    +  override def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit = {
    +    if (!overwriteIfPossible && fs.exists(dstPath)) {
    +      throw new FileAlreadyExistsException(
    +        s"Failed to rename $srcPath to $dstPath as destination already exists")
    +    }
    +
    +    if (!fs.rename(srcPath, dstPath)) {
    +      // If overwriteIfPossible = false, then we want to find out why the rename failed and
    +      // try to throw the right error.
    --- End diff --
    
    Fix this comment.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181487709
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManagerSuite.scala ---
    @@ -0,0 +1,192 @@
    +/*
    + * 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
    +
    +import java.io._
    +import java.net.URI
    +
    +import scala.util.Random
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +
    +import org.apache.spark.SparkFunSuite
    +import org.apache.spark.sql.catalyst.util.quietly
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.test.SharedSparkSession
    +import org.apache.spark.util.Utils
    +
    +abstract class CheckpointFileManagerTests extends SparkFunSuite {
    +
    +  def createManager(path: Path): CheckpointFileManager
    +
    +  test("mkdirs, list, createAtomic, open, delete") {
    +    withTempPath { p =>
    +      val basePath = new Path(p.getAbsolutePath)
    +      val fm = createManager(basePath)
    +      // Mkdirs
    +      val dir = new Path(s"$basePath/dir/subdir/subsubdir")
    +      assert(!fm.exists(dir))
    +      fm.mkdirs(dir)
    +      assert(fm.exists(dir))
    +      fm.mkdirs(dir)
    --- End diff --
    
    This is a test. I think it is fine. 


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89227/
    Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89232/
    Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r180940932
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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
    +
    +import java.io.{FileSystem => _, _}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.commons.io.IOUtils
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def create(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def rename(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.create(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        super.close()
    +        fm.rename(tempPath, finalPath, overwriteIfPossible)
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  fs.setVerifyChecksum(false)
    +  fs.setWriteChecksum(false)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def create(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    +  }
    +
    +  override def rename(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit = {
    +    if (!overwriteIfPossible && fs.exists(dstPath)) {
    +      throw new FileAlreadyExistsException(
    +        s"Failed to rename $srcPath to $dstPath as destination already exists")
    +    }
    +
    +    try {
    +      if (!fs.rename(srcPath, dstPath) && !overwriteIfPossible) {
    --- End diff --
    
    Well, they should not. This is specifically designed for one purpose. 
    Also, generally in all implementations, rename fails if you are doing something non-sensical like rename a file to a path where a directory already exists.
    
    Essentially, I want to keep this code absolutely minimal such that its easy to reason about and has minimal latency. Each check of whether its file or not will add to the latency. Most implementations will do those checks anyway. That's why there were patches in the past that removed unnecessary checks (e.g. https://github.com/apache/spark/commit/e24f21b5f8365ed25346e986748b393e0b4be25c). 


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    @steveloughran Thanks for your comments :)


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89357 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89357/testReport)** for PR 21048 at commit [`c5b0c98`](https://github.com/apache/spark/commit/c5b0c98257e39d6af2dd8f702b8cbc9f9e6fabe9).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89310 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89310/testReport)** for PR 21048 at commit [`ef05009`](https://github.com/apache/spark/commit/ef05009e491d1ffdca2a37ba0441ea8507756e3d).


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89227 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89227/testReport)** for PR 21048 at commit [`f9965f1`](https://github.com/apache/spark/commit/f9965f1cecf58b9aa79e0a746e6e16580238ef7b).


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by steveloughran <gi...@git.apache.org>.
Github user steveloughran commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181486717
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,347 @@
    +/*
    + * 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
    +
    +import java.io.{FileNotFoundException, IOException, OutputStream}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def createTempFile(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.createTempFile(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        try {
    +          fm.renameTempFile(tempPath, finalPath, overwriteIfPossible)
    +        } catch {
    +          case fe: FileAlreadyExistsException =>
    +            logWarning(
    +              s"Failed to rename temp file $tempPath to $finalPath because file exists", fe)
    +            if (!overwriteIfPossible) throw fe
    +        }
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def createTempFile(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path,
    +      overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    +  }
    +
    +  override def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit = {
    +    if (!overwriteIfPossible && fs.exists(dstPath)) {
    +      throw new FileAlreadyExistsException(
    +        s"Failed to rename $srcPath to $dstPath as destination already exists")
    +    }
    +
    +    if (!fs.rename(srcPath, dstPath)) {
    +      // If overwriteIfPossible = false, then we want to find out why the rename failed and
    +      // try to throw the right error.
    +      if (fs.exists(dstPath)) {
    +        // Some implementations of FileSystem may only return false instead of throwing
    +        // FileAlreadyExistsException. In that case, explicitly throw the error the error
    +        // if overwriteIfPossible = false. Note that this is definitely not atomic.
    +        // This is only a best-effort attempt to identify the situation when rename returned
    +        // false.
    +        if (!overwriteIfPossible) {
    +          throw new FileAlreadyExistsException(s"$dstPath already exists")
    +        }
    +      } else {
    +        val msg = s"Failed to rename temp file $srcPath to $dstPath as rename returned false"
    +        logWarning(msg)
    +        throw new IOException(msg)
    +      }
    +    }
    +  }
    +
    +  override def delete(path: Path): Unit = {
    +    try {
    +      fs.delete(path, true)
    +    } catch {
    +      case e: FileNotFoundException =>
    +        logInfo(s"Failed to delete $path as it does not exist")
    --- End diff --
    
    Basic FS compliance tests, which even GCS now runs, requires that [delete just returns false if there's no path](https://github.com/apache/hadoop/blob/trunk/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/contract/AbstractContractDeleteTest.java#L48). I wouldn't personally worry about it, as if it did ever arise, something has seriously broken.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r180940991
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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
    +
    +import java.io.{FileSystem => _, _}
    --- End diff --
    
    whoa .. i dont know either... my intellij did some weird magic :/


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by brkyvz <gi...@git.apache.org>.
Github user brkyvz commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r180936744
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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
    +
    +import java.io.{FileSystem => _, _}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.commons.io.IOUtils
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def create(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def rename(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.create(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        super.close()
    +        fm.rename(tempPath, finalPath, overwriteIfPossible)
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  fs.setVerifyChecksum(false)
    +  fs.setWriteChecksum(false)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def create(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    --- End diff --
    
    nit: separate lines please


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by brkyvz <gi...@git.apache.org>.
Github user brkyvz commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r180935752
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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
    +
    +import java.io.{FileSystem => _, _}
    --- End diff --
    
    whoa what does `FileSystem => _` do?


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89357/
    Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89226 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89226/testReport)** for PR 21048 at commit [`f1fc175`](https://github.com/apache/spark/commit/f1fc175a3e599c8b72a2c07dcd97bdc3d43e2092).


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by steveloughran <gi...@git.apache.org>.
Github user steveloughran commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    if this is being looked at again, it'd be nice to have a reference back end which just did the write straight to the destination: this is exactly what all the public cloud stores (s3, azure-*, gcs) offer as their atomic write. There'd be no need to make things clever and automatically switch; just make it something people can ask for.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by steveloughran <gi...@git.apache.org>.
Github user steveloughran commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181357072
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,347 @@
    +/*
    + * 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
    +
    +import java.io.{FileNotFoundException, IOException, OutputStream}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def createTempFile(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.createTempFile(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        try {
    +          fm.renameTempFile(tempPath, finalPath, overwriteIfPossible)
    +        } catch {
    +          case fe: FileAlreadyExistsException =>
    +            logWarning(
    +              s"Failed to rename temp file $tempPath to $finalPath because file exists", fe)
    +            if (!overwriteIfPossible) throw fe
    +        }
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def createTempFile(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path,
    +      overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    --- End diff --
    
    This is tagged as deprecated in Hadoop 3 as too much code was doing some exists() check alongside some other reinvocation fo the same underlying code, e.g `if (fs.exists(path) && fs.isFile(path)) { .,.. }`. If you call `fs.getFileStatus()` direct you get an FNFE raised if it isn't and a `FileStatus` if is is there, which can often be used.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89232 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89232/testReport)** for PR 21048 at commit [`1b23492`](https://github.com/apache/spark/commit/1b23492017b8209b6198e6886e06a5cd9d59b9db).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181485806
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,347 @@
    +/*
    + * 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
    +
    +import java.io.{FileNotFoundException, IOException, OutputStream}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def createTempFile(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.createTempFile(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        try {
    +          fm.renameTempFile(tempPath, finalPath, overwriteIfPossible)
    +        } catch {
    +          case fe: FileAlreadyExistsException =>
    +            logWarning(
    +              s"Failed to rename temp file $tempPath to $finalPath because file exists", fe)
    +            if (!overwriteIfPossible) throw fe
    +        }
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def createTempFile(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path,
    +      overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    --- End diff --
    
    Then basically I have to just copy the FileSystem.exists() code right here :)


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89226 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89226/testReport)** for PR 21048 at commit [`f1fc175`](https://github.com/apache/spark/commit/f1fc175a3e599c8b72a2c07dcd97bdc3d43e2092).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `  sealed trait RenameHelperMethods `


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89223/
    Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by brkyvz <gi...@git.apache.org>.
Github user brkyvz commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r180936292
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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
    +
    +import java.io.{FileSystem => _, _}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.commons.io.IOUtils
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def create(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def rename(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.create(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    --- End diff --
    
    nit: `logDebug`


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89357 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89357/testReport)** for PR 21048 at commit [`c5b0c98`](https://github.com/apache/spark/commit/c5b0c98257e39d6af2dd8f702b8cbc9f9e6fabe9).


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89223 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89223/testReport)** for PR 21048 at commit [`df7b339`](https://github.com/apache/spark/commit/df7b339d73097b8501fe0937f770b8b2ded1b63e).


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    I am merging this to master. Once again, thank you for your reviews. 


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89226/
    Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89223 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89223/testReport)** for PR 21048 at commit [`df7b339`](https://github.com/apache/spark/commit/df7b339d73097b8501fe0937f770b8b2ded1b63e).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `      .doc(\"The class used to write checkpoint files atomically. This class must be a subclass \" +`
      * `trait CheckpointFileManager `
      * `  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)`
      * `  sealed class RenameBasedFSDataOutputStream(`
      * `class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)`
      * `class FileContextBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)`


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by brkyvz <gi...@git.apache.org>.
Github user brkyvz commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r180938118
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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
    +
    +import java.io.{FileSystem => _, _}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.commons.io.IOUtils
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def create(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def rename(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.create(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        super.close()
    +        fm.rename(tempPath, finalPath, overwriteIfPossible)
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  fs.setVerifyChecksum(false)
    +  fs.setWriteChecksum(false)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def create(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    +  }
    +
    +  override def rename(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit = {
    +    if (!overwriteIfPossible && fs.exists(dstPath)) {
    +      throw new FileAlreadyExistsException(
    +        s"Failed to rename $srcPath to $dstPath as destination already exists")
    +    }
    +
    +    try {
    +      if (!fs.rename(srcPath, dstPath) && !overwriteIfPossible) {
    --- End diff --
    
    we should ensure that these are file paths and not directories, in case someone else tries to use these APIs elsewhere


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by steveloughran <gi...@git.apache.org>.
Github user steveloughran commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181355640
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,347 @@
    +/*
    + * 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
    +
    +import java.io.{FileNotFoundException, IOException, OutputStream}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def createTempFile(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.createTempFile(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        try {
    +          fm.renameTempFile(tempPath, finalPath, overwriteIfPossible)
    +        } catch {
    +          case fe: FileAlreadyExistsException =>
    +            logWarning(
    +              s"Failed to rename temp file $tempPath to $finalPath because file exists", fe)
    +            if (!overwriteIfPossible) throw fe
    +        }
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def createTempFile(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path,
    +      overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    +  }
    +
    +  override def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit = {
    +    if (!overwriteIfPossible && fs.exists(dstPath)) {
    +      throw new FileAlreadyExistsException(
    +        s"Failed to rename $srcPath to $dstPath as destination already exists")
    +    }
    +
    +    if (!fs.rename(srcPath, dstPath)) {
    --- End diff --
    
    there's a lot of ambiguity about "what does it mean if FileSystem.rename() returns false. FileContext.rename() is stricter here, One troublespot in particular is "what if the source file is not there?". If normally gets downgraded to a "return false".
    
    Proposed: add a `fs.getFileStatus(srcPath)` before the rename call, as it will raise an FNFE if the source file isn't visible. Low cost against HDFS; more against remote object stores, but S3 isn't going to use this one, is it?



---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89283 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89283/testReport)** for PR 21048 at commit [`75b9b18`](https://github.com/apache/spark/commit/75b9b186a54a443f632f06d48aec241f698063ac).


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89283/
    Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89310 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89310/testReport)** for PR 21048 at commit [`ef05009`](https://github.com/apache/spark/commit/ef05009e491d1ffdca2a37ba0441ea8507756e3d).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds no public classes.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181488490
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,347 @@
    +/*
    + * 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
    +
    +import java.io.{FileNotFoundException, IOException, OutputStream}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def createTempFile(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.createTempFile(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        try {
    +          fm.renameTempFile(tempPath, finalPath, overwriteIfPossible)
    +        } catch {
    +          case fe: FileAlreadyExistsException =>
    +            logWarning(
    +              s"Failed to rename temp file $tempPath to $finalPath because file exists", fe)
    +            if (!overwriteIfPossible) throw fe
    +        }
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def createTempFile(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path,
    +      overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    +  }
    +
    +  override def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit = {
    +    if (!overwriteIfPossible && fs.exists(dstPath)) {
    +      throw new FileAlreadyExistsException(
    +        s"Failed to rename $srcPath to $dstPath as destination already exists")
    +    }
    +
    +    if (!fs.rename(srcPath, dstPath)) {
    +      // If overwriteIfPossible = false, then we want to find out why the rename failed and
    +      // try to throw the right error.
    +      if (fs.exists(dstPath)) {
    +        // Some implementations of FileSystem may only return false instead of throwing
    +        // FileAlreadyExistsException. In that case, explicitly throw the error the error
    +        // if overwriteIfPossible = false. Note that this is definitely not atomic.
    +        // This is only a best-effort attempt to identify the situation when rename returned
    +        // false.
    +        if (!overwriteIfPossible) {
    +          throw new FileAlreadyExistsException(s"$dstPath already exists")
    +        }
    +      } else {
    +        val msg = s"Failed to rename temp file $srcPath to $dstPath as rename returned false"
    +        logWarning(msg)
    +        throw new IOException(msg)
    +      }
    +    }
    +  }
    +
    +  override def delete(path: Path): Unit = {
    +    try {
    +      fs.delete(path, true)
    +    } catch {
    +      case e: FileNotFoundException =>
    +        logInfo(s"Failed to delete $path as it does not exist")
    --- End diff --
    
    Well, some people have to deal with older versions of FileSystems, not just the latest "good" ones. :)
    As I said, since there isnt any overhead, I am inclined to keep it in there.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89232 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89232/testReport)** for PR 21048 at commit [`1b23492`](https://github.com/apache/spark/commit/1b23492017b8209b6198e6886e06a5cd9d59b9db).


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by steveloughran <gi...@git.apache.org>.
Github user steveloughran commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181485619
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,347 @@
    +/*
    + * 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
    +
    +import java.io.{FileNotFoundException, IOException, OutputStream}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def createTempFile(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.createTempFile(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        try {
    +          fm.renameTempFile(tempPath, finalPath, overwriteIfPossible)
    +        } catch {
    +          case fe: FileAlreadyExistsException =>
    +            logWarning(
    +              s"Failed to rename temp file $tempPath to $finalPath because file exists", fe)
    +            if (!overwriteIfPossible) throw fe
    +        }
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def createTempFile(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path,
    +      overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    +  }
    +
    +  override def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit = {
    +    if (!overwriteIfPossible && fs.exists(dstPath)) {
    +      throw new FileAlreadyExistsException(
    +        s"Failed to rename $srcPath to $dstPath as destination already exists")
    +    }
    +
    +    if (!fs.rename(srcPath, dstPath)) {
    --- End diff --
    
    Makes sense. 
    
    As you are doing a one-file rename, the rename() will have that atomic-operation semantics you want everywhere, it's just O(data) on s3 and swift. The direct write on both of those is what's critical to avoid checksum writes to block while that rename takes place, but not for the checksum output commit to take.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89283 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89283/testReport)** for PR 21048 at commit [`75b9b18`](https://github.com/apache/spark/commit/75b9b186a54a443f632f06d48aec241f698063ac).
     * This patch **fails to build**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89287 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89287/testReport)** for PR 21048 at commit [`12177b1`](https://github.com/apache/spark/commit/12177b19ef924a6f4fee2d3f774beefae19cc0f0).


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89310/
    Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89227 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89227/testReport)** for PR 21048 at commit [`f9965f1`](https://github.com/apache/spark/commit/f9965f1cecf58b9aa79e0a746e6e16580238ef7b).
     * This patch **fails Spark unit tests**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by steveloughran <gi...@git.apache.org>.
Github user steveloughran commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181357794
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManagerSuite.scala ---
    @@ -0,0 +1,192 @@
    +/*
    + * 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
    +
    +import java.io._
    +import java.net.URI
    +
    +import scala.util.Random
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +
    +import org.apache.spark.SparkFunSuite
    +import org.apache.spark.sql.catalyst.util.quietly
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.test.SharedSparkSession
    +import org.apache.spark.util.Utils
    +
    +abstract class CheckpointFileManagerTests extends SparkFunSuite {
    +
    +  def createManager(path: Path): CheckpointFileManager
    +
    +  test("mkdirs, list, createAtomic, open, delete") {
    +    withTempPath { p =>
    +      val basePath = new Path(p.getAbsolutePath)
    +      val fm = createManager(basePath)
    +      // Mkdirs
    +      val dir = new Path(s"$basePath/dir/subdir/subsubdir")
    +      assert(!fm.exists(dir))
    +      fm.mkdirs(dir)
    +      assert(fm.exists(dir))
    +      fm.mkdirs(dir)
    --- End diff --
    
    if that fm.exists() call was replaced with an fm.getFileStatus() operation, as suggested earlier, this assert could be come `assert(fm.getFileStatus(dir).isDirectory)`


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:

    https://github.com/apache/spark/pull/21048


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by brkyvz <gi...@git.apache.org>.
Github user brkyvz commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r180938649
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManagerSuite.scala ---
    @@ -0,0 +1,188 @@
    +/*
    + * 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
    +
    +import java.io._
    +import java.net.URI
    +
    +import scala.util.Random
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +
    +import org.apache.spark.SparkFunSuite
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.test.SharedSparkSession
    +import org.apache.spark.util.Utils
    +
    +abstract class CheckpointFileManagerTests extends SparkFunSuite {
    +
    +  def createManager(path: Path): CheckpointFileManager
    +
    +  test("mkdirs, list, createAtomic, open, delete") {
    +    withTempPath { p =>
    +      val basePath = new Path(p.getAbsolutePath)
    +      val fm = createManager(basePath)
    +      // Mkdirs
    +      val dir = new Path(s"$basePath/dir/subdir/subsubdir")
    +      assert(!fm.exists(dir))
    +      fm.mkdirs(dir)
    +      assert(fm.exists(dir))
    +      fm.mkdirs(dir)
    +
    +      // List
    +      val acceptAllFilter = new PathFilter {
    +        override def accept(path: Path): Boolean = true
    +      }
    +      val rejectAllFilter = new PathFilter {
    +        override def accept(path: Path): Boolean = false
    +      }
    +      assert(fm.list(basePath, acceptAllFilter).exists(_.getPath.getName == "dir"))
    +      assert(fm.list(basePath, rejectAllFilter).length === 0)
    +
    +      // Create atomic without overwrite
    +      var path = new Path(s"$dir/file")
    +      assert(!fm.exists(path))
    +      fm.createAtomic(path, overwriteIfPossible = false).cancel()
    +      assert(!fm.exists(path))
    +      fm.createAtomic(path, overwriteIfPossible = false).close()
    +      assert(fm.exists(path))
    +      intercept[IOException] {
    +        // should throw exception since file exists and overwrite is false
    +        fm.createAtomic(path, overwriteIfPossible = false).close()
    +      }
    +
    +      // Create atomic with overwrite if possible
    +      path = new Path(s"$dir/file2")
    +      assert(!fm.exists(path))
    +      fm.createAtomic(path, overwriteIfPossible = true).cancel()
    +      assert(!fm.exists(path))
    +      fm.createAtomic(path, overwriteIfPossible = true).close()
    +      assert(fm.exists(path))
    +      fm.createAtomic(path, overwriteIfPossible = true).close()  // should not throw exception
    +
    +      // Open and delete
    +      fm.open(path).close()
    +      fm.delete(path)
    +      assert(!fm.exists(path))
    +      intercept[IOException] {
    +        fm.open(path)
    +      }
    +      fm.delete(path) // should not throw exception
    +    }
    +  }
    +
    +  protected def withTempPath(f: File => Unit): Unit = {
    +    val path = Utils.createTempDir()
    +    path.delete()
    +    try f(path) finally Utils.deleteRecursively(path)
    +  }
    +}
    +
    +class CheckpointFileManagerSuite extends SparkFunSuite with SharedSparkSession {
    +
    +  test("CheckpointFileManager.create() should pick up user-specified class from conf") {
    +    withSQLConf(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key ->
    +        classOf[TestCheckpointFileManager].getName) {
    +      val fileManager =
    +        CheckpointFileManager.create(new Path("/"), spark.sessionState.newHadoopConf)
    +      assert(fileManager.isInstanceOf[TestCheckpointFileManager])
    +    }
    +  }
    +
    +  test("CheckpointFileManager.create() should fallback from FileContext to FileSystem") {
    +    import FakeFileSystem.scheme
    +    spark.conf.set(
    +      s"fs.$scheme.impl",
    +      classOf[FakeFileSystem].getName)
    +    withTempDir { temp =>
    +      val metadataLog = new HDFSMetadataLog[String](spark, s"$scheme://${temp.toURI.getPath}")
    +      assert(metadataLog.add(0, "batch0"))
    +      assert(metadataLog.getLatest() === Some(0 -> "batch0"))
    +      assert(metadataLog.get(0) === Some("batch0"))
    +      assert(metadataLog.get(None, Some(0)) === Array(0 -> "batch0"))
    +
    +
    +      val metadataLog2 = new HDFSMetadataLog[String](spark, s"$scheme://${temp.toURI.getPath}")
    +      assert(metadataLog2.get(0) === Some("batch0"))
    +      assert(metadataLog2.getLatest() === Some(0 -> "batch0"))
    +      assert(metadataLog2.get(None, Some(0)) === Array(0 -> "batch0"))
    +
    +    }
    +  }
    +}
    +
    +class FileContextBasedCheckpointFileManagerSuite extends CheckpointFileManagerTests {
    +  override def createManager(path: Path): CheckpointFileManager = {
    +    new FileContextBasedCheckpointFileManager(path, new Configuration())
    +  }
    +}
    +
    +class FileSystemBasedCheckpointFileManagerSuite extends CheckpointFileManagerTests {
    +  override def createManager(path: Path): CheckpointFileManager = {
    +    new FileSystemBasedCheckpointFileManager(path, new Configuration())
    +  }
    +}
    +
    +
    +/** A fake implementation to test different characteristics of CheckpointFileManager interface */
    +class TestCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends FileSystemBasedCheckpointFileManager(path, hadoopConf) {
    +
    +  import CheckpointFileManager._
    +
    +  override def createAtomic(path: Path, overwrite: Boolean): CancellableFSDataOutputStream = {
    +    if (TestCheckpointFileManager.shouldFailInCreateAtomic) {
    +      TestCheckpointFileManager.cancelCalledInCreateAtomic = false
    +    }
    +    val originalOut = super.createAtomic(path, overwrite)
    +
    +    new CancellableFSDataOutputStream(originalOut) {
    +      override def close(): Unit = {
    +        if (TestCheckpointFileManager.shouldFailInCreateAtomic) {
    +          throw new IOException("Copy failed intentionally")
    +        }
    +        super.close()
    +      }
    +
    +      override def cancel(): Unit = {
    +        TestCheckpointFileManager.cancelCalledInCreateAtomic = true
    +        originalOut.cancel()
    +      }
    +    }
    +  }
    +}
    +
    +object TestCheckpointFileManager {
    +  @volatile var shouldFailInCreateAtomic = false
    +  @volatile var cancelCalledInCreateAtomic = false
    +}
    +
    +
    +/** FakeFileSystem to test fallback of the HDFSMetadataLog from FileContext to FileSystem API */
    +private class FakeFileSystem extends RawLocalFileSystem {
    +  import FakeFileSystem.scheme
    +
    +  override def getUri: URI = {
    +    URI.create(s"$scheme:///")
    +  }
    +}
    +
    +private object FakeFileSystem {
    +  val scheme = s"HDFSMetadataLogSuite${math.abs(Random.nextInt)}"
    --- End diff --
    
    plagiarizer! :P


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/testing-k8s-prb-make-spark-distribution/2279/
    Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/testing-k8s-prb-make-spark-distribution/2278/
    Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/testing-k8s-prb-make-spark-distribution/2233/
    Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89282 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89282/testReport)** for PR 21048 at commit [`1818cb2`](https://github.com/apache/spark/commit/1818cb2e173b87b145be8746a1e9a3a48ce038c1).


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by steveloughran <gi...@git.apache.org>.
Github user steveloughran commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181355839
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,347 @@
    +/*
    + * 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
    +
    +import java.io.{FileNotFoundException, IOException, OutputStream}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def createTempFile(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.createTempFile(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        try {
    +          fm.renameTempFile(tempPath, finalPath, overwriteIfPossible)
    +        } catch {
    +          case fe: FileAlreadyExistsException =>
    +            logWarning(
    +              s"Failed to rename temp file $tempPath to $finalPath because file exists", fe)
    +            if (!overwriteIfPossible) throw fe
    +        }
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def createTempFile(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path,
    +      overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    +  }
    +
    +  override def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit = {
    +    if (!overwriteIfPossible && fs.exists(dstPath)) {
    +      throw new FileAlreadyExistsException(
    +        s"Failed to rename $srcPath to $dstPath as destination already exists")
    +    }
    +
    +    if (!fs.rename(srcPath, dstPath)) {
    +      // If overwriteIfPossible = false, then we want to find out why the rename failed and
    +      // try to throw the right error.
    +      if (fs.exists(dstPath)) {
    +        // Some implementations of FileSystem may only return false instead of throwing
    +        // FileAlreadyExistsException. In that case, explicitly throw the error the error
    +        // if overwriteIfPossible = false. Note that this is definitely not atomic.
    +        // This is only a best-effort attempt to identify the situation when rename returned
    +        // false.
    +        if (!overwriteIfPossible) {
    +          throw new FileAlreadyExistsException(s"$dstPath already exists")
    +        }
    +      } else {
    +        val msg = s"Failed to rename temp file $srcPath to $dstPath as rename returned false"
    +        logWarning(msg)
    +        throw new IOException(msg)
    +      }
    +    }
    +  }
    +
    +  override def delete(path: Path): Unit = {
    +    try {
    +      fs.delete(path, true)
    +    } catch {
    +      case e: FileNotFoundException =>
    +        logInfo(s"Failed to delete $path as it does not exist")
    --- End diff --
    
    Should *never* be raised by a filesystem. Have you actually seen this?


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r181483332
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,347 @@
    +/*
    + * 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
    +
    +import java.io.{FileNotFoundException, IOException, OutputStream}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def createTempFile(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.createTempFile(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        try {
    +          fm.renameTempFile(tempPath, finalPath, overwriteIfPossible)
    +        } catch {
    +          case fe: FileAlreadyExistsException =>
    +            logWarning(
    +              s"Failed to rename temp file $tempPath to $finalPath because file exists", fe)
    +            if (!overwriteIfPossible) throw fe
    +        }
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def createTempFile(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path,
    +      overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    +  }
    +
    +  override def renameTempFile(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit = {
    +    if (!overwriteIfPossible && fs.exists(dstPath)) {
    +      throw new FileAlreadyExistsException(
    +        s"Failed to rename $srcPath to $dstPath as destination already exists")
    +    }
    +
    +    if (!fs.rename(srcPath, dstPath)) {
    --- End diff --
    
    Ideally, I would like the default implementation with rename to work correctly for all FileSystems, including S3AFileSystem (it may not be efficient, but it should be correct). 
    
    Also it important to note that this CheckpointFileManager is built not as a general-purpose common API across FileSystem and FileContext, but specifically for the purpose of checkpointing. So in this case, this absolutely not expected that the source path (i.e. the temp file just written by `RenameBasedFSDataOutputStream`) is not present. So I dont think its worth adding another RPC in the common path just to handle that unexpected case. What I can do is add another check below after the rename return false to try to throw FileNotFoundException instead of the fallback IOException.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by tdas <gi...@git.apache.org>.
Github user tdas commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r180940389
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManagerSuite.scala ---
    @@ -0,0 +1,188 @@
    +/*
    + * 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
    +
    +import java.io._
    +import java.net.URI
    +
    +import scala.util.Random
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +
    +import org.apache.spark.SparkFunSuite
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.test.SharedSparkSession
    +import org.apache.spark.util.Utils
    +
    +abstract class CheckpointFileManagerTests extends SparkFunSuite {
    +
    +  def createManager(path: Path): CheckpointFileManager
    +
    +  test("mkdirs, list, createAtomic, open, delete") {
    +    withTempPath { p =>
    +      val basePath = new Path(p.getAbsolutePath)
    +      val fm = createManager(basePath)
    +      // Mkdirs
    +      val dir = new Path(s"$basePath/dir/subdir/subsubdir")
    +      assert(!fm.exists(dir))
    +      fm.mkdirs(dir)
    +      assert(fm.exists(dir))
    +      fm.mkdirs(dir)
    +
    +      // List
    +      val acceptAllFilter = new PathFilter {
    +        override def accept(path: Path): Boolean = true
    +      }
    +      val rejectAllFilter = new PathFilter {
    +        override def accept(path: Path): Boolean = false
    +      }
    +      assert(fm.list(basePath, acceptAllFilter).exists(_.getPath.getName == "dir"))
    +      assert(fm.list(basePath, rejectAllFilter).length === 0)
    +
    +      // Create atomic without overwrite
    +      var path = new Path(s"$dir/file")
    +      assert(!fm.exists(path))
    +      fm.createAtomic(path, overwriteIfPossible = false).cancel()
    +      assert(!fm.exists(path))
    +      fm.createAtomic(path, overwriteIfPossible = false).close()
    +      assert(fm.exists(path))
    +      intercept[IOException] {
    +        // should throw exception since file exists and overwrite is false
    +        fm.createAtomic(path, overwriteIfPossible = false).close()
    +      }
    +
    +      // Create atomic with overwrite if possible
    +      path = new Path(s"$dir/file2")
    +      assert(!fm.exists(path))
    +      fm.createAtomic(path, overwriteIfPossible = true).cancel()
    +      assert(!fm.exists(path))
    +      fm.createAtomic(path, overwriteIfPossible = true).close()
    +      assert(fm.exists(path))
    +      fm.createAtomic(path, overwriteIfPossible = true).close()  // should not throw exception
    +
    +      // Open and delete
    +      fm.open(path).close()
    +      fm.delete(path)
    +      assert(!fm.exists(path))
    +      intercept[IOException] {
    +        fm.open(path)
    +      }
    +      fm.delete(path) // should not throw exception
    +    }
    +  }
    +
    +  protected def withTempPath(f: File => Unit): Unit = {
    +    val path = Utils.createTempDir()
    +    path.delete()
    +    try f(path) finally Utils.deleteRecursively(path)
    +  }
    +}
    +
    +class CheckpointFileManagerSuite extends SparkFunSuite with SharedSparkSession {
    +
    +  test("CheckpointFileManager.create() should pick up user-specified class from conf") {
    +    withSQLConf(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key ->
    +        classOf[TestCheckpointFileManager].getName) {
    +      val fileManager =
    +        CheckpointFileManager.create(new Path("/"), spark.sessionState.newHadoopConf)
    +      assert(fileManager.isInstanceOf[TestCheckpointFileManager])
    +    }
    +  }
    +
    +  test("CheckpointFileManager.create() should fallback from FileContext to FileSystem") {
    +    import FakeFileSystem.scheme
    +    spark.conf.set(
    +      s"fs.$scheme.impl",
    +      classOf[FakeFileSystem].getName)
    +    withTempDir { temp =>
    +      val metadataLog = new HDFSMetadataLog[String](spark, s"$scheme://${temp.toURI.getPath}")
    +      assert(metadataLog.add(0, "batch0"))
    +      assert(metadataLog.getLatest() === Some(0 -> "batch0"))
    +      assert(metadataLog.get(0) === Some("batch0"))
    +      assert(metadataLog.get(None, Some(0)) === Array(0 -> "batch0"))
    +
    +
    +      val metadataLog2 = new HDFSMetadataLog[String](spark, s"$scheme://${temp.toURI.getPath}")
    +      assert(metadataLog2.get(0) === Some("batch0"))
    +      assert(metadataLog2.getLatest() === Some(0 -> "batch0"))
    +      assert(metadataLog2.get(None, Some(0)) === Array(0 -> "batch0"))
    +
    +    }
    +  }
    +}
    +
    +class FileContextBasedCheckpointFileManagerSuite extends CheckpointFileManagerTests {
    +  override def createManager(path: Path): CheckpointFileManager = {
    +    new FileContextBasedCheckpointFileManager(path, new Configuration())
    +  }
    +}
    +
    +class FileSystemBasedCheckpointFileManagerSuite extends CheckpointFileManagerTests {
    +  override def createManager(path: Path): CheckpointFileManager = {
    +    new FileSystemBasedCheckpointFileManager(path, new Configuration())
    +  }
    +}
    +
    +
    +/** A fake implementation to test different characteristics of CheckpointFileManager interface */
    +class TestCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends FileSystemBasedCheckpointFileManager(path, hadoopConf) {
    +
    +  import CheckpointFileManager._
    +
    +  override def createAtomic(path: Path, overwrite: Boolean): CancellableFSDataOutputStream = {
    +    if (TestCheckpointFileManager.shouldFailInCreateAtomic) {
    +      TestCheckpointFileManager.cancelCalledInCreateAtomic = false
    +    }
    +    val originalOut = super.createAtomic(path, overwrite)
    +
    +    new CancellableFSDataOutputStream(originalOut) {
    +      override def close(): Unit = {
    +        if (TestCheckpointFileManager.shouldFailInCreateAtomic) {
    +          throw new IOException("Copy failed intentionally")
    +        }
    +        super.close()
    +      }
    +
    +      override def cancel(): Unit = {
    +        TestCheckpointFileManager.cancelCalledInCreateAtomic = true
    +        originalOut.cancel()
    +      }
    +    }
    +  }
    +}
    +
    +object TestCheckpointFileManager {
    +  @volatile var shouldFailInCreateAtomic = false
    +  @volatile var cancelCalledInCreateAtomic = false
    +}
    +
    +
    +/** FakeFileSystem to test fallback of the HDFSMetadataLog from FileContext to FileSystem API */
    +private class FakeFileSystem extends RawLocalFileSystem {
    +  import FakeFileSystem.scheme
    +
    +  override def getUri: URI = {
    +    URI.create(s"$scheme:///")
    +  }
    +}
    +
    +private object FakeFileSystem {
    +  val scheme = s"HDFSMetadataLogSuite${math.abs(Random.nextInt)}"
    --- End diff --
    
    Hahaha.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by brkyvz <gi...@git.apache.org>.
Github user brkyvz commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r180938989
  
    --- Diff: sql/core/src/test/scala/org/apache/spark/sql/execution/streaming/state/StateStoreSuite.scala ---
    @@ -471,6 +470,41 @@ class StateStoreSuite extends StateStoreSuiteBase[HDFSBackedStateStoreProvider]
         }
       }
     
    +  test("error writing [version].delta cancels the output stream") {
    +
    +    val hadoopConf = new Configuration()
    +    hadoopConf.set(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key,
    +      classOf[TestCheckpointFileManager].getName)
    +    val remoteDir = Utils.createTempDir().getAbsolutePath
    +
    +    val provider = newStoreProvider(
    +      opId = Random.nextInt, partition = 0, dir = remoteDir, hadoopConf = hadoopConf)
    +
    +    // Disable failure of output stream and generate versions
    +    TestCheckpointFileManager.shouldFailInCreateAtomic = false
    +    for (version <- 1 to 10) {
    +      val store = provider.getStore(version - 1)
    +      put(store, version.toString, version) // update "1" -> 1, "2" -> 2, ...
    +      store.commit()
    +    }
    +    val version10Data = (1L to 10).map(_.toString).map(x => x -> x).toSet
    +
    +    val store = provider.getStore(10)
    +    // Fail commit for next version and verify that reloading resets the files
    +    TestCheckpointFileManager.shouldFailInCreateAtomic = true
    +    put(store, "11", 11)
    +    val e = intercept[IllegalStateException] { quietly { store.commit() } }
    +    assert(e.getCause.isInstanceOf[IOException], "Was waiting the IOException to be thrown")
    +    TestCheckpointFileManager.shouldFailInCreateAtomic = false
    +
    +    // Abort commit for next version and verify that reloading resets the files
    +    val store2 = provider.getStore(10)
    +    put(store2, "11", 11)
    +    store2.abort()
    +    assert(TestCheckpointFileManager.cancelCalledInCreateAtomic)
    --- End diff --
    
    can you verify that it was false before the `abort`?


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89287 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89287/testReport)** for PR 21048 at commit [`12177b1`](https://github.com/apache/spark/commit/12177b19ef924a6f4fee2d3f774beefae19cc0f0).
     * This patch passes all tests.
     * This patch merges cleanly.
     * This patch adds the following public classes _(experimental)_:
      * `class CreateAtomicTestManager(path: Path, hadoopConf: Configuration)`


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/testing-k8s-prb-make-spark-distribution/2292/
    Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by zsxwing <gi...@git.apache.org>.
Github user zsxwing commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    LGTM


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/testing-k8s-prb-make-spark-distribution/2326/
    Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89282/
    Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test FAILed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/testing-k8s-prb-make-spark-distribution/2232/
    Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    **[Test build #89282 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89282/testReport)** for PR 21048 at commit [`1818cb2`](https://github.com/apache/spark/commit/1818cb2e173b87b145be8746a1e9a3a48ce038c1).
     * This patch **fails to build**.
     * This patch merges cleanly.
     * This patch adds no public classes.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark pull request #21048: [SPARK-23966][SS] Refactoring all checkpoint file...

Posted by brkyvz <gi...@git.apache.org>.
Github user brkyvz commented on a diff in the pull request:

    https://github.com/apache/spark/pull/21048#discussion_r180937241
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/CheckpointFileManager.scala ---
    @@ -0,0 +1,344 @@
    +/*
    + * 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
    +
    +import java.io.{FileSystem => _, _}
    +import java.util.{EnumSet, UUID}
    +
    +import scala.util.control.NonFatal
    +
    +import org.apache.commons.io.IOUtils
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs._
    +import org.apache.hadoop.fs.local.{LocalFs, RawLocalFs}
    +import org.apache.hadoop.fs.permission.FsPermission
    +
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.sql.execution.streaming.CheckpointFileManager.RenameHelperMethods
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.util.Utils
    +
    +/**
    + * An interface to abstract out all operation related to streaming checkpoints. Most importantly,
    + * the key operation this interface provides is `createAtomic(path, overwrite)` which returns a
    + * `CancellableFSDataOutputStream`. This method is used by [[HDFSMetadataLog]] and
    + * [[org.apache.spark.sql.execution.streaming.state.StateStore StateStore]] implementations
    + * to write a complete checkpoint file atomically (i.e. no partial file will be visible), with or
    + * without overwrite.
    + *
    + * This higher-level interface above the Hadoop FileSystem is necessary because
    + * different implementation of FileSystem/FileContext may have different combination of operations
    + * to provide the desired atomic guarantees (e.g. write-to-temp-file-and-rename,
    + * direct-write-and-cancel-on-failure) and this abstraction allow different implementations while
    + * keeping the usage simple (`createAtomic` -> `close` or `cancel`).
    + */
    +trait CheckpointFileManager {
    +
    +  import org.apache.spark.sql.execution.streaming.CheckpointFileManager._
    +
    +  /**
    +   * Create a file and make its contents available atomically after the output stream is closed.
    +   *
    +   * @param path                Path to create
    +   * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +   *                            overwrite the file if it already exists. It should not throw
    +   *                            any exception if the file exists. However, if false, then the
    +   *                            implementation must not overwrite if the file alraedy exists and
    +   *                            must throw `FileAlreadyExistsException` in that case.
    +   */
    +  def createAtomic(path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream
    +
    +  /** Open a file for reading, or throw exception if it does not exist. */
    +  def open(path: Path): FSDataInputStream
    +
    +  /** List the files in a path that match a filter. */
    +  def list(path: Path, filter: PathFilter): Array[FileStatus]
    +
    +  /** List all the files in a path. */
    +  def list(path: Path): Array[FileStatus] = {
    +    list(path, new PathFilter { override def accept(path: Path): Boolean = true })
    +  }
    +
    +  /** Make directory at the give path and all its parent directories as needed. */
    +  def mkdirs(path: Path): Unit
    +
    +  /** Whether path exists */
    +  def exists(path: Path): Boolean
    +
    +  /** Recursively delete a path if it exists. Should not throw exception if file doesn't exist. */
    +  def delete(path: Path): Unit
    +
    +  /** Is the default file system this implementation is operating on the local file system. */
    +  def isLocal: Boolean
    +}
    +
    +object CheckpointFileManager extends Logging {
    +
    +  /**
    +   * Additional methods in CheckpointFileManager implementations that allows
    +   * [[RenameBasedFSDataOutputStream]] get atomicity by write-to-temp-file-and-rename
    +   */
    +  sealed trait RenameHelperMethods { self => CheckpointFileManager
    +    /** Create a file with overwrite. */
    +    def create(path: Path): FSDataOutputStream
    +
    +    /**
    +     * Rename a file.
    +     *
    +     * @param srcPath             Source path to rename
    +     * @param dstPath             Destination path to rename to
    +     * @param overwriteIfPossible If true, then the implementations must do a best-effort attempt to
    +     *                            overwrite the file if it already exists. It should not throw
    +     *                            any exception if the file exists. However, if false, then the
    +     *                            implementation must not overwrite if the file alraedy exists and
    +     *                            must throw `FileAlreadyExistsException` in that case.
    +     */
    +    def rename(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit
    +  }
    +
    +  /**
    +   * An interface to add the cancel() operation to [[FSDataOutputStream]]. This is used
    +   * mainly by `CheckpointFileManager.createAtomic` to write a file atomically.
    +   *
    +   * @see [[CheckpointFileManager]].
    +   */
    +  abstract class CancellableFSDataOutputStream(protected val underlyingStream: OutputStream)
    +    extends FSDataOutputStream(underlyingStream, null) {
    +    /** Cancel the `underlyingStream` and ensure that the output file is not generated. */
    +    def cancel(): Unit
    +  }
    +
    +  /**
    +   * An implementation of [[CancellableFSDataOutputStream]] that writes a file atomically by writing
    +   * to a temporary file and then renames.
    +   */
    +  sealed class RenameBasedFSDataOutputStream(
    +      fm: CheckpointFileManager with RenameHelperMethods,
    +      finalPath: Path,
    +      tempPath: Path,
    +      overwriteIfPossible: Boolean)
    +    extends CancellableFSDataOutputStream(fm.create(tempPath)) {
    +
    +    def this(fm: CheckpointFileManager with RenameHelperMethods, path: Path, overwrite: Boolean) = {
    +      this(fm, path, generateTempPath(path), overwrite)
    +    }
    +
    +    logInfo(s"Writing atomically to $finalPath using temp file $tempPath")
    +    @volatile private var terminated = false
    +
    +    override def close(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        super.close()
    +        fm.rename(tempPath, finalPath, overwriteIfPossible)
    +        logInfo(s"Renamed temp file $tempPath to $finalPath")
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +
    +    override def cancel(): Unit = synchronized {
    +      try {
    +        if (terminated) return
    +        underlyingStream.close()
    +        fm.delete(tempPath)
    +      } catch {
    +        case NonFatal(e) =>
    +          logWarning(s"Error cancelling write to $finalPath", e)
    +      } finally {
    +        terminated = true
    +      }
    +    }
    +  }
    +
    +
    +  /** Create an instance of [[CheckpointFileManager]] based on the path and configuration. */
    +  def create(path: Path, hadoopConf: Configuration): CheckpointFileManager = {
    +    val fileManagerClass = hadoopConf.get(
    +      SQLConf.STREAMING_CHECKPOINT_FILE_MANAGER_CLASS.parent.key)
    +    if (fileManagerClass != null) {
    +      return Utils.classForName(fileManagerClass)
    +        .getConstructor(classOf[Path], classOf[Configuration])
    +        .newInstance(path, hadoopConf)
    +        .asInstanceOf[CheckpointFileManager]
    +    }
    +    try {
    +      // Try to create a manager based on `FileContext` because HDFS's `FileContext.rename()
    +      // gives atomic renames, which is what we rely on for the default implementation
    +      // `CheckpointFileManager.createAtomic`.
    +      new FileContextBasedCheckpointFileManager(path, hadoopConf)
    +    } catch {
    +      case e: UnsupportedFileSystemException =>
    +        logWarning(
    +          "Could not use FileContext API for managing Structured Streaming checkpoint files at " +
    +            s"$path. Using FileSystem API instead for managing log files. If the implementation " +
    +            s"of FileSystem.rename() is not atomic, then the correctness and fault-tolerance of" +
    +            s"your Structured Streaming is not guaranteed.")
    +        new FileSystemBasedCheckpointFileManager(path, hadoopConf)
    +    }
    +  }
    +
    +  private def generateTempPath(path: Path): Path = {
    +    val tc = org.apache.spark.TaskContext.get
    +    val tid = if (tc != null) ".TID" + tc.taskAttemptId else ""
    +    new Path(path.getParent, s".${path.getName}.${UUID.randomUUID}${tid}.tmp")
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileSystem]] API. */
    +class FileSystemBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  protected val fs = path.getFileSystem(hadoopConf)
    +
    +  fs.setVerifyChecksum(false)
    +  fs.setWriteChecksum(false)
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fs.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fs.mkdirs(path, FsPermission.getDirDefault)
    +  }
    +
    +  override def create(path: Path): FSDataOutputStream = {
    +    fs.create(path, true)
    +  }
    +
    +  override def createAtomic(
    +      path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    +    new RenameBasedFSDataOutputStream(this, path, overwriteIfPossible)
    +  }
    +
    +  override def open(path: Path): FSDataInputStream = {
    +    fs.open(path)
    +  }
    +
    +  override def exists(path: Path): Boolean = {
    +    fs.exists(path)
    +  }
    +
    +  override def rename(srcPath: Path, dstPath: Path, overwriteIfPossible: Boolean): Unit = {
    +    if (!overwriteIfPossible && fs.exists(dstPath)) {
    +      throw new FileAlreadyExistsException(
    +        s"Failed to rename $srcPath to $dstPath as destination already exists")
    +    }
    +
    +    try {
    +      if (!fs.rename(srcPath, dstPath) && !overwriteIfPossible) {
    +        if (fs.exists(dstPath)) {
    +          // Some implementations of FileSystem may not throw FileAlreadyExistsException but
    +          // only return false if file already exists. Explicitly throw the error.
    +          // Note that this is definitely not atomic, so this is only a best-effort attempt
    +          // to throw the most appropriate exception when rename returned false.
    +          throw new FileAlreadyExistsException(s"$dstPath already exists")
    +        } else {
    +          val msg = s"Failed to rename temp file $srcPath to $dstPath as rename returned false"
    +          logWarning(msg)
    +          throw new IOException(msg)
    +        }
    +      }
    +    } catch {
    +      case fe: FileAlreadyExistsException =>
    +        // Some implementation of FileSystem can directly throw FileAlreadyExistsException if file
    +        // already exists. Ignore the error if overwriteIfPossible = true as it is expected to be
    +        // best effort.
    +        logWarning(s"Failed to rename temp file $srcPath to $dstPath because file exists", fe)
    +        if (!overwriteIfPossible) throw fe
    +    }
    +  }
    +
    +  override def delete(path: Path): Unit = {
    +    try {
    +      fs.delete(path, true)
    +    } catch {
    +      case e: FileNotFoundException =>
    +        logInfo(s"Failed to delete $path as it does not exist")
    +        // ignore if file has already been deleted
    +    }
    +  }
    +
    +  override def isLocal: Boolean = fs match {
    +    case _: LocalFileSystem | _: RawLocalFileSystem => true
    +    case _ => false
    +  }
    +}
    +
    +
    +/** An implementation of [[CheckpointFileManager]] using Hadoop's [[FileContext]] API. */
    +class FileContextBasedCheckpointFileManager(path: Path, hadoopConf: Configuration)
    +  extends CheckpointFileManager with RenameHelperMethods with Logging {
    +
    +  import CheckpointFileManager._
    +
    +  private val fc = if (path.toUri.getScheme == null) {
    +    FileContext.getFileContext(hadoopConf)
    +  } else {
    +    FileContext.getFileContext(path.toUri, hadoopConf)
    +  }
    +
    +  override def list(path: Path, filter: PathFilter): Array[FileStatus] = {
    +    fc.util.listStatus(path, filter)
    +  }
    +
    +  override def mkdirs(path: Path): Unit = {
    +    fc.mkdir(path, FsPermission.getDirDefault, true)
    +  }
    +
    +  override def create(path: Path): FSDataOutputStream = {
    +    import CreateFlag._
    +    fc.create(path, EnumSet.of(CREATE, OVERWRITE))
    +  }
    +
    +  override def createAtomic(
    +      path: Path, overwriteIfPossible: Boolean): CancellableFSDataOutputStream = {
    --- End diff --
    
    ditto on two lines


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Merged build finished. Test FAILed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/testing-k8s-prb-make-spark-distribution/2236/
    Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


[GitHub] spark issue #21048: [SPARK-23966][SS] Refactoring all checkpoint file writin...

Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:

    https://github.com/apache/spark/pull/21048
  
    Test PASSed.
    Refer to this link for build results (access rights to CI server needed): 
    https://amplab.cs.berkeley.edu/jenkins//job/testing-k8s-prb-make-spark-distribution/2281/
    Test PASSed.


---

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org