Skip to content

Commit 9146def

Browse files
committed
SPARK-1352: Improve robustness of spark-submit script
1. Better error messages when required arguments are missing. 2. Support for unit testing cases where presented arguments are invalid. 3. Bug fix: Only use environment varaibles when they are set (otherwise will cause NPE). 4. A verbose mode to aid debugging. 5. Visibility of several variables is set to private. 6. Deprecation warning for existing scripts.
1 parent fda86d8 commit 9146def

File tree

6 files changed

+163
-48
lines changed

6 files changed

+163
-48
lines changed

core/src/main/scala/org/apache/spark/deploy/Client.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,9 @@ private class ClientActor(driverArgs: ClientArguments, conf: SparkConf) extends
128128
*/
129129
object Client {
130130
def main(args: Array[String]) {
131+
println("WARNING: This client is deprecated and will be removed in a future version of Spark.")
132+
println("Use ./bin/spark-submit with \"--master spark://host:port\"")
133+
131134
val conf = new SparkConf()
132135
val driverArgs = new ClientArguments(args)
133136

core/src/main/scala/org/apache/spark/deploy/SparkSubmit.scala

Lines changed: 43 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
package org.apache.spark.deploy
1919

20-
import java.io.File
20+
import java.io.{PrintStream, File}
2121
import java.net.URL
2222

2323
import org.apache.spark.executor.ExecutorURLClassLoader
@@ -32,38 +32,51 @@ import scala.collection.mutable.Map
3232
* modes that Spark supports.
3333
*/
3434
object SparkSubmit {
35-
val YARN = 1
36-
val STANDALONE = 2
37-
val MESOS = 4
38-
val LOCAL = 8
39-
val ALL_CLUSTER_MGRS = YARN | STANDALONE | MESOS | LOCAL
35+
private val YARN = 1
36+
private val STANDALONE = 2
37+
private val MESOS = 4
38+
private val LOCAL = 8
39+
private val ALL_CLUSTER_MGRS = YARN | STANDALONE | MESOS | LOCAL
4040

41-
var clusterManager: Int = LOCAL
41+
private var clusterManager: Int = LOCAL
4242

4343
def main(args: Array[String]) {
4444
val appArgs = new SparkSubmitArguments(args)
45+
if (appArgs.verbose) {
46+
printStream.println(appArgs)
47+
}
4548
val (childArgs, classpath, sysProps, mainClass) = createLaunchEnv(appArgs)
46-
launch(childArgs, classpath, sysProps, mainClass)
49+
launch(childArgs, classpath, sysProps, mainClass, appArgs.verbose)
4750
}
4851

52+
// Exposed for testing
53+
private[spark] var printStream: PrintStream = System.err
54+
private[spark] var exitFn: () => Unit = () => System.exit(-1)
55+
56+
private[spark] def printErrorAndExit(str: String) = {
57+
printStream.println("error: " + str)
58+
printStream.println("run with --help for more information or --verbose for debugging output")
59+
exitFn()
60+
}
61+
private[spark] def printWarning(str: String) = printStream.println("warning: " + str)
62+
4963
/**
5064
* @return
5165
* a tuple containing the arguments for the child, a list of classpath
5266
* entries for the child, and the main class for the child
5367
*/
54-
def createLaunchEnv(appArgs: SparkSubmitArguments): (ArrayBuffer[String],
68+
private[spark] def createLaunchEnv(appArgs: SparkSubmitArguments): (ArrayBuffer[String],
5569
ArrayBuffer[String], Map[String, String], String) = {
56-
if (appArgs.master.startsWith("yarn")) {
70+
if (appArgs.master.startsWith("local")) {
71+
clusterManager = LOCAL
72+
} else if (appArgs.master.startsWith("yarn")) {
5773
clusterManager = YARN
5874
} else if (appArgs.master.startsWith("spark")) {
5975
clusterManager = STANDALONE
6076
} else if (appArgs.master.startsWith("mesos")) {
6177
clusterManager = MESOS
62-
} else if (appArgs.master.startsWith("local")) {
63-
clusterManager = LOCAL
6478
} else {
65-
System.err.println("master must start with yarn, mesos, spark, or local")
66-
System.exit(1)
79+
printErrorAndExit("master must start with yarn, mesos, spark, or local")
6780
}
6881

6982
// Because "yarn-standalone" and "yarn-client" encapsulate both the master
@@ -73,12 +86,10 @@ object SparkSubmit {
7386
appArgs.deployMode = "cluster"
7487
}
7588
if (appArgs.deployMode == "cluster" && appArgs.master == "yarn-client") {
76-
System.err.println("Deploy mode \"cluster\" and master \"yarn-client\" are at odds")
77-
System.exit(1)
89+
printErrorAndExit("Deploy mode \"cluster\" and master \"yarn-client\" are not compatible")
7890
}
7991
if (appArgs.deployMode == "client" && appArgs.master == "yarn-standalone") {
80-
System.err.println("Deploy mode \"client\" and master \"yarn-standalone\" are at odds")
81-
System.exit(1)
92+
printErrorAndExit("Deploy mode \"client\" and master \"yarn-standalone\" are not compatible")
8293
}
8394
if (appArgs.deployMode == "cluster" && appArgs.master.startsWith("yarn")) {
8495
appArgs.master = "yarn-standalone"
@@ -95,8 +106,7 @@ object SparkSubmit {
95106
var childMainClass = ""
96107

97108
if (clusterManager == MESOS && deployOnCluster) {
98-
System.err.println("Mesos does not support running the driver on the cluster")
99-
System.exit(1)
109+
printErrorAndExit("Mesos does not support running the driver on the cluster")
100110
}
101111

102112
if (!deployOnCluster) {
@@ -174,8 +184,17 @@ object SparkSubmit {
174184
(childArgs, childClasspath, sysProps, childMainClass)
175185
}
176186

177-
def launch(childArgs: ArrayBuffer[String], childClasspath: ArrayBuffer[String],
178-
sysProps: Map[String, String], childMainClass: String) {
187+
private def launch(childArgs: ArrayBuffer[String], childClasspath: ArrayBuffer[String],
188+
sysProps: Map[String, String], childMainClass: String, verbose: Boolean = false) {
189+
190+
if (verbose) {
191+
System.err.println(s"Main class:\n$childMainClass")
192+
System.err.println(s"Arguments:\n${childArgs.mkString("\n")}")
193+
System.err.println(s"System properties:\n${sysProps.mkString("\n")}")
194+
System.err.println(s"Classpath elements:\n${childClasspath.mkString("\n")}")
195+
System.err.println("\n")
196+
}
197+
179198
val loader = new ExecutorURLClassLoader(new Array[URL](0),
180199
Thread.currentThread.getContextClassLoader)
181200
Thread.currentThread.setContextClassLoader(loader)
@@ -193,10 +212,10 @@ object SparkSubmit {
193212
mainMethod.invoke(null, childArgs.toArray)
194213
}
195214

196-
def addJarToClasspath(localJar: String, loader: ExecutorURLClassLoader) {
215+
private def addJarToClasspath(localJar: String, loader: ExecutorURLClassLoader) {
197216
val localJarFile = new File(localJar)
198217
if (!localJarFile.exists()) {
199-
System.err.println("Jar does not exist: " + localJar + ". Skipping.")
218+
printWarning(s"Jar $localJar does not exist, skipping.")
200219
}
201220

202221
val url = localJarFile.getAbsoluteFile.toURI.toURL

core/src/main/scala/org/apache/spark/deploy/SparkSubmitArguments.scala

Lines changed: 52 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -40,25 +40,45 @@ private[spark] class SparkSubmitArguments(args: Array[String]) {
4040
var name: String = null
4141
var childArgs: ArrayBuffer[String] = new ArrayBuffer[String]()
4242
var jars: String = null
43+
var verbose: Boolean = false
4344

4445
loadEnvVars()
45-
parseArgs(args.toList)
46-
47-
def loadEnvVars() {
48-
master = System.getenv("MASTER")
49-
deployMode = System.getenv("DEPLOY_MODE")
46+
parseOpts(args.toList)
47+
48+
// Sanity checks
49+
if (args.length == 0) printUsageAndExit(-1)
50+
if (primaryResource == null) SparkSubmit.printErrorAndExit("Must specify a primary resource")
51+
if (mainClass == null) SparkSubmit.printErrorAndExit("Must specify a main class with --class")
52+
53+
override def toString = {
54+
s"""Parsed arguments:
55+
| master $master
56+
| deployMode $deployMode
57+
| executorMemory $executorMemory
58+
| executorCores $executorCores
59+
| totalExecutorCores $totalExecutorCores
60+
| driverMemory $driverMemory
61+
| drivercores $driverCores
62+
| supervise $supervise
63+
| queue $queue
64+
| numExecutors $numExecutors
65+
| files $files
66+
| archives $archives
67+
| mainClass $mainClass
68+
| primaryResource $primaryResource
69+
| name $name
70+
| childArgs [${childArgs.mkString(" ")}]
71+
| jars $jars
72+
| verbose $verbose
73+
""".stripMargin
5074
}
5175

52-
def parseArgs(args: List[String]) {
53-
if (args.size == 0) {
54-
printUsageAndExit(1)
55-
System.exit(1)
56-
}
57-
primaryResource = args(0)
58-
parseOpts(args.tail)
76+
private def loadEnvVars() {
77+
Option(System.getenv("MASTER")).map(master = _)
78+
Option(System.getenv("DEPLOY_MODE")).map(deployMode = _)
5979
}
6080

61-
def parseOpts(opts: List[String]): Unit = opts match {
81+
private def parseOpts(opts: List[String]): Unit = opts match {
6282
case ("--name") :: value :: tail =>
6383
name = value
6484
parseOpts(tail)
@@ -73,8 +93,7 @@ private[spark] class SparkSubmitArguments(args: Array[String]) {
7393

7494
case ("--deploy-mode") :: value :: tail =>
7595
if (value != "client" && value != "cluster") {
76-
System.err.println("--deploy-mode must be either \"client\" or \"cluster\"")
77-
System.exit(1)
96+
SparkSubmit.printErrorAndExit("--deploy-mode must be either \"client\" or \"cluster\"")
7897
}
7998
deployMode = value
8099
parseOpts(tail)
@@ -130,17 +149,28 @@ private[spark] class SparkSubmitArguments(args: Array[String]) {
130149
case ("--help" | "-h") :: tail =>
131150
printUsageAndExit(0)
132151

133-
case Nil =>
152+
case ("--verbose" | "-v") :: tail =>
153+
verbose = true
154+
parseOpts(tail)
134155

135-
case _ =>
136-
printUsageAndExit(1, opts)
156+
case value :: tail =>
157+
if (primaryResource != null) {
158+
val error = s"Found two conflicting resources, $value and $primaryResource." +
159+
" Expecting only one resource."
160+
SparkSubmit.printErrorAndExit(error)
161+
}
162+
primaryResource = value
163+
parseOpts(tail)
164+
165+
case Nil =>
137166
}
138167

139-
def printUsageAndExit(exitCode: Int, unknownParam: Any = null) {
168+
private def printUsageAndExit(exitCode: Int, unknownParam: Any = null) {
169+
val outStream = SparkSubmit.printStream
140170
if (unknownParam != null) {
141-
System.err.println("Unknown/unsupported param " + unknownParam)
171+
outStream.println("Unknown/unsupported param " + unknownParam)
142172
}
143-
System.err.println(
173+
outStream.println(
144174
"""Usage: spark-submit <primary binary> [options]
145175
|Options:
146176
| --master MASTER_URL spark://host:port, mesos://host:port, yarn, or local.
@@ -171,6 +201,6 @@ private[spark] class SparkSubmitArguments(args: Array[String]) {
171201
| --archives ARCHIVES Comma separated list of archives to be extracted into the
172202
| working dir of each executor.""".stripMargin
173203
)
174-
System.exit(exitCode)
204+
SparkSubmit.exitFn()
175205
}
176206
}

core/src/test/scala/org/apache/spark/deploy/SparkSubmitSuite.scala

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,71 @@
1717

1818
package org.apache.spark.deploy
1919

20+
import java.io.{OutputStream, PrintStream}
21+
22+
import scala.collection.mutable.ArrayBuffer
23+
2024
import org.scalatest.FunSuite
2125
import org.scalatest.matchers.ShouldMatchers
26+
2227
import org.apache.spark.deploy.SparkSubmit._
2328

29+
2430
class SparkSubmitSuite extends FunSuite with ShouldMatchers {
31+
32+
val noOpOutputStream = new OutputStream {
33+
def write(b: Int) = {}
34+
}
35+
36+
/** Simple PrintStream that reads data into a buffer */
37+
class BufferPrintStream extends PrintStream(noOpOutputStream) {
38+
var lineBuffer = ArrayBuffer[String]()
39+
override def println(line: String) {
40+
lineBuffer += line
41+
}
42+
}
43+
44+
/** Returns true if the script exits and the given search string is printed. */
45+
def testPrematureExit(input: Array[String], searchString: String): Boolean = {
46+
val printStream = new BufferPrintStream()
47+
SparkSubmit.printStream = printStream
48+
49+
@volatile var exitedCleanly = false
50+
SparkSubmit.exitFn = () => exitedCleanly = true
51+
52+
val thread = new Thread {
53+
override def run() = try {
54+
SparkSubmit.main(input)
55+
} catch {
56+
// If exceptions occur after the "exit" has happened, fine to ignore them.
57+
// These represent code paths not reachable during normal execution.
58+
case e: Exception => if (!exitedCleanly) throw e
59+
}
60+
}
61+
thread.start()
62+
thread.join()
63+
printStream.lineBuffer.find(s => s.contains(searchString)).size > 0
64+
}
65+
2566
test("prints usage on empty input") {
26-
val clArgs = Array[String]()
27-
// val appArgs = new SparkSubmitArguments(clArgs)
67+
testPrematureExit(Array[String](), "Usage: spark-submit") should be (true)
68+
}
69+
70+
test("prints usage with only --help") {
71+
testPrematureExit(Array("--help"), "Usage: spark-submit") should be (true)
72+
}
73+
74+
test("handles multiple binary definitions") {
75+
val adjacentJars = Array("foo.jar", "bar.jar")
76+
testPrematureExit(adjacentJars, "error: Found two conflicting resources") should be (true)
77+
78+
val nonAdjacentJars =
79+
Array("foo.jar", "--master", "123", "--class", "abc", "bar.jar")
80+
testPrematureExit(nonAdjacentJars, "error: Found two conflicting resources") should be (true)
81+
}
82+
83+
test("handle binary specified but not class") {
84+
testPrematureExit(Array("foo.jar"), "must specify a main class")
2885
}
2986

3087
test("handles YARN cluster mode") {

yarn/alpha/src/main/scala/org/apache/spark/deploy/yarn/Client.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,9 @@ class Client(clientArgs: ClientArguments, hadoopConf: Configuration, spConf: Spa
167167
object Client {
168168

169169
def main(argStrings: Array[String]) {
170+
println("WARNING: This client is deprecated and will be removed in a future version of Spark.")
171+
println("Use ./bin/spark-submit with \"--master yarn\"")
172+
170173
// Set an env variable indicating we are running in YARN mode.
171174
// Note that anything with SPARK prefix gets propagated to all (remote) processes
172175
System.setProperty("SPARK_YARN_MODE", "true")

yarn/stable/src/main/scala/org/apache/spark/deploy/yarn/Client.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,9 @@ class Client(clientArgs: ClientArguments, hadoopConf: Configuration, spConf: Spa
173173
object Client {
174174

175175
def main(argStrings: Array[String]) {
176+
println("WARNING: This client is deprecated and will be removed in a future version of Spark.")
177+
println("Use ./bin/spark-submit with \"--master yarn\"")
178+
176179
// Set an env variable indicating we are running in YARN mode.
177180
// Note: anything env variable with SPARK_ prefix gets propagated to all (remote) processes -
178181
// see Client#setupLaunchEnv().

0 commit comments

Comments
 (0)