parthchandra commented on code in PR #44021:
URL: https://github.com/apache/spark/pull/44021#discussion_r1428532057


##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/package.scala:
##########
@@ -0,0 +1,68 @@
+/*
+ * 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.executor
+
+import org.apache.spark.internal.config.ConfigBuilder
+
+package object profiler {
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_ENABLED =
+    ConfigBuilder("spark.executor.profiling.enabled")
+      .doc("Turn on code profiling via async_profiler in executors.")
+      .version("4.0.0")
+      .booleanConf
+      .createWithDefault(false)
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_OUTPUT_DIR =
+    ConfigBuilder("spark.executor.profiling.dfsDir")
+      .doc("HDFS compatible file-system  path to where the profiler will write 
output jfr files.")

Review Comment:
   extra space removed



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorProfilerPlugin.scala:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.executor.profiler
+
+import java.util.{Map => JMap}
+
+import scala.jdk.CollectionConverters._
+import scala.util.Random
+
+import org.apache.spark.SparkConf
+import org.apache.spark.api.plugin.{DriverPlugin, ExecutorPlugin, 
PluginContext, SparkPlugin}
+import org.apache.spark.internal.Logging
+
+
+/**
+ * Spark plugin to do code profiling of executors
+ */
+class ExecutorProfilerPlugin extends SparkPlugin {
+  override def driverPlugin(): DriverPlugin = null
+
+  // No-op
+  override def executorPlugin(): ExecutorPlugin = new 
CodeProfilerExecutorPlugin
+}
+
+class CodeProfilerExecutorPlugin extends ExecutorPlugin with Logging {
+
+  private var sparkConf: SparkConf = _
+  private var pluginCtx: PluginContext = _
+  private var profiler: ExecutorJVMProfiler = _
+  private var codeProfilingEnabled: Boolean = _
+  private var codeProfilingFraction: Double = _
+  private val rand: Random = new Random(System.currentTimeMillis())
+
+  override def init(ctx: PluginContext, extraConf: JMap[String, String]): Unit 
= {
+    pluginCtx = ctx
+    sparkConf = ctx.conf()
+    codeProfilingEnabled = sparkConf.get(EXECUTOR_CODE_PROFILING_ENABLED)
+    codeProfilingFraction = sparkConf.get(EXECUTOR_CODE_PROFILING_FRACTION)

Review Comment:
   Done



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorJVMProfiler.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.executor.profiler
+
+import java.io.{BufferedInputStream, FileInputStream, InputStream}
+import java.net.URI
+import java.util.concurrent.{ScheduledExecutorService, TimeUnit}
+
+import one.profiler.{AsyncProfiler, AsyncProfilerLoader}
+import org.apache.hadoop.fs.{FileSystem, FSDataOutputStream, Path}
+
+import org.apache.spark.SparkConf
+import org.apache.spark.deploy.SparkHadoopUtil
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.ThreadUtils
+
+
+/**
+ * A class that enables the async code profiler
+ */
+private[spark] class ExecutorJVMProfiler(conf: SparkConf, executorId: String) 
extends Logging {
+
+  private var running = false
+  private val enableProfiler = conf.get(EXECUTOR_CODE_PROFILING_ENABLED)
+  private val profilerOptions = conf.get(EXECUTOR_CODE_PROFILING_OPTIONS)
+  private val profilerOutputDir = conf.get(EXECUTOR_CODE_PROFILING_OUTPUT_DIR)

Review Comment:
   Yes, of course. Done



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/package.scala:
##########
@@ -0,0 +1,68 @@
+/*
+ * 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.executor
+
+import org.apache.spark.internal.config.ConfigBuilder
+
+package object profiler {
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_ENABLED =
+    ConfigBuilder("spark.executor.profiling.enabled")
+      .doc("Turn on code profiling via async_profiler in executors.")
+      .version("4.0.0")
+      .booleanConf
+      .createWithDefault(false)
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_OUTPUT_DIR =

Review Comment:
   Done



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/package.scala:
##########
@@ -0,0 +1,68 @@
+/*
+ * 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.executor
+
+import org.apache.spark.internal.config.ConfigBuilder
+
+package object profiler {
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_ENABLED =
+    ConfigBuilder("spark.executor.profiling.enabled")
+      .doc("Turn on code profiling via async_profiler in executors.")
+      .version("4.0.0")
+      .booleanConf
+      .createWithDefault(false)
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_OUTPUT_DIR =
+    ConfigBuilder("spark.executor.profiling.dfsDir")
+      .doc("HDFS compatible file-system  path to where the profiler will write 
output jfr files.")
+      .version("4.0.0")
+      .stringConf
+      .createOptional
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_LOCAL_DIR =
+    ConfigBuilder("spark.executor.profiling.localDir")
+      .doc("Local file system path on executor where profiler output is saved. 
Defaults to the " +
+        "working directory of the executor process.")
+      .version("4.0.0")
+      .stringConf
+      .createWithDefault(".")
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_OPTIONS =
+    ConfigBuilder("spark.executor.profiling.options")
+      .doc("Options to pass on to the async profiler.")
+      .version("4.0.0")
+      .stringConf
+      
.createWithDefault("event=wall,interval=10ms,alloc=2m,lock=10ms,chunktime=300s")
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_FRACTION =
+    ConfigBuilder("spark.executor.profiling.fraction")
+      .doc("Fraction of executors to profile")
+      .version("4.0.0")
+      .doubleConf
+      .checkValue(v => v >= 0.0 && v < 1.0,
+        "Fraction of executors to profile must be in [0,1)")
+      .createWithDefault(0.1)
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_WRITE_INTERVAL =
+    ConfigBuilder("spark.executor.profiling.writeInterval")
+      .doc("Time interval in seconds after which the profiler output will be 
synced to dfs")
+      .version("4.0.0")
+      .intConf

Review Comment:
   Added the check. There is no upper time limit. 



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/package.scala:
##########
@@ -0,0 +1,68 @@
+/*
+ * 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.executor
+
+import org.apache.spark.internal.config.ConfigBuilder
+
+package object profiler {
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_ENABLED =
+    ConfigBuilder("spark.executor.profiling.enabled")
+      .doc("Turn on code profiling via async_profiler in executors.")
+      .version("4.0.0")
+      .booleanConf
+      .createWithDefault(false)
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_OUTPUT_DIR =
+    ConfigBuilder("spark.executor.profiling.dfsDir")
+      .doc("HDFS compatible file-system  path to where the profiler will write 
output jfr files.")
+      .version("4.0.0")
+      .stringConf
+      .createOptional
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_LOCAL_DIR =
+    ConfigBuilder("spark.executor.profiling.localDir")
+      .doc("Local file system path on executor where profiler output is saved. 
Defaults to the " +
+        "working directory of the executor process.")
+      .version("4.0.0")
+      .stringConf
+      .createWithDefault(".")
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_OPTIONS =
+    ConfigBuilder("spark.executor.profiling.options")
+      .doc("Options to pass on to the async profiler.")
+      .version("4.0.0")
+      .stringConf
+      
.createWithDefault("event=wall,interval=10ms,alloc=2m,lock=10ms,chunktime=300s")
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_FRACTION =
+    ConfigBuilder("spark.executor.profiling.fraction")
+      .doc("Fraction of executors to profile")
+      .version("4.0.0")
+      .doubleConf
+      .checkValue(v => v >= 0.0 && v < 1.0,
+        "Fraction of executors to profile must be in [0,1)")

Review Comment:
   Corrected to include 100%



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/package.scala:
##########
@@ -0,0 +1,68 @@
+/*
+ * 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.executor
+
+import org.apache.spark.internal.config.ConfigBuilder
+
+package object profiler {
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_ENABLED =

Review Comment:
   Okay



##########
connector/profiler/README.md:
##########
@@ -0,0 +1,109 @@
+# Spark JVM Profiler Plugin
+
+## Build
+
+To build
+```
+  ./build/mvn clean package -DskipTests -Pjvm-profiler
+```
+
+## Executor Code Profiling
+
+The spark profiler module enables code profiling of executors in cluster mode 
based on the the [async 
profiler](https://github.com/async-profiler/async-profiler/blob/v2.10/README.md),
 a low overhead sampling profiler. This allows a Spark application to capture 
CPU and memory profiles for application running on a cluster which can later be 
analyzed for performance issues. The profiler captures [Java Flight Recorder 
(jfr)](https://access.redhat.com/documentation/es-es/red_hat_build_of_openjdk/17/html/using_jdk_flight_recorder_with_red_hat_build_of_openjdk/openjdk-flight-recorded-overview)
 files for each executor; these can be read by many tools including Java 
Mission Control and Intellij.
+
+The profiler writes the jfr files to the executor's working directory in the 
executor's local file system and the files can grow to be large so it is 
advisable that the executor machines have adequate storage. The profiler can be 
configured to copy the jfr files to a hdfs location before the executor shuts 
down.
+
+Code profiling is currently only supported for
+
+*   Linux (x64)
+*   Linux (arm 64)
+*   Linux (musl, x64)
+*   MacOS
+
+To get maximum profiling information set the following jvm options for the 
executor :
+
+```
+    -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints 
-XX:+PreserveFramePointer
+```
+
+For more information on async_profiler see the [Async Profiler 
Manual](https://krzysztofslusarski.github.io/2022/12/12/async-manual.html)
+
+
+To enable code profiling, first enable the code profiling plugin via
+
+```
+spark.plugins=org.apache.spark.executor.profiler.ExecutorProfilerPlugin
+```
+
+Then enable the profiling in the configuration.
+
+
+### Code profiling configuration
+
+<table class="table">
+<tr><th>Property Name</th><th>Default</th><th>Meaning</th><th>Since 
Version</th></tr>
+<tr>
+  <td><code>spark.executor.profiling.enabled</code></td>
+  <td><code>false</code></td>
+  <td>
+    If true, will enable code profiling
+  </td>
+  <td>4.0.0</td>
+</tr>
+<tr>
+  <td><code>spark.executor.profiling.dfsDir</code></td>
+  <td>(none)</td>
+  <td>
+      An HDFS compatible path to which the profiler's output files are copied. 
The output files will be written as 
<i>dfsDir/application_id/profile-appname-exec-executor_id.jfr</i> <br/>
+      If no <i>dfsDir</i> is specified then the files are not copied over. 
Users should ensure there is sufficient disk space available otherwise it may 
lead to corrupt jfr files.
+  </td>
+  <td>4.0.0</td>
+</tr>
+<tr>
+  <td><code>spark.executor.profiling.localDir</code></td>
+  <td><code>.</code> i.e. the executor's working dir</td>
+  <td>
+   The local directory in the executor container to write the jfr files to. If 
not specified the file will be written to the executor's working directory. 
Users should ensure there is sufficient disk space available on the system as 
running out of space may result in corrupt jfr file and even cause jobs to fail 
on systems like K8s.  
+  </td>
+  <td>4.0.0</td>
+</tr>
+<tr>
+  <td><code>spark.executor.profiling.fraction</code></td>
+  <td>0.10</td>
+  <td>
+    The fraction of executors on which to enable code profiling. The executors 
to be profiled are picked at random.
+  </td>
+  <td>4.0.0</td>
+</tr>
+<tr>
+  <td><code>spark.executor.profiling.writeInterval</code></td>
+  <td>30</td>
+  <td>
+    Time interval, in seconds, after which the profiler output will be synced 
to dfs.
+  </td>
+  <td>4.0.0</td>
+</tr>
+</table>
+
+### Kubernetes
+On Kubernetes, spark will try to shut down the executor pods while the 
profiler files are still being saved. To prevent this set
+```
+  spark.kubernetes.executor.deleteOnTermination=false
+```
+
+### Example
+```
+./bin/spark-submit \
+  --class <main-class> \
+  --master <master-url> \
+  --deploy-mode <deploy-mode> \
+  -c spark.executor.extraJavaOptions="-XX:+UnlockDiagnosticVMOptions 
-XX:+DebugNonSafepoints -XX:+PreserveFramePointer" \
+  -c spark.plugins=org.apache.spark.executor.profiler.ExecutorProfilerPlugin \
+  -c spark.executor.profiling.enabled=true \
+  -c spark.executor.profiling.outputDir=s3a://my-bucket/spark/profiles/  \

Review Comment:
   Oops. Fixed.



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/package.scala:
##########
@@ -0,0 +1,68 @@
+/*
+ * 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.executor
+
+import org.apache.spark.internal.config.ConfigBuilder
+
+package object profiler {
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_ENABLED =
+    ConfigBuilder("spark.executor.profiling.enabled")
+      .doc("Turn on code profiling via async_profiler in executors.")
+      .version("4.0.0")
+      .booleanConf
+      .createWithDefault(false)
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_OUTPUT_DIR =
+    ConfigBuilder("spark.executor.profiling.dfsDir")
+      .doc("HDFS compatible file-system  path to where the profiler will write 
output jfr files.")
+      .version("4.0.0")
+      .stringConf
+      .createOptional
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_LOCAL_DIR =
+    ConfigBuilder("spark.executor.profiling.localDir")
+      .doc("Local file system path on executor where profiler output is saved. 
Defaults to the " +
+        "working directory of the executor process.")
+      .version("4.0.0")
+      .stringConf
+      .createWithDefault(".")
+
+  private[profiler] val EXECUTOR_CODE_PROFILING_OPTIONS =
+    ConfigBuilder("spark.executor.profiling.options")
+      .doc("Options to pass on to the async profiler.")

Review Comment:
   I've added a section on the options in the README. 



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorJVMProfiler.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.executor.profiler
+
+import java.io.{BufferedInputStream, FileInputStream, InputStream}
+import java.net.URI
+import java.util.concurrent.{ScheduledExecutorService, TimeUnit}
+
+import one.profiler.{AsyncProfiler, AsyncProfilerLoader}
+import org.apache.hadoop.fs.{FileSystem, FSDataOutputStream, Path}
+
+import org.apache.spark.SparkConf
+import org.apache.spark.deploy.SparkHadoopUtil
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.ThreadUtils
+
+
+/**
+ * A class that enables the async code profiler
+ */
+private[spark] class ExecutorJVMProfiler(conf: SparkConf, executorId: String) 
extends Logging {
+
+  private var running = false
+  private val enableProfiler = conf.get(EXECUTOR_CODE_PROFILING_ENABLED)
+  private val profilerOptions = conf.get(EXECUTOR_CODE_PROFILING_OPTIONS)
+  private val profilerOutputDir = conf.get(EXECUTOR_CODE_PROFILING_OUTPUT_DIR)
+  private val profilerLocalDir = conf.get(EXECUTOR_CODE_PROFILING_LOCAL_DIR)
+  private val writeInterval = conf.get(EXECUTOR_CODE_PROFILING_WRITE_INTERVAL)
+
+  private val startcmd = 
s"start,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val stopcmd = 
s"stop,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val dumpcmd = 
s"dump,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val resumecmd = 
s"resume,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+
+  private val UPLOAD_SIZE = 8 * 1024 * 1024 // 8 MB
+  private var outputStream: FSDataOutputStream = _
+  private var inputStream: InputStream = _
+  private val dataBuffer = new Array[Byte](UPLOAD_SIZE)
+  private var threadpool: ScheduledExecutorService = _
+  private var writing: Boolean = false
+
+  val profiler: AsyncProfiler = if (enableProfiler) {
+    if (AsyncProfilerLoader.isSupported) {
+      AsyncProfilerLoader.load()
+    } else {
+      logWarning("Executor code profiling is enabled but is not supported for 
this platform")
+      null
+    }
+  } else {
+    null
+  }
+
+  def start(): Unit = {
+    if (profiler != null && !running) {
+      logInfo("Executor code profiling starting.")
+      try {
+        profiler.execute(startcmd)
+      } catch {
+        case e: Exception =>
+          logWarning("Executor code profiling aborted due to exception: ", e)
+          return
+      }
+      logInfo("Executor code profiling started.")
+      running = true
+    }
+    startWriting()
+  }
+
+  /** Stops the profiling and saves output to hdfs location. */
+  def stop(): Unit = {
+    if (profiler != null && running) {
+      profiler.execute(stopcmd)
+      logInfo("Code profiler stopped")
+      running = false
+      finishWriting()
+    }
+  }
+
+  private def startWriting(): Unit = {
+    if (profilerOutputDir.isDefined) {
+      val applicationId = conf.getAppId
+      val config = SparkHadoopUtil.get.newConfiguration(conf)
+      val appName = conf.get("spark.app.name");
+      val profilerOutputDirname = profilerOutputDir.get
+      val profileOutputFile =
+        
s"$profilerOutputDirname/$applicationId/profile-$appName-exec-$executorId.jfr"
+      val fs = FileSystem.get(new URI(profileOutputFile), config);
+      val filenamePath = new Path(profileOutputFile)
+      outputStream = fs.create(filenamePath)
+      try {
+        if (fs.exists(filenamePath)) {
+          fs.delete(filenamePath, true)
+        }
+        logInfo(s"Copying executor profiling file to $profileOutputFile")
+        inputStream = new BufferedInputStream(new 
FileInputStream(s"$profilerLocalDir/profile.jfr"))
+        threadpool = 
ThreadUtils.newDaemonSingleThreadScheduledExecutor("profilerOutputThread")
+        threadpool.scheduleWithFixedDelay(new Runnable() {
+          override def run(): Unit = writeChunk()
+        }, writeInterval, writeInterval,
+          TimeUnit.SECONDS)
+        writing = true
+      } catch {
+        case e: Exception =>
+          logError("Failed to start code profiler", e)
+          if (threadpool != null) {
+            threadpool.shutdownNow()
+          }
+          if (inputStream != null) {
+            inputStream.close()
+          }
+          if (outputStream != null) {
+            outputStream.close()
+          }
+      }
+    }
+  }
+
+  private def writeChunk(): Unit = {
+    if (!writing) {
+      return
+    }
+    try {
+      // stop (pause) the profiler, dump the results and then resume. This is 
not ideal as we miss
+      // the events while the file is being dumped, but that is the only way 
to make sure that
+      // the chunk of data we are copying to dfs is in a consistent state.
+      profiler.execute(stopcmd)
+      profiler.execute(dumpcmd)
+      var remaining = inputStream.available()
+      profiler.execute(resumecmd)
+      while (remaining > 0) {
+        val read = inputStream.read(dataBuffer, 0, math.min(remaining, 
UPLOAD_SIZE))
+        outputStream.write(dataBuffer, 0, read)
+        remaining -= read
+      }
+    } catch {
+      case e: Exception => logError("Exception occurred while writing profiler 
output", e)
+    }
+  }
+
+  private def finishWriting(): Unit = {
+    if (profilerOutputDir.isDefined && writing) {
+      try {
+        // shutdown background writer
+        threadpool.shutdown()
+        threadpool.awaitTermination(30, TimeUnit.SECONDS)
+        // flush remaining data
+        writeChunk()
+        inputStream.close()
+        outputStream.close()
+      } catch {
+        case e: Exception =>

Review Comment:
   I've added more specific handling.



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorProfilerPlugin.scala:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.executor.profiler
+
+import java.util.{Map => JMap}
+
+import scala.jdk.CollectionConverters._
+import scala.util.Random
+
+import org.apache.spark.SparkConf
+import org.apache.spark.api.plugin.{DriverPlugin, ExecutorPlugin, 
PluginContext, SparkPlugin}
+import org.apache.spark.internal.Logging
+
+
+/**
+ * Spark plugin to do code profiling of executors

Review Comment:
   Done



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorProfilerPlugin.scala:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.executor.profiler
+
+import java.util.{Map => JMap}
+
+import scala.jdk.CollectionConverters._
+import scala.util.Random
+
+import org.apache.spark.SparkConf
+import org.apache.spark.api.plugin.{DriverPlugin, ExecutorPlugin, 
PluginContext, SparkPlugin}
+import org.apache.spark.internal.Logging
+
+
+/**
+ * Spark plugin to do code profiling of executors
+ */
+class ExecutorProfilerPlugin extends SparkPlugin {
+  override def driverPlugin(): DriverPlugin = null
+
+  // No-op
+  override def executorPlugin(): ExecutorPlugin = new 
CodeProfilerExecutorPlugin
+}
+
+class CodeProfilerExecutorPlugin extends ExecutorPlugin with Logging {

Review Comment:
   Sure



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorJVMProfiler.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.executor.profiler
+
+import java.io.{BufferedInputStream, FileInputStream, InputStream}
+import java.net.URI
+import java.util.concurrent.{ScheduledExecutorService, TimeUnit}
+
+import one.profiler.{AsyncProfiler, AsyncProfilerLoader}
+import org.apache.hadoop.fs.{FileSystem, FSDataOutputStream, Path}
+
+import org.apache.spark.SparkConf
+import org.apache.spark.deploy.SparkHadoopUtil
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.ThreadUtils
+
+
+/**
+ * A class that enables the async code profiler
+ */
+private[spark] class ExecutorJVMProfiler(conf: SparkConf, executorId: String) 
extends Logging {
+
+  private var running = false
+  private val enableProfiler = conf.get(EXECUTOR_CODE_PROFILING_ENABLED)
+  private val profilerOptions = conf.get(EXECUTOR_CODE_PROFILING_OPTIONS)
+  private val profilerOutputDir = conf.get(EXECUTOR_CODE_PROFILING_OUTPUT_DIR)
+  private val profilerLocalDir = conf.get(EXECUTOR_CODE_PROFILING_LOCAL_DIR)
+  private val writeInterval = conf.get(EXECUTOR_CODE_PROFILING_WRITE_INTERVAL)
+
+  private val startcmd = 
s"start,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val stopcmd = 
s"stop,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val dumpcmd = 
s"dump,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val resumecmd = 
s"resume,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+
+  private val UPLOAD_SIZE = 8 * 1024 * 1024 // 8 MB
+  private var outputStream: FSDataOutputStream = _
+  private var inputStream: InputStream = _
+  private val dataBuffer = new Array[Byte](UPLOAD_SIZE)
+  private var threadpool: ScheduledExecutorService = _
+  private var writing: Boolean = false
+
+  val profiler: AsyncProfiler = if (enableProfiler) {

Review Comment:
   Changed to use Option



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorJVMProfiler.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.executor.profiler
+
+import java.io.{BufferedInputStream, FileInputStream, InputStream}
+import java.net.URI
+import java.util.concurrent.{ScheduledExecutorService, TimeUnit}
+
+import one.profiler.{AsyncProfiler, AsyncProfilerLoader}
+import org.apache.hadoop.fs.{FileSystem, FSDataOutputStream, Path}
+
+import org.apache.spark.SparkConf
+import org.apache.spark.deploy.SparkHadoopUtil
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.ThreadUtils
+
+
+/**
+ * A class that enables the async code profiler
+ */
+private[spark] class ExecutorJVMProfiler(conf: SparkConf, executorId: String) 
extends Logging {
+
+  private var running = false
+  private val enableProfiler = conf.get(EXECUTOR_CODE_PROFILING_ENABLED)
+  private val profilerOptions = conf.get(EXECUTOR_CODE_PROFILING_OPTIONS)
+  private val profilerOutputDir = conf.get(EXECUTOR_CODE_PROFILING_OUTPUT_DIR)
+  private val profilerLocalDir = conf.get(EXECUTOR_CODE_PROFILING_LOCAL_DIR)
+  private val writeInterval = conf.get(EXECUTOR_CODE_PROFILING_WRITE_INTERVAL)
+
+  private val startcmd = 
s"start,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val stopcmd = 
s"stop,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val dumpcmd = 
s"dump,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val resumecmd = 
s"resume,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+
+  private val UPLOAD_SIZE = 8 * 1024 * 1024 // 8 MB
+  private var outputStream: FSDataOutputStream = _
+  private var inputStream: InputStream = _
+  private val dataBuffer = new Array[Byte](UPLOAD_SIZE)
+  private var threadpool: ScheduledExecutorService = _
+  private var writing: Boolean = false
+
+  val profiler: AsyncProfiler = if (enableProfiler) {
+    if (AsyncProfilerLoader.isSupported) {
+      AsyncProfilerLoader.load()
+    } else {
+      logWarning("Executor code profiling is enabled but is not supported for 
this platform")
+      null
+    }
+  } else {
+    null
+  }
+
+  def start(): Unit = {
+    if (profiler != null && !running) {

Review Comment:
   Done



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorJVMProfiler.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.executor.profiler
+
+import java.io.{BufferedInputStream, FileInputStream, InputStream}
+import java.net.URI
+import java.util.concurrent.{ScheduledExecutorService, TimeUnit}
+
+import one.profiler.{AsyncProfiler, AsyncProfilerLoader}
+import org.apache.hadoop.fs.{FileSystem, FSDataOutputStream, Path}
+
+import org.apache.spark.SparkConf
+import org.apache.spark.deploy.SparkHadoopUtil
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.ThreadUtils
+
+
+/**
+ * A class that enables the async code profiler
+ */
+private[spark] class ExecutorJVMProfiler(conf: SparkConf, executorId: String) 
extends Logging {
+
+  private var running = false
+  private val enableProfiler = conf.get(EXECUTOR_CODE_PROFILING_ENABLED)
+  private val profilerOptions = conf.get(EXECUTOR_CODE_PROFILING_OPTIONS)
+  private val profilerOutputDir = conf.get(EXECUTOR_CODE_PROFILING_OUTPUT_DIR)
+  private val profilerLocalDir = conf.get(EXECUTOR_CODE_PROFILING_LOCAL_DIR)
+  private val writeInterval = conf.get(EXECUTOR_CODE_PROFILING_WRITE_INTERVAL)
+
+  private val startcmd = 
s"start,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val stopcmd = 
s"stop,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val dumpcmd = 
s"dump,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val resumecmd = 
s"resume,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+
+  private val UPLOAD_SIZE = 8 * 1024 * 1024 // 8 MB
+  private var outputStream: FSDataOutputStream = _
+  private var inputStream: InputStream = _
+  private val dataBuffer = new Array[Byte](UPLOAD_SIZE)
+  private var threadpool: ScheduledExecutorService = _
+  private var writing: Boolean = false
+
+  val profiler: AsyncProfiler = if (enableProfiler) {
+    if (AsyncProfilerLoader.isSupported) {
+      AsyncProfilerLoader.load()
+    } else {
+      logWarning("Executor code profiling is enabled but is not supported for 
this platform")
+      null
+    }
+  } else {
+    null
+  }
+
+  def start(): Unit = {
+    if (profiler != null && !running) {
+      logInfo("Executor code profiling starting.")
+      try {
+        profiler.execute(startcmd)
+      } catch {
+        case e: Exception =>
+          logWarning("Executor code profiling aborted due to exception: ", e)
+          return
+      }
+      logInfo("Executor code profiling started.")
+      running = true
+    }
+    startWriting()
+  }
+
+  /** Stops the profiling and saves output to hdfs location. */
+  def stop(): Unit = {
+    if (profiler != null && running) {
+      profiler.execute(stopcmd)
+      logInfo("Code profiler stopped")
+      running = false
+      finishWriting()
+    }
+  }
+
+  private def startWriting(): Unit = {
+    if (profilerOutputDir.isDefined) {
+      val applicationId = conf.getAppId
+      val config = SparkHadoopUtil.get.newConfiguration(conf)
+      val appName = conf.get("spark.app.name");
+      val profilerOutputDirname = profilerOutputDir.get
+      val profileOutputFile =
+        
s"$profilerOutputDirname/$applicationId/profile-$appName-exec-$executorId.jfr"
+      val fs = FileSystem.get(new URI(profileOutputFile), config);
+      val filenamePath = new Path(profileOutputFile)
+      outputStream = fs.create(filenamePath)
+      try {
+        if (fs.exists(filenamePath)) {
+          fs.delete(filenamePath, true)
+        }
+        logInfo(s"Copying executor profiling file to $profileOutputFile")
+        inputStream = new BufferedInputStream(new 
FileInputStream(s"$profilerLocalDir/profile.jfr"))
+        threadpool = 
ThreadUtils.newDaemonSingleThreadScheduledExecutor("profilerOutputThread")
+        threadpool.scheduleWithFixedDelay(new Runnable() {
+          override def run(): Unit = writeChunk()
+        }, writeInterval, writeInterval,
+          TimeUnit.SECONDS)
+        writing = true
+      } catch {
+        case e: Exception =>
+          logError("Failed to start code profiler", e)
+          if (threadpool != null) {
+            threadpool.shutdownNow()
+          }
+          if (inputStream != null) {
+            inputStream.close()
+          }
+          if (outputStream != null) {
+            outputStream.close()
+          }
+      }
+    }
+  }
+
+  private def writeChunk(): Unit = {
+    if (!writing) {
+      return
+    }
+    try {
+      // stop (pause) the profiler, dump the results and then resume. This is 
not ideal as we miss
+      // the events while the file is being dumped, but that is the only way 
to make sure that
+      // the chunk of data we are copying to dfs is in a consistent state.
+      profiler.execute(stopcmd)
+      profiler.execute(dumpcmd)
+      var remaining = inputStream.available()
+      profiler.execute(resumecmd)
+      while (remaining > 0) {
+        val read = inputStream.read(dataBuffer, 0, math.min(remaining, 
UPLOAD_SIZE))
+        outputStream.write(dataBuffer, 0, read)
+        remaining -= read
+      }
+    } catch {
+      case e: Exception => logError("Exception occurred while writing profiler 
output", e)
+    }
+  }
+
+  private def finishWriting(): Unit = {
+    if (profilerOutputDir.isDefined && writing) {
+      try {
+        // shutdown background writer
+        threadpool.shutdown()
+        threadpool.awaitTermination(30, TimeUnit.SECONDS)
+        // flush remaining data
+        writeChunk()
+        inputStream.close()
+        outputStream.close()
+      } catch {
+        case e: Exception =>
+          logError("Exception in completing profiler output", e)

Review Comment:
   Made it a little more descriptive.



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorJVMProfiler.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.executor.profiler
+
+import java.io.{BufferedInputStream, FileInputStream, InputStream}
+import java.net.URI
+import java.util.concurrent.{ScheduledExecutorService, TimeUnit}
+
+import one.profiler.{AsyncProfiler, AsyncProfilerLoader}
+import org.apache.hadoop.fs.{FileSystem, FSDataOutputStream, Path}
+
+import org.apache.spark.SparkConf
+import org.apache.spark.deploy.SparkHadoopUtil
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.ThreadUtils
+
+
+/**
+ * A class that enables the async code profiler
+ */
+private[spark] class ExecutorJVMProfiler(conf: SparkConf, executorId: String) 
extends Logging {
+
+  private var running = false
+  private val enableProfiler = conf.get(EXECUTOR_CODE_PROFILING_ENABLED)
+  private val profilerOptions = conf.get(EXECUTOR_CODE_PROFILING_OPTIONS)
+  private val profilerOutputDir = conf.get(EXECUTOR_CODE_PROFILING_OUTPUT_DIR)
+  private val profilerLocalDir = conf.get(EXECUTOR_CODE_PROFILING_LOCAL_DIR)
+  private val writeInterval = conf.get(EXECUTOR_CODE_PROFILING_WRITE_INTERVAL)
+
+  private val startcmd = 
s"start,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val stopcmd = 
s"stop,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val dumpcmd = 
s"dump,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val resumecmd = 
s"resume,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+
+  private val UPLOAD_SIZE = 8 * 1024 * 1024 // 8 MB
+  private var outputStream: FSDataOutputStream = _
+  private var inputStream: InputStream = _
+  private val dataBuffer = new Array[Byte](UPLOAD_SIZE)
+  private var threadpool: ScheduledExecutorService = _
+  private var writing: Boolean = false
+
+  val profiler: AsyncProfiler = if (enableProfiler) {
+    if (AsyncProfilerLoader.isSupported) {
+      AsyncProfilerLoader.load()
+    } else {
+      logWarning("Executor code profiling is enabled but is not supported for 
this platform")
+      null
+    }
+  } else {
+    null
+  }
+
+  def start(): Unit = {
+    if (profiler != null && !running) {
+      logInfo("Executor code profiling starting.")
+      try {
+        profiler.execute(startcmd)
+      } catch {
+        case e: Exception =>
+          logWarning("Executor code profiling aborted due to exception: ", e)
+          return

Review Comment:
   If the profiler fails to start we don't want the job to fail, so I feel it 
is better to log a warning and keep going.
   



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorJVMProfiler.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.executor.profiler
+
+import java.io.{BufferedInputStream, FileInputStream, InputStream}
+import java.net.URI
+import java.util.concurrent.{ScheduledExecutorService, TimeUnit}
+
+import one.profiler.{AsyncProfiler, AsyncProfilerLoader}
+import org.apache.hadoop.fs.{FileSystem, FSDataOutputStream, Path}
+
+import org.apache.spark.SparkConf
+import org.apache.spark.deploy.SparkHadoopUtil
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.ThreadUtils
+
+
+/**
+ * A class that enables the async code profiler
+ */
+private[spark] class ExecutorJVMProfiler(conf: SparkConf, executorId: String) 
extends Logging {
+
+  private var running = false
+  private val enableProfiler = conf.get(EXECUTOR_CODE_PROFILING_ENABLED)
+  private val profilerOptions = conf.get(EXECUTOR_CODE_PROFILING_OPTIONS)
+  private val profilerOutputDir = conf.get(EXECUTOR_CODE_PROFILING_OUTPUT_DIR)
+  private val profilerLocalDir = conf.get(EXECUTOR_CODE_PROFILING_LOCAL_DIR)
+  private val writeInterval = conf.get(EXECUTOR_CODE_PROFILING_WRITE_INTERVAL)
+
+  private val startcmd = 
s"start,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val stopcmd = 
s"stop,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val dumpcmd = 
s"dump,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val resumecmd = 
s"resume,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+
+  private val UPLOAD_SIZE = 8 * 1024 * 1024 // 8 MB
+  private var outputStream: FSDataOutputStream = _
+  private var inputStream: InputStream = _
+  private val dataBuffer = new Array[Byte](UPLOAD_SIZE)
+  private var threadpool: ScheduledExecutorService = _
+  private var writing: Boolean = false
+
+  val profiler: AsyncProfiler = if (enableProfiler) {
+    if (AsyncProfilerLoader.isSupported) {
+      AsyncProfilerLoader.load()
+    } else {
+      logWarning("Executor code profiling is enabled but is not supported for 
this platform")
+      null
+    }
+  } else {
+    null
+  }
+
+  def start(): Unit = {
+    if (profiler != null && !running) {
+      logInfo("Executor code profiling starting.")
+      try {
+        profiler.execute(startcmd)
+      } catch {
+        case e: Exception =>
+          logWarning("Executor code profiling aborted due to exception: ", e)
+          return
+      }
+      logInfo("Executor code profiling started.")
+      running = true
+    }
+    startWriting()
+  }
+
+  /** Stops the profiling and saves output to hdfs location. */

Review Comment:
   changed



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorJVMProfiler.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.executor.profiler
+
+import java.io.{BufferedInputStream, FileInputStream, InputStream}
+import java.net.URI
+import java.util.concurrent.{ScheduledExecutorService, TimeUnit}
+
+import one.profiler.{AsyncProfiler, AsyncProfilerLoader}
+import org.apache.hadoop.fs.{FileSystem, FSDataOutputStream, Path}
+
+import org.apache.spark.SparkConf
+import org.apache.spark.deploy.SparkHadoopUtil
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.ThreadUtils
+
+
+/**
+ * A class that enables the async code profiler
+ */
+private[spark] class ExecutorJVMProfiler(conf: SparkConf, executorId: String) 
extends Logging {
+
+  private var running = false
+  private val enableProfiler = conf.get(EXECUTOR_CODE_PROFILING_ENABLED)
+  private val profilerOptions = conf.get(EXECUTOR_CODE_PROFILING_OPTIONS)
+  private val profilerOutputDir = conf.get(EXECUTOR_CODE_PROFILING_OUTPUT_DIR)
+  private val profilerLocalDir = conf.get(EXECUTOR_CODE_PROFILING_LOCAL_DIR)
+  private val writeInterval = conf.get(EXECUTOR_CODE_PROFILING_WRITE_INTERVAL)
+
+  private val startcmd = 
s"start,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val stopcmd = 
s"stop,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val dumpcmd = 
s"dump,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val resumecmd = 
s"resume,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+
+  private val UPLOAD_SIZE = 8 * 1024 * 1024 // 8 MB
+  private var outputStream: FSDataOutputStream = _
+  private var inputStream: InputStream = _
+  private val dataBuffer = new Array[Byte](UPLOAD_SIZE)
+  private var threadpool: ScheduledExecutorService = _
+  private var writing: Boolean = false
+
+  val profiler: AsyncProfiler = if (enableProfiler) {
+    if (AsyncProfilerLoader.isSupported) {
+      AsyncProfilerLoader.load()
+    } else {
+      logWarning("Executor code profiling is enabled but is not supported for 
this platform")
+      null
+    }
+  } else {
+    null
+  }
+
+  def start(): Unit = {
+    if (profiler != null && !running) {
+      logInfo("Executor code profiling starting.")
+      try {
+        profiler.execute(startcmd)
+      } catch {
+        case e: Exception =>

Review Comment:
   We really want to catch all exceptions here. Irrespective of what the 
exception was, we want to log it (so user can  take corrective action) but we 
don't want the job to fail.
   I'm now checking for the specific exceptions thrown by the profiler but am 
also catching any other exceptions



##########
connector/profiler/src/main/scala/org/apache/spark/executor/profiler/ExecutorJVMProfiler.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.executor.profiler
+
+import java.io.{BufferedInputStream, FileInputStream, InputStream}
+import java.net.URI
+import java.util.concurrent.{ScheduledExecutorService, TimeUnit}
+
+import one.profiler.{AsyncProfiler, AsyncProfilerLoader}
+import org.apache.hadoop.fs.{FileSystem, FSDataOutputStream, Path}
+
+import org.apache.spark.SparkConf
+import org.apache.spark.deploy.SparkHadoopUtil
+import org.apache.spark.internal.Logging
+import org.apache.spark.util.ThreadUtils
+
+
+/**
+ * A class that enables the async code profiler
+ */
+private[spark] class ExecutorJVMProfiler(conf: SparkConf, executorId: String) 
extends Logging {
+
+  private var running = false
+  private val enableProfiler = conf.get(EXECUTOR_CODE_PROFILING_ENABLED)
+  private val profilerOptions = conf.get(EXECUTOR_CODE_PROFILING_OPTIONS)
+  private val profilerOutputDir = conf.get(EXECUTOR_CODE_PROFILING_OUTPUT_DIR)
+  private val profilerLocalDir = conf.get(EXECUTOR_CODE_PROFILING_LOCAL_DIR)
+  private val writeInterval = conf.get(EXECUTOR_CODE_PROFILING_WRITE_INTERVAL)
+
+  private val startcmd = 
s"start,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val stopcmd = 
s"stop,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val dumpcmd = 
s"dump,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+  private val resumecmd = 
s"resume,$profilerOptions,file=$profilerLocalDir/profile.jfr"
+
+  private val UPLOAD_SIZE = 8 * 1024 * 1024 // 8 MB
+  private var outputStream: FSDataOutputStream = _
+  private var inputStream: InputStream = _
+  private val dataBuffer = new Array[Byte](UPLOAD_SIZE)
+  private var threadpool: ScheduledExecutorService = _
+  private var writing: Boolean = false
+
+  val profiler: AsyncProfiler = if (enableProfiler) {
+    if (AsyncProfilerLoader.isSupported) {
+      AsyncProfilerLoader.load()
+    } else {
+      logWarning("Executor code profiling is enabled but is not supported for 
this platform")
+      null
+    }
+  } else {
+    null
+  }
+
+  def start(): Unit = {
+    if (profiler != null && !running) {
+      logInfo("Executor code profiling starting.")
+      try {
+        profiler.execute(startcmd)
+      } catch {
+        case e: Exception =>
+          logWarning("Executor code profiling aborted due to exception: ", e)
+          return
+      }
+      logInfo("Executor code profiling started.")
+      running = true
+    }
+    startWriting()
+  }
+
+  /** Stops the profiling and saves output to hdfs location. */
+  def stop(): Unit = {
+    if (profiler != null && running) {
+      profiler.execute(stopcmd)
+      logInfo("Code profiler stopped")

Review Comment:
   Of course



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


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

Reply via email to