Github user rxin commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15551#discussion_r84196777
  
    --- Diff: 
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/WriteOutput.scala
 ---
    @@ -0,0 +1,514 @@
    +/*
    + * 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.datasources
    +
    +import java.util.{Date, UUID}
    +
    +import org.apache.hadoop.conf.Configuration
    +import org.apache.hadoop.fs.Path
    +import org.apache.hadoop.mapreduce._
    +import org.apache.hadoop.mapreduce.lib.output.{FileOutputCommitter, 
FileOutputFormat}
    +import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl
    +
    +import org.apache.spark._
    +import org.apache.spark.internal.Logging
    +import org.apache.spark.mapred.SparkHadoopMapRedUtil
    +import org.apache.spark.sql.{Dataset, SparkSession}
    +import org.apache.spark.sql.catalyst.catalog.BucketSpec
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.catalyst.plans.physical.HashPartitioning
    +import org.apache.spark.sql.catalyst.InternalRow
    +import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
    +import org.apache.spark.sql.execution.{SQLExecution, 
UnsafeKVExternalSorter}
    +import org.apache.spark.sql.internal.SQLConf
    +import org.apache.spark.sql.types.{IntegerType, StringType, StructField, 
StructType}
    +import org.apache.spark.util.{SerializableConfiguration, Utils}
    +import org.apache.spark.util.collection.unsafe.sort.UnsafeExternalSorter
    +
    +
    +/**
    + * A helper object for writing data out to an existing partition.
    + */
    +object WriteOutput extends Logging {
    +
    +  /** A shared job description for all the write tasks. */
    +  private class WriteJobDescription(
    +      val serializableHadoopConf: SerializableConfiguration,
    +      val outputWriterFactory: OutputWriterFactory,
    +      val allColumns: Seq[Attribute],
    +      val partitionColumns: Seq[Attribute],
    +      val nonPartitionColumns: Seq[Attribute],
    +      val bucketSpec: Option[BucketSpec],
    +      val isAppend: Boolean,
    +      val path: String,
    +      val outputFormatClass: Class[_ <: OutputFormat[_, _]])
    +    extends Serializable {
    +
    +    assert(allColumns.toSet == (partitionColumns ++ 
nonPartitionColumns).toSet)
    +  }
    +
    +  /**
    +   * Basic work flow of this command is:
    +   * 1. Driver side setup, including output committer initialization and 
data source specific
    +   *    preparation work for the write job to be issued.
    +   * 2. Issues a write job consists of one or more executor side tasks, 
each of which writes all
    +   *    rows within an RDD partition.
    +   * 3. If no exception is thrown in a task, commits that task, otherwise 
aborts that task;  If any
    +   *    exception is thrown during task commitment, also aborts that task.
    +   * 4. If all tasks are committed, commit the job, otherwise aborts the 
job;  If any exception is
    +   *    thrown during job commitment, also aborts the job.
    +   */
    +  def write(
    +      sparkSession: SparkSession,
    +      plan: LogicalPlan,
    +      fileFormat: FileFormat,
    +      outputPath: Path,
    +      hadoopConf: Configuration,
    +      partitionColumns: Seq[Attribute],
    +      bucketSpec: Option[BucketSpec],
    +      refreshFunction: () => Unit,
    +      options: Map[String, String],
    +      isAppend: Boolean): Unit = {
    +
    +    val job = Job.getInstance(hadoopConf)
    +    job.setOutputKeyClass(classOf[Void])
    +    job.setOutputValueClass(classOf[InternalRow])
    +    FileOutputFormat.setOutputPath(job, outputPath)
    +
    +    val partitionSet = AttributeSet(partitionColumns)
    +    val dataColumns = plan.output.filterNot(partitionSet.contains)
    +    val queryExecution = Dataset.ofRows(sparkSession, plan).queryExecution
    +
    +    // Note: prepareWrite has side effect. It sets "job".
    +    val outputWriterFactory =
    +      fileFormat.prepareWrite(sparkSession, job, options, 
dataColumns.toStructType)
    +
    +    val description = new WriteJobDescription(
    +      serializableHadoopConf = new 
SerializableConfiguration(job.getConfiguration),
    +      outputWriterFactory = outputWriterFactory,
    +      allColumns = plan.output,
    +      partitionColumns = partitionColumns,
    +      nonPartitionColumns = dataColumns,
    +      bucketSpec = bucketSpec,
    +      isAppend = isAppend,
    +      path = outputPath.toString,
    +      outputFormatClass = job.getOutputFormatClass)
    +
    +    SQLExecution.withNewExecutionId(sparkSession, queryExecution) {
    +      // This call shouldn't be put into the `try` block below because it 
only initializes and
    +      // prepares the job, any exception thrown from here shouldn't cause 
abortJob() to be called.
    +      val committer = setupDriverCommitter(job, outputPath.toString, 
isAppend)
    +
    +      try {
    +        sparkSession.sparkContext.runJob(queryExecution.toRdd,
    +          (taskContext: TaskContext, iter: Iterator[InternalRow]) => {
    +            executeTask(
    +              description = description,
    +              sparkStageId = taskContext.stageId(),
    +              sparkPartitionId = taskContext.partitionId(),
    +              sparkAttemptNumber = taskContext.attemptNumber(),
    +              iterator = iter)
    +          })
    +
    +        committer.commitJob(job)
    +        logInfo(s"Job ${job.getJobID} committed.")
    +
    +        refreshFunction()
    +      } catch { case cause: Throwable =>
    +        logError(s"Aborting job ${job.getJobID}.", cause)
    +        committer.abortJob(job, JobStatus.State.FAILED)
    +
    +        throw new SparkException("Job aborted.", cause)
    +      }
    +    }
    +  }
    +
    +  /**
    +   * Writes data out in a single Spark task.
    +   */
    +  def executeTask(
    +      description: WriteJobDescription,
    +      sparkStageId: Int,
    +      sparkPartitionId: Int,
    +      sparkAttemptNumber: Int,
    +      iterator: Iterator[InternalRow]): Unit = {
    +
    +    // Set up the attempt context required to use in the output committers.
    +    val taskAttemptContext: TaskAttemptContext = {
    +      val jobId = SparkHadoopWriter.createJobID(new Date, sparkStageId)
    +      val taskId = new TaskID(jobId, TaskType.MAP, sparkPartitionId)
    +      val taskAttemptId = new TaskAttemptID(taskId, sparkAttemptNumber)
    +
    +      // Set up the configuration object
    +      val hadoopConf = description.serializableHadoopConf.value
    +      hadoopConf.set("mapred.job.id", jobId.toString)
    +      hadoopConf.set("mapred.tip.id", taskAttemptId.getTaskID.toString)
    +      hadoopConf.set("mapred.task.id", taskAttemptId.toString)
    +      hadoopConf.setBoolean("mapred.task.is.map", true)
    +      hadoopConf.setInt("mapred.task.partition", 0)
    +
    +      new TaskAttemptContextImpl(hadoopConf, taskAttemptId)
    +    }
    +
    +    val committer = newOutputCommitter(
    +      description.outputFormatClass, taskAttemptContext, description.path, 
description.isAppend)
    +    committer.setupTask(taskAttemptContext)
    +
    +    val jobId = taskAttemptContext.getJobID
    +    val taskId = taskAttemptContext.getTaskAttemptID.getTaskID
    +
    +    val writeTask =
    +      if (description.partitionColumns.isEmpty && 
description.bucketSpec.isEmpty) {
    +        new SingleDirectoryWriteTask(description, taskAttemptContext, 
committer)
    +      } else {
    +        new DynamicPartitionWriteTask(description, taskAttemptContext, 
committer)
    +      }
    +
    +    try {
    +      Utils.tryWithSafeFinallyAndFailureCallbacks(block = {
    +        // Execute the task to write rows out
    +        writeTask.execute(iterator)
    +        writeTask.releaseResources()
    +
    +        // Commit the task
    +        SparkHadoopMapRedUtil.commitTask(committer, taskAttemptContext, 
jobId.getId, taskId.getId)
    +      })(catchBlock = {
    +        // If there is an error, release resource and then abort the task
    +        try {
    --- End diff --
    
    No because we can't abort the task if there is no error (which would happen 
if we put it in finally).



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastruct...@apache.org or file a JIRA ticket
with INFRA.
---

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

Reply via email to