├── NOTICE ├── resources └── images │ ├── profiling-group.gif │ ├── sample-command.gif │ └── profiling-results.gif ├── .gitignore ├── CODE_OF_CONDUCT.md ├── src ├── main │ ├── java │ │ └── software │ │ │ └── amazon │ │ │ └── profiler │ │ │ ├── utils │ │ │ └── SparkConfUtils.java │ │ │ ├── ProfilingContext.java │ │ │ ├── SparkExecutorPlugin.java │ │ │ ├── SparkDriverPlugin.java │ │ │ └── BasePlugin.java │ └── scala │ │ └── software │ │ └── amazon │ │ └── profiler │ │ ├── AmazonProfilerPlugin.scala │ │ └── SampleSparkApp.scala └── test │ └── java │ └── software │ └── amazon │ └── profiler │ ├── SparkDriverPluginTest.java │ ├── SparkExecutorPluginTest.java │ ├── ProfilingContextTest.java │ └── BasePluginTest.java ├── .github └── workflows │ └── maven-build.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md └── pom.xml /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | -------------------------------------------------------------------------------- /resources/images/profiling-group.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amzn/amazon-codeguru-profiler-for-spark/HEAD/resources/images/profiling-group.gif -------------------------------------------------------------------------------- /resources/images/sample-command.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amzn/amazon-codeguru-profiler-for-spark/HEAD/resources/images/sample-command.gif -------------------------------------------------------------------------------- /resources/images/profiling-results.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amzn/amazon-codeguru-profiler-for-spark/HEAD/resources/images/profiling-results.gif -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ 2 | *.iml 3 | *.ipr 4 | *.iws 5 | .idea 6 | */checkpoint 7 | 8 | # Maven 9 | **/target/ 10 | **/logs/ 11 | *.versionsBackup 12 | .flattened-pom.xml 13 | **/scalastyle-output.xml 14 | dependency-reduced-pom.xml 15 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/profiler/utils/SparkConfUtils.java: -------------------------------------------------------------------------------- 1 | package software.amazon.profiler.utils; 2 | 3 | import org.apache.spark.SparkConf; 4 | 5 | public class SparkConfUtils { 6 | public static String getValueFromEnvOrSparkConf(SparkConf conf, boolean isDriver, String propertyName) { 7 | String result = System.getenv(propertyName); 8 | if (result != null) { 9 | return result; 10 | } 11 | String prefix = isDriver ? "spark.yarn.appMasterEnv" : "spark.executorEnv"; 12 | return conf.get(String.format("%s.%s", prefix, propertyName), null); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /.github/workflows/maven-build.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven 3 | 4 | name: Java CI with Maven 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up JDK 8 20 | uses: actions/setup-java@v2 21 | with: 22 | java-version: '8' 23 | distribution: 'adopt' 24 | cache: maven 25 | - name: Build with Maven 26 | run: mvn -B package --file pom.xml 27 | -------------------------------------------------------------------------------- /src/main/scala/software/amazon/profiler/AmazonProfilerPlugin.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | package software.amazon.profiler 16 | 17 | import org.apache.spark.api.plugin.{DriverPlugin, ExecutorPlugin, SparkPlugin} 18 | 19 | class AmazonProfilerPlugin extends SparkPlugin { 20 | 21 | // Return the plugin's driver-side component. 22 | override def driverPlugin(): DriverPlugin = new SparkDriverPlugin() 23 | 24 | // Return the plugin's executor-side component. 25 | override def executorPlugin(): ExecutorPlugin = new SparkExecutorPlugin() 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/profiler/SparkDriverPluginTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | package software.amazon.profiler; 16 | 17 | import org.junit.jupiter.api.Test; 18 | import static org.mockito.Mockito.spy; 19 | import static org.mockito.Mockito.times; 20 | import static org.mockito.Mockito.verify; 21 | 22 | public class SparkDriverPluginTest { 23 | 24 | @Test 25 | public void testShutdown() { 26 | SparkDriverPlugin plugin = spy(SparkDriverPlugin.class); 27 | plugin.shutdown(); 28 | verify(plugin, times(1)).stopProfiler(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/profiler/SparkExecutorPluginTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | package software.amazon.profiler; 16 | 17 | import org.junit.jupiter.api.Test; 18 | import static org.mockito.Mockito.spy; 19 | import static org.mockito.Mockito.times; 20 | import static org.mockito.Mockito.verify; 21 | 22 | public class SparkExecutorPluginTest { 23 | 24 | @Test 25 | public void testShutdown() { 26 | SparkExecutorPlugin plugin = spy(SparkExecutorPlugin.class); 27 | plugin.shutdown(); 28 | verify(plugin, times(1)).stopProfiler(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/scala/software/amazon/profiler/SampleSparkApp.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | package software.amazon.profiler 16 | 17 | import java.math.BigInteger 18 | import java.util.Random 19 | 20 | import org.apache.spark.SparkContext 21 | import org.apache.spark.SparkConf 22 | 23 | object SampleSparkApp { 24 | def main(args: Array[String]) { 25 | 26 | val conf = new SparkConf().setAppName("software.amazon.profiler.SampleSparkApp") 27 | val sc = new SparkContext(conf) 28 | val rdd = sc.parallelize(1 to 12, 2) 29 | 30 | println("Simulating a CPU intensive long-running task for each executor") 31 | rdd.map(n => BigInteger.probablePrime(n*1000, new Random())).collect.foreach(println) 32 | 33 | println("Simulating a CPU intensive long-running task for the driver") 34 | println(BigInteger.probablePrime(5000, new Random())) 35 | 36 | sc.stop() 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/profiler/ProfilingContext.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | package software.amazon.profiler; 16 | 17 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 18 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 19 | import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; 20 | import lombok.AllArgsConstructor; 21 | import lombok.Builder; 22 | import lombok.Value; 23 | 24 | /** 25 | * This model class represents the profiling context of a given profiling environment. 26 | */ 27 | @Value 28 | @Builder 29 | @AllArgsConstructor 30 | @JsonDeserialize(builder = ProfilingContext.ProfilingContextBuilder.class) 31 | @JsonIgnoreProperties(ignoreUnknown = true) 32 | public final class ProfilingContext { 33 | 34 | String profilingGroupName; 35 | 36 | @Builder.Default 37 | boolean driverEnabled = false; 38 | 39 | @Builder.Default 40 | boolean executorEnabled = true; 41 | 42 | @Builder.Default 43 | boolean heapSummaryEnabled = true; 44 | 45 | @Builder.Default 46 | double probability = 1.00; 47 | 48 | @JsonPOJOBuilder(withPrefix = "") 49 | public static final class ProfilingContextBuilder { 50 | // This method declaration is needed only for the JSON annotation 51 | // lombok will fill in the implementation details 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/profiler/SparkExecutorPlugin.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | package software.amazon.profiler; 16 | 17 | import java.io.IOException; 18 | import java.util.Map; 19 | 20 | import lombok.extern.slf4j.Slf4j; 21 | import org.apache.spark.api.plugin.ExecutorPlugin; 22 | import org.apache.spark.api.plugin.PluginContext; 23 | 24 | /** 25 | * This plugin provides a way to profile Spark executor processes. 26 | */ 27 | @Slf4j 28 | public class SparkExecutorPlugin extends BasePlugin implements ExecutorPlugin { 29 | 30 | /** 31 | * Each executor process will, during its initialization, invoke this method on each plugin. 32 | */ 33 | @Override 34 | public void init(PluginContext ctx, Map extraConf) { 35 | SERVICE.submit(() -> { 36 | try { 37 | ProfilingContext context = getContext(ctx.conf(), false); 38 | if (context != null && context.isExecutorEnabled()) { 39 | log.info("Profiling context: " + context); 40 | startProfiler(context.getProfilingGroupName(), context.isHeapSummaryEnabled(), context.getProbability()); 41 | } 42 | } catch (IOException | RuntimeException e) { 43 | log.warn("Failed to start profiling in executor", e); 44 | } 45 | }); 46 | } 47 | 48 | /** 49 | * Clean up and terminate this plugin. 50 | */ 51 | @Override 52 | public void shutdown() { 53 | try { 54 | stopProfiler(); 55 | SERVICE.shutdown(); 56 | } catch (RuntimeException e) { 57 | log.warn("Failed to stop profiling in executor", e); 58 | } 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/profiler/SparkDriverPlugin.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | package software.amazon.profiler; 16 | 17 | import java.io.IOException; 18 | import java.util.Collections; 19 | import java.util.Map; 20 | 21 | import lombok.extern.slf4j.Slf4j; 22 | import org.apache.spark.SparkContext; 23 | import org.apache.spark.api.plugin.DriverPlugin; 24 | import org.apache.spark.api.plugin.PluginContext; 25 | 26 | /** 27 | * This plugin provides a way to profile a Spark driver process. 28 | */ 29 | @Slf4j 30 | public class SparkDriverPlugin extends BasePlugin implements DriverPlugin { 31 | 32 | /** 33 | * Each driver process will, during its initialization, invoke this method on each plugin. 34 | */ 35 | @Override 36 | public Map init(SparkContext sc, PluginContext pluginContext) { 37 | SERVICE.submit(() -> { 38 | try { 39 | ProfilingContext context = getContext(pluginContext.conf(), true); 40 | if (context != null && context.isDriverEnabled()) { 41 | log.info("Profiling context: " + context); 42 | startProfiler(context.getProfilingGroupName(), context.isHeapSummaryEnabled(), 1.00); 43 | } 44 | } catch (IOException | RuntimeException e) { 45 | log.warn("Failed to start profiling in driver", e); 46 | } 47 | }); 48 | return Collections.emptyMap(); 49 | } 50 | 51 | /** 52 | * Clean up and terminate this plugin. 53 | */ 54 | @Override 55 | public void shutdown() { 56 | try { 57 | stopProfiler(); 58 | SERVICE.shutdown(); 59 | } catch (RuntimeException e) { 60 | log.warn("Failed to stop profiling in driver", e); 61 | } 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/profiler/ProfilingContextTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | package software.amazon.profiler; 16 | 17 | import org.junit.jupiter.api.Test; 18 | import org.junit.jupiter.api.Assertions; 19 | 20 | public class ProfilingContextTest { 21 | 22 | @Test 23 | public void testGetProfilingGroupName() { 24 | ProfilingContext context = ProfilingContext.builder() 25 | .profilingGroupName("Sample-Spark-App-Beta") 26 | .heapSummaryEnabled(false) 27 | .build(); 28 | 29 | Assertions.assertEquals("Sample-Spark-App-Beta", context.getProfilingGroupName()); 30 | Assertions.assertFalse(context.isHeapSummaryEnabled()); 31 | } 32 | 33 | @Test 34 | public void testIsHeapSummaryEnabled() { 35 | ProfilingContext context = ProfilingContext.builder() 36 | .profilingGroupName("Sample-Spark-App-Gamma") 37 | .build(); 38 | 39 | Assertions.assertEquals("Sample-Spark-App-Gamma", context.getProfilingGroupName()); 40 | Assertions.assertTrue(context.isHeapSummaryEnabled()); 41 | } 42 | 43 | @Test 44 | public void testNullProfilingGroupName() { 45 | ProfilingContext context = ProfilingContext.builder() 46 | .build(); 47 | 48 | Assertions.assertNull(context.getProfilingGroupName()); 49 | Assertions.assertTrue(context.isHeapSummaryEnabled()); 50 | } 51 | 52 | @Test 53 | public void testDefaultProfilingGroupProbability() { 54 | ProfilingContext context = ProfilingContext.builder() 55 | .build(); 56 | 57 | Assertions.assertEquals(1.00, context.getProbability()); 58 | } 59 | 60 | @Test 61 | public void testProfilingGroupProbabilitySet() { 62 | ProfilingContext context = ProfilingContext.builder() 63 | .probability(0.05) 64 | .build(); 65 | 66 | Assertions.assertEquals(0.05, context.getProbability()); 67 | } 68 | 69 | @Test 70 | public void testProfilingGroupProbabilityOutsideNorm() { 71 | ProfilingContext context = ProfilingContext.builder() 72 | .probability(15.12) 73 | .build(); 74 | Assertions.assertEquals(15.12, context.getProbability()); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/profiler/BasePlugin.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | package software.amazon.profiler; 16 | 17 | import java.io.IOException; 18 | import java.util.Random; 19 | import java.util.concurrent.Executors; 20 | import java.util.concurrent.ExecutorService; 21 | import java.util.concurrent.ThreadLocalRandom; 22 | 23 | import com.fasterxml.jackson.databind.ObjectMapper; 24 | import lombok.extern.slf4j.Slf4j; 25 | import org.apache.spark.SparkConf; 26 | import software.amazon.codeguruprofilerjavaagent.Profiler; 27 | import software.amazon.profiler.utils.SparkConfUtils; 28 | 29 | /** 30 | * A base class interacts with AWS CodeGuru to start and stop profiling. 31 | */ 32 | @Slf4j 33 | public class BasePlugin { 34 | 35 | static final ExecutorService SERVICE = Executors.newSingleThreadExecutor(runnable -> { 36 | final Thread thread = new Thread(runnable, "Amazon-Profiler-Plugin"); 37 | // Use daemon threads to not block application shutdown 38 | thread.setDaemon(true); 39 | return thread; 40 | }); 41 | 42 | // One profiler per JVM process 43 | transient volatile Profiler _profiler; 44 | 45 | private final static Random random = ThreadLocalRandom.current(); 46 | 47 | public synchronized void startProfiler(String profilingGroupName, boolean heapSummaryEnabled, double probability) { 48 | Profiler profiler = _profiler; 49 | if (profiler == null) { 50 | if (random.nextDouble() >= probability) { 51 | log.info("Profiler is not being started for this executor. Probability {}.", probability); 52 | return; 53 | } 54 | profiler = createProfiler(profilingGroupName, heapSummaryEnabled); 55 | log.info("Profiling is being started"); 56 | profiler.start(); 57 | _profiler = profiler; 58 | } 59 | } 60 | 61 | public synchronized void stopProfiler() { 62 | Profiler profiler = _profiler; 63 | if (profiler != null && profiler.isRunning()) { 64 | profiler.stop(); 65 | log.info("Profiling is stopped"); 66 | } 67 | _profiler = null; 68 | } 69 | 70 | public Profiler createProfiler(String profilingGroupName, boolean heapSummaryEnabled) { 71 | return Profiler.builder() 72 | .profilingGroupName(profilingGroupName) 73 | .withHeapSummary(heapSummaryEnabled) 74 | .build(); 75 | } 76 | 77 | public ProfilingContext getContext(SparkConf conf, boolean isDriver) throws IOException { 78 | if ("true".equals(SparkConfUtils.getValueFromEnvOrSparkConf(conf, isDriver, "ENABLE_AMAZON_PROFILER"))) { 79 | log.info("Profiling is enabled"); 80 | String json = SparkConfUtils.getValueFromEnvOrSparkConf(conf, isDriver, "PROFILING_CONTEXT"); 81 | if (json != null) { 82 | return new ObjectMapper().readValue(json, ProfilingContext.class); 83 | } 84 | } 85 | return null; 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Context 2 | 3 | Spark 3 introduces SparkPlugin, allowing us to create a plugin which is automatically instantiated within Spark driver and executors. For each plugin specified in the `spark.plugins` configuration, an instance will be created for every executor, including those created by dynamic allocation, before the executor starts running any tasks. 4 | 5 | Given that, this package is created to enable CPU and memory profiling for any JVM based Spark app using AWS CodeGuru Profiler. With visibility into the runtime characteristics of your Spark app, you would have the opportunity to improve SLA and reduce IMR cost by identifying bottlenecks and inefficiencies from profiling results. Internally, it has helped us to identify issues like thread contentions and unnecessary expensive object creation of AWS service clients. 6 | 7 | ## License 8 | 9 | This project is licensed under the Apache-2.0 License. 10 | 11 | ## Security 12 | 13 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 14 | 15 | ## Prerequisites 16 | 17 | - Your app is built and run against Spark 3.x 18 | 19 | ### Spark on EMR 20 | 21 | - To leverage any Spark plugin, your EMR cluster needs to be run on release 6.x or newer, and `spark.plugins` needs to be specified when a Spark job is submitted. 22 | 23 | ### Spark on AWS Glue 24 | 25 | - To leverage any Spark plugin, you should be on AWS Glue 3 or Newer, and `spark.plugins` needs to be specified when Glue job is submitted. 26 | 27 | ## Onboarding Steps 28 | 29 | - Create a profiling group in CodeGuru Profiler and grant permission to your EMR EC2 role or AWS Glue Job role so that profiler agents can emit metrics to CodeGuru. Detailed instructions can be found [here](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-long.html). 30 | 31 | ![](resources/images/profiling-group.gif) 32 | 33 | ### Spark on EMR 34 | 35 | - Reference `codeguru-profiler-for-spark` via `--packages` (or `--jars`) when submitting your Spark job, along with `PROFILING_CONTEXT` and `ENABLE_AMAZON_PROFILER` defined. Below is an example where the profling group created in the previous step is assumed to be `CodeGuru-Spark-Demo`. 36 | 37 | ``` 38 | spark-submit \ 39 | --master yarn \ 40 | --deploy-mode cluster \ 41 | --class \ 42 | --packages software.amazon.profiler:codeguru-profiler-for-spark:1.0 \ 43 | --conf spark.plugins=software.amazon.profiler.AmazonProfilerPlugin \ 44 | --conf spark.executorEnv.PROFILING_CONTEXT="{\\\"profilingGroupName\\\":\\\"CodeGuru-Spark-Demo\\\"}" \ 45 | --conf spark.executorEnv.ENABLE_AMAZON_PROFILER=true \ 46 | --conf spark.yarn.appMasterEnv.PROFILING_CONTEXT="{\\\"profilingGroupName\\\":\\\"CodeGuru-Spark-Demo\\\",\\\"driverEnabled\\\":\\\"true\\\"}" \ 47 | --conf spark.yarn.appMasterEnv.ENABLE_AMAZON_PROFILER=true \ 48 | --conf spark.dynamicAllocation.enabled=false \ 49 | 50 | ``` 51 | 52 | - An alternative way to specify `PROFILING_CONTEXT` and `ENABLE_AMAZON_PROFILER` is via the AWS EMR web console. Go to the Configurations tab of your EMR cluster and configure both environment variables under the `yarn-env.export` classification for instance groups. Please note that `PROFILING_CONTEXT`, if configured in the web console, needs to escape all the commas on top of what's for the above spark-submit command. 53 | ```json 54 | [{ 55 | "classification": "yarn-env", 56 | "properties": {}, 57 | "configurations": [{ 58 | "classification": "export", 59 | "properties": { 60 | "ENABLE_AMAZON_PROFILER": "true", 61 | "PROFILING_CONTEXT": "{\\\"profilingGroupName\\\":\\\"CodeGuru-Spark-Demo\\\"\\,\\\"driverEnabled\\\":\\\"true\\\"}" 62 | }, 63 | "configurations": [] 64 | }] 65 | }] 66 | ``` 67 | 68 | ### Spark on AWS Glue 69 | 70 | - Upload `codeguru-profiler-for-apache-spark.jar` to S3 and add the jar s3 path through `--extra-jars` parameter when using AWS Glue API. More details on AWS Glue API can be found [here](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-glue-arguments.html#w6aac28c11b8c11). 71 | - Then, you need to specify the `PROFILING_CONTEXT` and `ENABLE_AMAZON_PROFILER` properties through `--conf` parameter when using AWS Glue API. A Sample value for `--conf` parameter would look like below: 72 | `spark.plugins=software.amazon.profiler.AmazonProfilerPlugin --conf spark.executorEnv.ENABLE_AMAZON_PROFILER=true --conf spark.executorEnv.PROFILING_CONTEXT={"profilingGroupName":"CodeGuru-Spark-Demo"} --conf spark.yarn.appMasterEnv.ENABLE_AMAZON_PROFILER=true --conf spark.yarn.appMasterEnv.PROFILING_CONTEXT={"profilingGroupName":"CodeGuru-Spark-Demo", "driverEnabled": "true"}`. 73 | 74 | ***Note:*** AWS Glue doesn't support passing multiple `--conf` parameters, so when you're passing more than one `--conf` parameters such as `--conf k1=v1 --conf k2=v2`, The key and value for Glue API would look like below: 75 | *Key:* `--conf` 76 | *Value:* `k1=v1 --conf k2=v2` 77 | 78 | 79 | ## Troubleshooting Tips 80 | 81 | ### Spark on EMR 82 | 83 | If profiling results do not show up in the CodeGuru web console of your AWS account, you can fire off a Spark shell from the master node of your EMR cluster and then check if your environment variables are correctly set up. For example, 84 | 85 | ``` 86 | spark-shell \ 87 | --master yarn \ 88 | --deploy-mode client \ 89 | --conf spark.plugins=software.amazon.profiler.AmazonProfilerPlugin \ 90 | --conf spark.executorEnv.PROFILING_CONTEXT="{\\\"profilingGroupName\\\":\\\"CodeGuru-Spark-Demo\\\"}" \ 91 | --conf spark.executorEnv.ENABLE_AMAZON_PROFILER=true \ 92 | --conf spark.dynamicAllocation.enabled=false \ 93 | --jars s3:///codeguru-profiler-for-spark-1.0.jar 94 | ``` 95 | 96 | ```scala 97 | scala> val rdd = sc.parallelize(1 to 3, 2) 98 | scala> rdd.map(x => System.getenv("ENABLE_AMAZON_PROFILER")).collect.foreach(println) 99 | true 100 | true 101 | true 102 | 103 | scala> rdd.map(x => System.getenv("PROFILING_CONTEXT")).collect.foreach(println) 104 | {"profilingGroupName":"CodeGuru-Spark-Demo"} 105 | {"profilingGroupName":"CodeGuru-Spark-Demo"} 106 | {"profilingGroupName":"CodeGuru-Spark-Demo"} 107 | ``` 108 | 109 | To help you with troubleshooting, this package provides a sample Spark app which you can use to check if everything is set up correctly. 110 | 111 | ``` 112 | spark-submit \ 113 | --master yarn \ 114 | --deploy-mode cluster \ 115 | --class software.amazon.profiler.SampleSparkApp \ 116 | --packages software.amazon.profiler:codeguru-profiler-for-spark:1.0 \ 117 | --conf spark.plugins=software.amazon.profiler.AmazonProfilerPlugin \ 118 | --conf spark.executorEnv.PROFILING_CONTEXT="{\\\"profilingGroupName\\\":\\\"CodeGuru-Spark-Demo\\\"}" \ 119 | --conf spark.executorEnv.ENABLE_AMAZON_PROFILER=true \ 120 | --conf spark.yarn.appMasterEnv.PROFILING_CONTEXT="{\\\"profilingGroupName\\\":\\\"CodeGuru-Spark-Demo\\\",\\\"driverEnabled\\\":\\\"true\\\"}" \ 121 | --conf spark.yarn.appMasterEnv.ENABLE_AMAZON_PROFILER=true \ 122 | --conf spark.dynamicAllocation.enabled=false \ 123 | /usr/lib/hadoop-yarn/hadoop-yarn-server-tests.jar 124 | ``` 125 | 126 | ![](resources/images/sample-command.gif) 127 | 128 | Once you run the above command from the master node of your EMR cluster, you should expect that the driver node has logs similar to 129 | 130 | ``` 131 | 21/11/21 21:27:15 INFO BasePlugin: Profiling is enabled 132 | 21/11/21 21:27:15 INFO DriverPluginContainer: Initialized driver component for plugin software.amazon.profiler.AmazonProfilerPlugin. 133 | ... 134 | 21/11/21 21:27:15 INFO SparkDriverPlugin: Profiling context: ProfilingContext(profilingGroupName=CodeGuru-Spark-Demo, driverEnabled=true, executorEnabled=true, heapSummaryEnabled=true) 135 | 21/11/21 21:27:15 INFO BasePlugin: Profiling is being started 136 | 21/11/21 21:27:15 INFO Profiler: Starting the profiler : ProfilerParameters{profilingGroupName='CodeGuru-Spark-Demo', threadSupport=BasicThreadSupport (default), excludedThreads=[Signal Dispatcher, Attach Listener], shouldProfile=true, integrationMode='', memoryUsageLimit=104857600, heapSummaryEnabled=true, stackDepthLimit=1000, samplingInterval=PT1S, reportingInterval=PT5M, addProfilerOverheadAsSamples=true, minimumTimeForReporting=PT1M, dontReportIfSampledLessThanTimes=1} 137 | 21/11/21 21:27:15 INFO ProfilingCommandExecutor: Profiling scheduled, sampling rate is PT1S 138 | ... 139 | 21/11/21 21:27:17 INFO ProfilingCommand: New agent configuration received : AgentConfiguration(AgentParameters={MaxStackDepth=1000, MinimumTimeForReportingInMilliseconds=60000, SamplingIntervalInMilliseconds=1000, MemoryUsageLimitPercent=10, ReportingIntervalInMilliseconds=300000}, PeriodInSeconds=300, ShouldProfile=true) 140 | ... 141 | 21/11/21 21:32:18 INFO ProfilingCommand: Attempting to report profile data: start=2021-11-21T21:27:17.819Z end=2021-11-21T21:32:17.738Z force=false memoryRefresh=false numberOfTimesSampled=300 142 | 21/11/21 21:32:18 INFO javaClass: [HeapSummary] Processed 12 events. 143 | 21/11/21 21:32:18 INFO ProfilingCommand: Successfully reported profile 144 | ``` 145 | 146 | You should also expect that an executor node has logs similar to 147 | 148 | ``` 149 | 21/11/21 21:27:21 INFO BasePlugin: Profiling is enabled 150 | 21/11/21 21:27:21 INFO ExecutorPluginContainer: Initialized executor component for plugin software.amazon.profiler.AmazonProfilerPlugin. 151 | 21/11/21 21:27:21 INFO SparkExecutorPlugin: Profiling context: ProfilingContext(profilingGroupName=CodeGuru-Spark-Demo, driverEnabled=false, executorEnabled=true, heapSummaryEnabled=true) 152 | 21/11/21 21:27:21 INFO YarnCoarseGrainedExecutorBackend: Got assigned task 1 153 | 21/11/21 21:27:21 INFO BasePlugin: Profiling is being started 154 | 21/11/21 21:27:21 INFO Executor: Running task 1.0 in stage 0.0 (TID 1) 155 | 21/11/21 21:27:21 INFO Profiler: Starting the profiler : ProfilerParameters{profilingGroupName='CodeGuru-Spark-Demo', threadSupport=BasicThreadSupport (default), excludedThreads=[Signal Dispatcher, Attach Listener], shouldProfile=true, integrationMode='', memoryUsageLimit=104857600, heapSummaryEnabled=true, stackDepthLimit=1000, samplingInterval=PT1S, reportingInterval=PT5M, addProfilerOverheadAsSamples=true, minimumTimeForReporting=PT1M, dontReportIfSampledLessThanTimes=1} 156 | 21/11/21 21:27:21 INFO ProfilingCommandExecutor: Profiling scheduled, sampling rate is PT1S 157 | ... 158 | 21/11/21 21:27:23 INFO ProfilingCommand: New agent configuration received : AgentConfiguration(AgentParameters={MaxStackDepth=1000, MinimumTimeForReportingInMilliseconds=60000, SamplingIntervalInMilliseconds=1000, MemoryUsageLimitPercent=10, ReportingIntervalInMilliseconds=300000}, PeriodInSeconds=300, ShouldProfile=true) 159 | 21/11/21 21:32:23 INFO ProfilingCommand: Attempting to report profile data: start=2021-11-21T21:27:23.227Z end=2021-11-21T21:32:22.765Z force=false memoryRefresh=false numberOfTimesSampled=300 160 | 21/11/21 21:32:23 INFO javaClass: [HeapSummary] Processed 20 events. 161 | 21/11/21 21:32:24 INFO ProfilingCommand: Successfully reported profile 162 | ``` 163 | 164 | ## Sample Profiling Results 165 | 166 | ![](resources/images/profiling-results.gif) 167 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/profiler/BasePluginTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | package software.amazon.profiler; 16 | 17 | import org.apache.spark.SparkConf; 18 | import software.amazon.codeguruprofilerjavaagent.Profiler; 19 | 20 | import com.github.stefanbirkner.systemlambda.SystemLambda; 21 | import org.junit.jupiter.api.Test; 22 | import org.junit.jupiter.api.Assertions; 23 | import static org.mockito.Mockito.mock; 24 | import static org.mockito.Mockito.times; 25 | import static org.mockito.Mockito.verify; 26 | import static org.mockito.Mockito.when; 27 | 28 | public class BasePluginTest { 29 | 30 | @Test 31 | public void testStartProfiler() { 32 | Profiler profiler = mock(Profiler.class); 33 | when(profiler.isRunning()).thenReturn(true); 34 | 35 | BasePlugin plugin = new BasePlugin() { 36 | @Override 37 | public Profiler createProfiler(String profilingGroupName, boolean heapSummaryEnabled) { 38 | return profiler; 39 | } 40 | }; 41 | 42 | plugin.startProfiler("Sample-Spark-App-Beta", true, 1.0); 43 | verify(profiler, times(1)).start(); 44 | Assertions.assertEquals(profiler, plugin._profiler); 45 | } 46 | 47 | @Test 48 | public void testStartProfilerZeroProbability() { 49 | Profiler profiler = mock(Profiler.class); 50 | when(profiler.isRunning()).thenReturn(true); 51 | 52 | BasePlugin plugin = new BasePlugin() { 53 | @Override 54 | public Profiler createProfiler(String profilingGroupName, boolean heapSummaryEnabled) { 55 | return profiler; 56 | } 57 | }; 58 | 59 | plugin.startProfiler("Sample-Spark-App-Beta", true, 0.00); 60 | verify(profiler, times(0)).start(); 61 | Assertions.assertNull(plugin._profiler); 62 | } 63 | 64 | @Test 65 | public void testStopProfiler() { 66 | Profiler profiler = mock(Profiler.class); 67 | when(profiler.isRunning()).thenReturn(true); 68 | 69 | BasePlugin plugin = new BasePlugin(); 70 | plugin._profiler = profiler; 71 | 72 | plugin.stopProfiler(); 73 | verify(profiler, times(1)).stop(); 74 | } 75 | 76 | @Test 77 | public void testCreateProfiler() { 78 | BasePlugin plugin = new BasePlugin(); 79 | Profiler profiler = plugin.createProfiler("Sample-Spark-App-Gamma", true); 80 | Assertions.assertFalse(profiler.isRunning()); 81 | Assertions.assertFalse(profiler.isProfiling()); 82 | } 83 | 84 | @Test 85 | public void testGetContextWithoutEnvOrSparkConfDefined() throws Exception { 86 | Assertions.assertNull(new BasePlugin().getContext(new SparkConf(), false)); 87 | } 88 | 89 | @Test 90 | public void testGetContextWithFirstEnvDefined() throws Exception { 91 | ProfilingContext context = SystemLambda.withEnvironmentVariable("ENABLE_AMAZON_PROFILER", "true") 92 | .execute(() -> new BasePlugin().getContext(new SparkConf(), false)); 93 | Assertions.assertNull(context); 94 | } 95 | 96 | @Test 97 | public void testGetContextWithEnvDefined() throws Exception { 98 | ProfilingContext context = SystemLambda.withEnvironmentVariable("ENABLE_AMAZON_PROFILER", "true") 99 | .and("PROFILING_CONTEXT", "{\"profilingGroupName\":\"Sample-Spark-App-Beta\"}") 100 | .execute(() -> new BasePlugin().getContext(new SparkConf(), false)); 101 | 102 | Assertions.assertEquals("Sample-Spark-App-Beta", context.getProfilingGroupName()); 103 | Assertions.assertFalse(context.isDriverEnabled()); 104 | Assertions.assertTrue(context.isExecutorEnabled()); 105 | Assertions.assertTrue(context.isHeapSummaryEnabled()); 106 | } 107 | 108 | @Test 109 | public void testGetContextWithAllFlagsEnabledInEnv() throws Exception { 110 | ProfilingContext context = SystemLambda.withEnvironmentVariable("ENABLE_AMAZON_PROFILER", "true") 111 | .and("PROFILING_CONTEXT", "{\"profilingGroupName\":\"Sample-Spark-App-Beta\",\"driverEnabled\":\"true\"}") 112 | .execute(() -> new BasePlugin().getContext(new SparkConf(), false)); 113 | 114 | Assertions.assertEquals("Sample-Spark-App-Beta", context.getProfilingGroupName()); 115 | Assertions.assertTrue(context.isDriverEnabled()); 116 | Assertions.assertTrue(context.isExecutorEnabled()); 117 | Assertions.assertTrue(context.isHeapSummaryEnabled()); 118 | } 119 | 120 | @Test 121 | public void testGetContextWithAllFlagsDisabledInEnv() throws Exception { 122 | ProfilingContext context = SystemLambda.withEnvironmentVariable("ENABLE_AMAZON_PROFILER", "true") 123 | .and("PROFILING_CONTEXT", "{\"profilingGroupName\":\"Sample-Spark-App-Gamma\",\"executorEnabled\":\"false\",\"heapSummaryEnabled\":\"false\"}") 124 | .execute(() -> new BasePlugin().getContext(new SparkConf(), false)); 125 | 126 | Assertions.assertEquals("Sample-Spark-App-Gamma", context.getProfilingGroupName()); 127 | Assertions.assertFalse(context.isDriverEnabled()); 128 | Assertions.assertFalse(context.isExecutorEnabled()); 129 | Assertions.assertFalse(context.isHeapSummaryEnabled()); 130 | } 131 | 132 | @Test 133 | public void testGetContextWithFirstSparkConfDefinedInExecutor() throws Exception { 134 | SparkConf sparkConf = new SparkConf(); 135 | sparkConf.set("spark.executorEnv.ENABLE_AMAZON_PROFILER", "true"); 136 | ProfilingContext context = new BasePlugin().getContext(sparkConf, false); 137 | Assertions.assertNull(context); 138 | } 139 | 140 | @Test 141 | public void testGetContextWithBothSparkConfDefinedInExecutor() throws Exception { 142 | SparkConf sparkConf = new SparkConf(); 143 | sparkConf.set("spark.executorEnv.ENABLE_AMAZON_PROFILER", "true"); 144 | sparkConf.set("spark.executorEnv.PROFILING_CONTEXT", "{\"profilingGroupName\":\"Sample-Spark-App-Beta\"}"); 145 | 146 | ProfilingContext context = new BasePlugin().getContext(sparkConf, false); 147 | 148 | Assertions.assertEquals("Sample-Spark-App-Beta", context.getProfilingGroupName()); 149 | Assertions.assertFalse(context.isDriverEnabled()); 150 | Assertions.assertTrue(context.isExecutorEnabled()); 151 | Assertions.assertTrue(context.isHeapSummaryEnabled()); 152 | } 153 | 154 | @Test 155 | public void testGetContextWithAllFlagsEnabledInSparkConfForExecutor() throws Exception { 156 | SparkConf sparkConf = new SparkConf(); 157 | sparkConf.set("spark.executorEnv.ENABLE_AMAZON_PROFILER", "true"); 158 | sparkConf.set("spark.executorEnv.PROFILING_CONTEXT", "{\"profilingGroupName\":\"Sample-Spark-App-Beta\",\"driverEnabled\":\"true\"}"); 159 | 160 | ProfilingContext context = new BasePlugin().getContext(sparkConf, false); 161 | 162 | Assertions.assertEquals("Sample-Spark-App-Beta", context.getProfilingGroupName()); 163 | Assertions.assertTrue(context.isDriverEnabled()); 164 | Assertions.assertTrue(context.isExecutorEnabled()); 165 | Assertions.assertTrue(context.isHeapSummaryEnabled()); 166 | } 167 | 168 | @Test 169 | public void testGetContextWithAllFlagsDisabledInSparkConfForExecutor() throws Exception { 170 | SparkConf sparkConf = new SparkConf(); 171 | sparkConf.set("spark.executorEnv.ENABLE_AMAZON_PROFILER", "true"); 172 | sparkConf.set("spark.executorEnv.PROFILING_CONTEXT", "{\"profilingGroupName\":\"Sample-Spark-App-Gamma\",\"executorEnabled\":\"false\",\"heapSummaryEnabled\":\"false\"}"); 173 | 174 | ProfilingContext context = new BasePlugin().getContext(sparkConf, false); 175 | 176 | Assertions.assertEquals("Sample-Spark-App-Gamma", context.getProfilingGroupName()); 177 | Assertions.assertFalse(context.isDriverEnabled()); 178 | Assertions.assertFalse(context.isExecutorEnabled()); 179 | Assertions.assertFalse(context.isHeapSummaryEnabled()); 180 | } 181 | 182 | @Test 183 | public void testGetContextWithFirstSparkConfDefinedInDriver() throws Exception { 184 | SparkConf sparkConf = new SparkConf(); 185 | sparkConf.set("spark.yarn.appMasterEnv.ENABLE_AMAZON_PROFILER", "true"); 186 | ProfilingContext context = new BasePlugin().getContext(sparkConf, true); 187 | Assertions.assertNull(context); 188 | } 189 | 190 | @Test 191 | public void testGetContextWithBothSparkConfDefinedInDriver() throws Exception { 192 | SparkConf sparkConf = new SparkConf(); 193 | sparkConf.set("spark.yarn.appMasterEnv.ENABLE_AMAZON_PROFILER", "true"); 194 | sparkConf.set("spark.yarn.appMasterEnv.PROFILING_CONTEXT", "{\"profilingGroupName\":\"Sample-Spark-App-Beta\"}"); 195 | 196 | ProfilingContext context = new BasePlugin().getContext(sparkConf, true); 197 | 198 | Assertions.assertEquals("Sample-Spark-App-Beta", context.getProfilingGroupName()); 199 | Assertions.assertFalse(context.isDriverEnabled()); 200 | Assertions.assertTrue(context.isExecutorEnabled()); 201 | Assertions.assertTrue(context.isHeapSummaryEnabled()); 202 | } 203 | 204 | @Test 205 | public void testGetContextWithAllFlagsEnabledInSparkConfForDriver() throws Exception { 206 | SparkConf sparkConf = new SparkConf(); 207 | sparkConf.set("spark.yarn.appMasterEnv.ENABLE_AMAZON_PROFILER", "true"); 208 | sparkConf.set("spark.yarn.appMasterEnv.PROFILING_CONTEXT", "{\"profilingGroupName\":\"Sample-Spark-App-Beta\",\"driverEnabled\":\"true\"}"); 209 | 210 | ProfilingContext context = new BasePlugin().getContext(sparkConf, true); 211 | 212 | Assertions.assertEquals("Sample-Spark-App-Beta", context.getProfilingGroupName()); 213 | Assertions.assertTrue(context.isDriverEnabled()); 214 | Assertions.assertTrue(context.isExecutorEnabled()); 215 | Assertions.assertTrue(context.isHeapSummaryEnabled()); 216 | } 217 | 218 | @Test 219 | public void testGetContextWithAllFlagsDisabledInSparkConfForDriver() throws Exception { 220 | SparkConf sparkConf = new SparkConf(); 221 | sparkConf.set("spark.yarn.appMasterEnv.ENABLE_AMAZON_PROFILER", "true"); 222 | sparkConf.set("spark.yarn.appMasterEnv.PROFILING_CONTEXT", "{\"profilingGroupName\":\"Sample-Spark-App-Gamma\",\"executorEnabled\":\"false\",\"heapSummaryEnabled\":\"false\"}"); 223 | 224 | ProfilingContext context = new BasePlugin().getContext(sparkConf, true); 225 | 226 | Assertions.assertEquals("Sample-Spark-App-Gamma", context.getProfilingGroupName()); 227 | Assertions.assertFalse(context.isDriverEnabled()); 228 | Assertions.assertFalse(context.isExecutorEnabled()); 229 | Assertions.assertFalse(context.isHeapSummaryEnabled()); 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | software.amazon.profiler 8 | codeguru-profiler-for-spark 9 | 1.2 10 | jar 11 | 12 | ${project.groupId}:${project.artifactId} 13 | A Spark plugin for CPU and memory profiling based on AWS CodeGuru. 14 | https://github.com/amzn/amazon-codeguru-profiler-for-spark 15 | 16 | 17 | 18 | The Apache License, Version 2.0 19 | http://www.apache.org/licenses/LICENSE-2.0.txt 20 | 21 | 22 | 23 | 24 | 25 | Bo Xiong 26 | codeguru-profiler-for-spark@amazon.com 27 | Amazon 28 | https://github.com/amzn 29 | 30 | 31 | 32 | 33 | scm:git:git@github.com/amzn/amazon-codeguru-profiler-for-spark.git 34 | scm:git:git@github.com/amzn/amazon-codeguru-profiler-for-spark.git 35 | https://github.com/amzn/amazon-codeguru-profiler-for-spark.git 36 | 37 | 38 | 39 | 40 | codeguru-profiler 41 | https://d1osg35nybn3tt.cloudfront.net 42 | 43 | 44 | 45 | 46 | UTF-8 47 | 1.8 48 | 2.12 49 | ${scala-binary.version}.8 50 | 3.4.0 51 | 1.2.2 52 | 1.7.32 53 | 1.18.22 54 | 5.8.1 55 | 1.2.0 56 | 2.21.0 57 | 3.0.8 58 | 59 | 60 | 1.9.1 61 | 1.4.0 62 | 1.0 63 | 3.2.2 64 | 3.1.0 65 | 3.0.0 66 | 3.8.1 67 | 2.19.1 68 | 3.2.4 69 | 3.1.1 70 | 3.2.1 71 | 3.2.0 72 | 2.8.2 73 | 3.9.0 74 | 1.6 75 | 3.0.0 76 | 1.6.8 77 | 78 | 79 | 80 | 81 | 82 | org.scala-lang 83 | scala-library 84 | ${scala.version} 85 | 86 | 87 | 88 | 89 | org.apache.spark 90 | spark-core_${scala-binary.version} 91 | ${spark.version} 92 | 93 | 94 | org.scala-lang 95 | scala-library 96 | 97 | 98 | 99 | 100 | 101 | 102 | com.amazonaws 103 | codeguru-profiler-java-agent 104 | ${profiler.version} 105 | 106 | 107 | 108 | 109 | org.slf4j 110 | slf4j-api 111 | ${slf4j.version} 112 | 113 | 114 | 115 | 116 | org.projectlombok 117 | lombok 118 | ${lombok.version} 119 | provided 120 | 121 | 122 | 123 | 124 | org.scalatest 125 | scalatest_${scala-binary.version} 126 | ${scalatest.version} 127 | test 128 | 129 | 130 | org.mockito 131 | mockito-core 132 | ${mockito.version} 133 | test 134 | 135 | 136 | org.junit.jupiter 137 | junit-jupiter-engine 138 | ${junit.version} 139 | test 140 | 141 | 142 | com.github.stefanbirkner 143 | system-lambda 144 | ${system-lambda.version} 145 | test 146 | 147 | 148 | 149 | 150 | 151 | 152 | src/main/resources/ 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | maven-clean-plugin 162 | ${maven-clean-plugin.version} 163 | 164 | 165 | maven-dependency-plugin 166 | ${maven-dependency-plugin.version} 167 | 168 | 169 | maven-compiler-plugin 170 | ${maven-compiler-plugin.version} 171 | 172 | 173 | maven-surefire-plugin 174 | ${maven-surefire-plugin.version} 175 | 176 | 177 | maven-shade-plugin 178 | ${maven-shade-plugin.version} 179 | 180 | 181 | maven-jar-plugin 182 | ${maven-jar-plugin.version} 183 | 184 | 185 | maven-source-plugin 186 | ${maven-source-plugin.version} 187 | 188 | 189 | maven-javadoc-plugin 190 | ${maven-javadoc-plugin.version} 191 | 192 | 193 | maven-deploy-plugin 194 | ${maven-deploy-plugin.version} 195 | 196 | 197 | maven-site-plugin 198 | ${maven-site-plugin.version} 199 | 200 | 201 | maven-gpg-plugin 202 | ${maven-gpg-plugin.version} 203 | 204 | 205 | maven-project-info-reports-plugin 206 | ${maven-project-info-reports-plugin.version} 207 | 208 | 209 | nexus-staging-maven-plugin 210 | ${nexus-staging-maven-plugin.version} 211 | 212 | 213 | 214 | 215 | 216 | 217 | org.apache.maven.plugins 218 | maven-compiler-plugin 219 | ${maven-compiler-plugin.version} 220 | 221 | ${java.version} 222 | ${java.version} 223 | 224 | 225 | 226 | 227 | net.alchim31.maven 228 | scala-maven-plugin 229 | ${scala-maven-plugin.version} 230 | 231 | 232 | 233 | compile 234 | testCompile 235 | 236 | 237 | 238 | 239 | 240 | -dependencyfile 241 | ${project.build.directory}/.scala_dependencies 242 | 243 | -nobootcp 244 | 245 | 246 | 247 | 248 | 249 | org.apache.maven.plugins 250 | maven-surefire-plugin 251 | ${maven-surefire-plugin.version} 252 | 253 | false 254 | true 255 | 256 | **/*Test.* 257 | **/*Suite.* 258 | 259 | 260 | 261 | 262 | 263 | org.apache.maven.plugins 264 | maven-jar-plugin 265 | ${maven-jar-plugin.version} 266 | 267 | 268 | 269 | true 270 | software.amazon.profiler.AmazonProfilerPlugin 271 | 272 | 273 | 274 | 275 | 276 | 277 | org.apache.maven.plugins 278 | maven-shade-plugin 279 | ${maven-shade-plugin.version} 280 | 281 | 282 | package 283 | 284 | shade 285 | 286 | 287 | 288 | 289 | io.netty:netty-all 290 | 291 | 292 | com.amazonaws:codeguru-profiler-java-agent 293 | com.amazon.ion:ion-java 294 | org.apache.httpcomponents:httpcore 295 | org.apache.httpcomponents:httpclient 296 | commons-logging:commons-logging 297 | org.reactivestreams:reactive-streams 298 | software.amazon.eventstream:eventstream 299 | org.jetbrains.kotlin:kotlin-stdlib 300 | org.jetbrains.kotlin:kotlin-stdlib-common 301 | org.jetbrains:annotations 302 | software.amazon.awssdk:* 303 | io.netty:* 304 | com.typesafe.netty:* 305 | 306 | 307 | 308 | 309 | com.amazon.ion 310 | software.amazon.profiler.shaded.com.amazon.ion 311 | 312 | 313 | org.apache.http 314 | software.amazon.profiler.shaded.org.apache.http 315 | 316 | 317 | org.apache.commons.logging 318 | software.amazon.profiler.shaded.org.apache.commons.logging 319 | 320 | 321 | org.reactivestreams 322 | software.amazon.profiler.shaded.org.reactivestreams 323 | 324 | 325 | software.amazon.eventstream 326 | software.amazon.profiler.shaded.software.amazon.eventstream 327 | 328 | 329 | kotlin 330 | software.amazon.profiler.shaded.kotlin 331 | 332 | 333 | org.intellij.lang.annotations 334 | software.amazon.profiler.shaded.org.intellij.lang.annotations 335 | 336 | 337 | org.jetbrains.annotations 338 | software.amazon.profiler.shaded.org.jetbrains.annotations 339 | 340 | 341 | software.amazon.awssdk 342 | software.amazon.profiler.shaded.software.amazon.awssdk 343 | 344 | 345 | io.netty 346 | software.amazon.profiler.shaded.io.netty 347 | 348 | 349 | com.typesafe.netty 350 | software.amazon.profiler.shaded.com.typesafe.netty 351 | 352 | 353 | 354 | 355 | *:* 356 | 357 | codegurushadow/**/* 358 | META-INF/**/* 359 | **/*.java 360 | **/*.txt 361 | **/*.json 362 | **/mime.types 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | org.apache.maven.plugins 373 | maven-dependency-plugin 374 | ${maven-dependency-plugin.version} 375 | 376 | 377 | copy-dependencies 378 | package 379 | 380 | copy-dependencies 381 | 382 | 383 | ${project.build.directory} 384 | false 385 | false 386 | true 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | org.codehaus.mojo 395 | build-helper-maven-plugin 396 | ${build-helper.version} 397 | 398 | 399 | add-source 400 | generate-sources 401 | 402 | add-source 403 | 404 | 405 | 406 | src/main/java 407 | src/main/scala 408 | 409 | 410 | 411 | 412 | add-test-source 413 | generate-sources 414 | 415 | add-test-source 416 | 417 | 418 | 419 | src/test/java 420 | src/it/java 421 | src/test/scala 422 | src/it/scala 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | org.scalatest 431 | scalatest-maven-plugin 432 | ${scalatest.plugin.version} 433 | 434 | false 435 | ${project.build.directory}/surefire-reports 436 | 437 | 438 | 439 | test 440 | 441 | test 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | org.scoverage 450 | scoverage-maven-plugin 451 | ${scoverage.plugin.version} 452 | 453 | ${scala.version} 454 | true 455 | true 456 | 90 457 | true 458 | 459 | 460 | 461 | 462 | 463 | check 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | ossrh 474 | https://aws.oss.sonatype.org/content/repositories/snapshots 475 | 476 | 477 | ossrh 478 | https://aws.oss.sonatype.org/service/local/staging/deploy/maven2/ 479 | 480 | 481 | 482 | 483 | 484 | release 485 | 486 | ${java.version} 487 | 488 | 489 | 490 | 491 | 492 | org.apache.maven.plugins 493 | maven-source-plugin 494 | ${maven-source-plugin.version} 495 | 496 | 497 | attach-sources 498 | package 499 | 500 | jar-no-fork 501 | 502 | 503 | 504 | 505 | 506 | 507 | org.apache.maven.plugins 508 | maven-javadoc-plugin 509 | ${maven-javadoc-plugin.version} 510 | 511 | 512 | attach-javadocs 513 | package 514 | 515 | jar 516 | 517 | 518 | none 519 | 520 | 521 | 522 | 523 | 524 | maven-deploy-plugin 525 | ${maven-deploy-plugin.version} 526 | 527 | 528 | deploy 529 | deploy 530 | 531 | deploy 532 | 533 | 534 | 535 | 536 | 537 | org.apache.maven.plugins 538 | maven-site-plugin 539 | ${maven-site-plugin.version} 540 | 541 | 542 | 543 | org.apache.maven.plugins 544 | maven-gpg-plugin 545 | ${maven-gpg-plugin.version} 546 | 547 | 548 | sign-artifacts 549 | verify 550 | 551 | sign 552 | 553 | 554 | 555 | 556 | 557 | 558 | org.sonatype.plugins 559 | nexus-staging-maven-plugin 560 | ${nexus-staging-maven-plugin.version} 561 | true 562 | 563 | ossrh 564 | https://aws.oss.sonatype.org/ 565 | false 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | org.apache.maven.plugins 574 | maven-project-info-reports-plugin 575 | ${maven-project-info-reports-plugin.version} 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | --------------------------------------------------------------------------------