Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
org.apache.spark.deploy.history.BasicEventFilterBuilder

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EventFilterBuilder is private in Spark. Do you mind if I ask why we use service loader?

@HeartSaVioR HeartSaVioR Jan 31, 2020

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

core module cannot refer SQL/core module which also has EventFilterBuilder. So that should be the way to discover and load implementations of EventFilterBuilder"s".

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. I think that's possible via simply using reflection which I think is easier to read the codes. I think we're already doing this in few places such as FileCommitProtocol.instantiate

Seems a bit odds to use service loader for internal classes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

private def loadPlugins(): Iterable[AppHistoryServerPlugin] = {
ServiceLoader.load(classOf[AppHistoryServerPlugin], Utils.getContextOrSparkClassLoader).asScala
}

That is the way how FsHistoryProvider already deals with loading class in SQL core module.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, thanks. at least it's consistent.

Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/*
* 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.deploy.history

import scala.collection.mutable

import org.apache.spark.deploy.history.EventFilter.FilterStatistics
import org.apache.spark.internal.Logging
import org.apache.spark.scheduler._

/**
* This class tracks both live jobs and live executors, and pass the list to the
* [[BasicEventFilter]] to help BasicEventFilter to reject finished jobs (+ stages/tasks/RDDs)
* and dead executors.
*/
private[spark] class BasicEventFilterBuilder extends SparkListener with EventFilterBuilder {
private val _liveJobToStages = new mutable.HashMap[Int, Set[Int]]
private val _stageToTasks = new mutable.HashMap[Int, mutable.Set[Long]]
private val _stageToRDDs = new mutable.HashMap[Int, Set[Int]]
private val _liveExecutors = new mutable.HashSet[String]

private var totalJobs: Long = 0L
private var totalStages: Long = 0L
private var totalTasks: Long = 0L

def liveJobs: Set[Int] = _liveJobToStages.keySet.toSet
def liveStages: Set[Int] = _stageToRDDs.keySet.toSet
def liveTasks: Set[Long] = _stageToTasks.values.flatten.toSet
def liveRDDs: Set[Int] = _stageToRDDs.values.flatten.toSet
def liveExecutors: Set[String] = _liveExecutors.toSet

override def onJobStart(jobStart: SparkListenerJobStart): Unit = {
totalJobs += 1
jobStart.stageIds.foreach { stageId =>
if (_stageToRDDs.get(stageId).isEmpty) {
// stage submit event is not received yet
totalStages += 1
_stageToRDDs.put(stageId, Set.empty[Int])
}
}
_liveJobToStages += jobStart.jobId -> jobStart.stageIds.toSet
}

override def onJobEnd(jobEnd: SparkListenerJobEnd): Unit = {
val stages = _liveJobToStages.getOrElse(jobEnd.jobId, Seq.empty[Int])
_liveJobToStages -= jobEnd.jobId
// This might leave some stages and tasks if job end event comes earlier than stage submitted
// or task start event; it's not accurate but safer than dropping wrong events which cannot be
// restored.
_stageToTasks --= stages
_stageToRDDs --= stages
}

override def onStageSubmitted(stageSubmitted: SparkListenerStageSubmitted): Unit = {
val stageId = stageSubmitted.stageInfo.stageId
if (_stageToRDDs.get(stageId).isEmpty) {
// job start event is not received yet

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you seen this situation? I was under the impression you'd never see a stage submission without the parent job starting first.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I admit it's just guessing that events out of order can happen in arbitrary way, as previous review comment pointed out I should consider events out of order but I have no idea about these out of order. But it's also non-trivial to sort out which cases can happen from looking into AppStatusListener code.

Why not enumerating the cases we've observed in AppStatusListener as code comment? There's no value if only part of group knows about it in their memory. This looks to be a "truck number".

Btw, have we struggle to find out why these events can be out of order, and try to fix it?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The order of job/stage/task events is defined by the DAGScheduler. Adding comments in AppStatusListener would just be trying to document the scheduler behavior, so if you want to track that, it would be better to document the scheduler itself. When you add other subsystems (like SQL), then you also add other things that may arrive out of order (see how the SQL listener needs to handle job / execution events).

On the scheduler side, I think most of the out of order issues are related to tasks. I'm somewhat confident that job and stage events generally arrive in order, but tasks can be very off. e.g. see this comment in handleBeginEvent:

    // Note that there is a chance that this task is launched after the stage is cancelled.
    // In that case, we wouldn't have the stage anymore in stageIdToStage.

I guess my reply here applies more to my onTaskStart comment below; here we can assume that the events are in order. But there, it would be better to ignore events if they arrive at the wrong time.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah OK my bad. I was confused that there's a case the message bus doesn't guarantee event order (so I felt we have to rely on history), but looks like that's not the case. Then it would be enough if there's enough comment on DAGScheduler.

Thanks for the correction. I may need to spend my time to read through DAGScheduler, but collecting the information from your comment, looks like the main point is discarding the task if the stage is not active. I'll deal with it for now.

totalStages += 1
}
_stageToRDDs.put(stageId, stageSubmitted.stageInfo.rddInfos.map(_.id).toSet)
}

override def onTaskStart(taskStart: SparkListenerTaskStart): Unit = {
totalTasks += 1
val curTasks = _stageToTasks.getOrElseUpdate(taskStart.stageId,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still think this should not be getOrElseUpdate. Add the empty set to the map in onStageSubmitted, clean it up in onJobEnd, and only update it here if it's still in the map.

Also, maybe something for the future: if a large stage is recomputed, you could potentially filter out a lot of data by filtering the failed attempt's tasks or a subset of them (e.g. only keep the failed ones).

@HeartSaVioR HeartSaVioR Jan 6, 2020

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here; this is assuming arbitrary out of order of events. If we are sure stage submission event must happen earlier than task start event, this code doesn't make sense. But I also would like to be sure we document these cases as a reference. It's not easy to understand the intention as I don't have background knowledge and can't find it easily.

mutable.HashSet[Long]())
curTasks += taskStart.taskInfo.taskId
}

override def onExecutorAdded(executorAdded: SparkListenerExecutorAdded): Unit = {
_liveExecutors += executorAdded.executorId
}

override def onExecutorRemoved(executorRemoved: SparkListenerExecutorRemoved): Unit = {
_liveExecutors -= executorRemoved.executorId
}

override def createFilter(): EventFilter = {
val stats = FilterStatistics(totalJobs, liveJobs.size, totalStages,
liveStages.size, totalTasks, liveTasks.size)

new BasicEventFilter(stats, liveJobs, liveStages, liveTasks, liveRDDs, liveExecutors)
}
}

/**
* This class provides the functionality to reject events which are related to the finished
* jobs based on the given information. This class only deals with job related events, and provides
* a PartialFunction which returns false for rejected events for finished jobs, returns true
* otherwise.
*/
private[spark] abstract class JobEventFilter(
stats: Option[FilterStatistics],
liveJobs: Set[Int],
liveStages: Set[Int],
liveTasks: Set[Long],
liveRDDs: Set[Int]) extends EventFilter with Logging {

logDebug(s"jobs : $liveJobs")
logDebug(s"stages : $liveStages")
logDebug(s"tasks : $liveTasks")
logDebug(s"RDDs : $liveRDDs")

override def statistics(): Option[FilterStatistics] = stats

protected val acceptFnForJobEvents: PartialFunction[SparkListenerEvent, Boolean] = {
case e: SparkListenerStageCompleted =>
liveStages.contains(e.stageInfo.stageId)
case e: SparkListenerStageSubmitted =>
liveStages.contains(e.stageInfo.stageId)
case e: SparkListenerTaskStart =>
liveTasks.contains(e.taskInfo.taskId)
case e: SparkListenerTaskGettingResult =>
liveTasks.contains(e.taskInfo.taskId)
case e: SparkListenerTaskEnd =>
liveTasks.contains(e.taskInfo.taskId)
case e: SparkListenerJobStart =>
liveJobs.contains(e.jobId)
case e: SparkListenerJobEnd =>
liveJobs.contains(e.jobId)
case e: SparkListenerUnpersistRDD =>
liveRDDs.contains(e.rddId)
case e: SparkListenerExecutorMetricsUpdate =>
e.accumUpdates.exists { case (_, stageId, _, _) => liveStages.contains(stageId) }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this also check the live executors? (Stage may still be running but the executor is gone, so maybe data about it is not interesting anymore?)

Or maybe that particular check should be in BasicEventFilter... not sure, I'm slightly confused about the role of each class here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In AppStatusListener, SparkListenerExecutorMetricsUpdate updates metrics not only for executor but also for stage and task; so ideally the event may need to be accepted if either task or stage is live. (I'll add the check for liveTasks as well)

If checking executor is needed in any way, we may want to move this to BasicEventFilter.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, ok, makes sense to try to keep the stage metrics accurate.

case e: SparkListenerSpeculativeTaskSubmitted =>
liveStages.contains(e.stageId)
}
}

/**
* This class rejects events which are related to the finished jobs or dead executors,
* based on the given information. The events which are not related to the job and executor
* will be considered as "Don't mind".
*/
private[spark] class BasicEventFilter(
_stats: FilterStatistics,
_liveJobs: Set[Int],
_liveStages: Set[Int],
_liveTasks: Set[Long],
_liveRDDs: Set[Int],
liveExecutors: Set[String])
extends JobEventFilter(
Some(_stats),
_liveJobs,
_liveStages,
_liveTasks,
_liveRDDs) with Logging {

logDebug(s"live executors : $liveExecutors")

private val _acceptFn: PartialFunction[SparkListenerEvent, Boolean] = {
case e: SparkListenerExecutorAdded => liveExecutors.contains(e.executorId)
case e: SparkListenerExecutorRemoved => liveExecutors.contains(e.executorId)
case e: SparkListenerExecutorBlacklisted => liveExecutors.contains(e.executorId)
case e: SparkListenerExecutorUnblacklisted => liveExecutors.contains(e.executorId)
case e: SparkListenerStageExecutorMetrics => liveExecutors.contains(e.execId)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's also SparkListenerBlockManagerAdded / SparkListenerBlockManagerRemoved. That has an extra complication that the driver is a block manager and generates an add event, and that one should never be filtered out.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The intention is not rejecting these kinds of events as any implementations of EventFilter don't know how to determine whether it should be accepted or not, but if we have some cases whether it should never be rejected, it would be better to explicitly accept these cases for safety.

Thanks for guiding on the case as driver being a block manager. Looking into the code of AppStatusListener, there seems to be no information to determine whether the block manager is driver or not; it seems safer to accept all.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We shouldn't be accepting block manager events for executors that are dead. That basically means that even after you compact the log files, you'll get all the executors in the UI. It defeats the filtering of the executor added / removed events.

The driver is different because it does not generate an executor added event, just a block manager added event. So when filtering block manager events you need to check whether the block manager ID refers either to the driver or a live executor.

}

override def acceptFn(): PartialFunction[SparkListenerEvent, Boolean] = {
_acceptFn.orElse(acceptFnForJobEvents)
}
}
109 changes: 109 additions & 0 deletions core/src/main/scala/org/apache/spark/deploy/history/EventFilter.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* 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.deploy.history

import scala.io.{Codec, Source}
import scala.util.control.NonFatal

import org.apache.hadoop.fs.{FileSystem, Path}
import org.json4s.jackson.JsonMethods.parse

import org.apache.spark.deploy.history.EventFilter.FilterStatistics
import org.apache.spark.internal.Logging
import org.apache.spark.scheduler._
import org.apache.spark.util.{JsonProtocol, Utils}

/**
* EventFilterBuilder provides the interface to gather the information from events being received
* by [[SparkListenerInterface]], and create a new [[EventFilter]] instance which leverages
* information gathered to decide whether the event should be accepted or not.
*/
private[spark] trait EventFilterBuilder extends SparkListenerInterface {
def createFilter(): EventFilter
}

/** [[EventFilter]] decides whether the given event should be accepted or rejected. */
private[spark] trait EventFilter {
/**
* Provide statistic information of event filter, which would be used for measuring the score
* of compaction.
*
* To simplify the condition, currently the fields of statistic are static, since major kinds of
* events compaction would filter out are job related event types. If the filter doesn't track
* with job related events, return None instead.
*/
def statistics(): Option[FilterStatistics]

/**
* Classify whether the event is accepted or rejected by this filter.
*
* The method should return the partial function which matches the events where the filter can
* decide whether the event should be accepted or rejected. Otherwise it should leave the events
* be unmatched.
*/
def acceptFn(): PartialFunction[SparkListenerEvent, Boolean]
}

object EventFilter extends Logging {
case class FilterStatistics(
totalJobs: Long,
liveJobs: Long,
totalStages: Long,
liveStages: Long,
totalTasks: Long,
liveTasks: Long)

def applyFilterToFile(
fs: FileSystem,
filters: Seq[EventFilter],
path: Path,
onAccepted: (String, SparkListenerEvent) => Unit,
onRejected: (String, SparkListenerEvent) => Unit,
onUnidentified: String => Unit): Unit = {
Utils.tryWithResource(EventLogFileReader.openEventLog(path, fs)) { in =>
val lines = Source.fromInputStream(in)(Codec.UTF8).getLines()

lines.zipWithIndex.foreach { case (line, lineNum) =>
try {
val event = try {
Some(JsonProtocol.sparkEventFromJson(parse(line)))
} catch {
// ignore any exception occurred from unidentified json
case NonFatal(_) =>
onUnidentified(line)
None
}

event.foreach { e =>
val results = filters.flatMap(_.acceptFn().lift.apply(e))
if (results.isEmpty || !results.contains(false)) {
onAccepted(line, e)
} else {
onRejected(line, e)
}
}
} catch {
case e: Exception =>
logError(s"Exception parsing Spark event log: ${path.getName}", e)
logError(s"Malformed line #$lineNum: $line\n")
throw e
}
}
}
}
}
Loading