aboutsummaryrefslogtreecommitdiff
path: root/yarn/common/src/main/scala/org/apache/spark/scheduler/cluster/YarnClientSchedulerBackend.scala
blob: 6aa6475fe4a1899791b661f29adf704230a89113 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/*
 * 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.scheduler.cluster

import org.apache.hadoop.yarn.api.records.{ApplicationId, YarnApplicationState}
import org.apache.spark.{SparkException, Logging, SparkContext}
import org.apache.spark.deploy.yarn.{Client, ClientArguments, YarnSparkHadoopUtil}
import org.apache.spark.scheduler.TaskSchedulerImpl

import scala.collection.mutable.ArrayBuffer

private[spark] class YarnClientSchedulerBackend(
    scheduler: TaskSchedulerImpl,
    sc: SparkContext)
  extends CoarseGrainedSchedulerBackend(scheduler, sc.env.actorSystem)
  with Logging {

  if (conf.getOption("spark.scheduler.minRegisteredResourcesRatio").isEmpty) {
    minRegisteredRatio = 0.8
  }

  var client: Client = null
  var appId: ApplicationId = null
  var checkerThread: Thread = null
  var stopping: Boolean = false
  var totalExpectedExecutors = 0

  private[spark] def addArg(optionName: String, envVar: String, sysProp: String,
      arrayBuf: ArrayBuffer[String]) {
    if (System.getenv(envVar) != null) {
      arrayBuf += (optionName, System.getenv(envVar))
    } else if (sc.getConf.contains(sysProp)) {
      arrayBuf += (optionName, sc.getConf.get(sysProp))
    }
  }

  override def start() {
    super.start()

    val driverHost = conf.get("spark.driver.host")
    val driverPort = conf.get("spark.driver.port")
    val hostport = driverHost + ":" + driverPort
    sc.ui.foreach { ui => conf.set("spark.driver.appUIAddress", ui.appUIHostPort) }

    val argsArrayBuf = new ArrayBuffer[String]()
    argsArrayBuf += (
      "--args", hostport
    )

    // process any optional arguments, given either as environment variables
    // or system properties. use the defaults already defined in ClientArguments
    // if things aren't specified. system properties override environment
    // variables.
    List(("--driver-memory", "SPARK_MASTER_MEMORY", "spark.master.memory"),
      ("--driver-memory", "SPARK_DRIVER_MEMORY", "spark.driver.memory"),
      ("--num-executors", "SPARK_WORKER_INSTANCES", "spark.executor.instances"),
      ("--num-executors", "SPARK_EXECUTOR_INSTANCES", "spark.executor.instances"),
      ("--executor-memory", "SPARK_WORKER_MEMORY", "spark.executor.memory"),
      ("--executor-memory", "SPARK_EXECUTOR_MEMORY", "spark.executor.memory"),
      ("--executor-cores", "SPARK_WORKER_CORES", "spark.executor.cores"),
      ("--executor-cores", "SPARK_EXECUTOR_CORES", "spark.executor.cores"),
      ("--queue", "SPARK_YARN_QUEUE", "spark.yarn.queue"),
      ("--name", "SPARK_YARN_APP_NAME", "spark.app.name"))
    .foreach { case (optName, envVar, sysProp) => addArg(optName, envVar, sysProp, argsArrayBuf) }

    logDebug("ClientArguments called with: " + argsArrayBuf)
    val args = new ClientArguments(argsArrayBuf.toArray, conf)
    totalExpectedExecutors = args.numExecutors
    client = new Client(args, conf)
    appId = client.runApp()
    waitForApp()
    checkerThread = yarnApplicationStateCheckerThread()
  }

  def waitForApp() {

    // TODO : need a better way to find out whether the executors are ready or not
    // maybe by resource usage report?
    while(true) {
      val report = client.getApplicationReport(appId)

      logInfo("Application report from ASM: \n" +
        "\t appMasterRpcPort: " + report.getRpcPort() + "\n" +
        "\t appStartTime: " + report.getStartTime() + "\n" +
        "\t yarnAppState: " + report.getYarnApplicationState() + "\n"
      )

      // Ready to go, or already gone.
      val state = report.getYarnApplicationState()
      if (state == YarnApplicationState.RUNNING) {
        return
      } else if (state == YarnApplicationState.FINISHED ||
        state == YarnApplicationState.FAILED ||
        state == YarnApplicationState.KILLED) {
        throw new SparkException("Yarn application already ended," +
          "might be killed or not able to launch application master.")
      }

      Thread.sleep(1000)
    }
  }

  private def yarnApplicationStateCheckerThread(): Thread = {
    val t = new Thread {
      override def run() {
        while (!stopping) {
          val report = client.getApplicationReport(appId)
          val state = report.getYarnApplicationState()
          if (state == YarnApplicationState.FINISHED || state == YarnApplicationState.KILLED
            || state == YarnApplicationState.FAILED) {
            logError(s"Yarn application already ended: $state")
            sc.stop()
            stopping = true
          }
          Thread.sleep(1000L)
        }
        checkerThread = null
        Thread.currentThread().interrupt()
      }
    }
    t.setName("Yarn Application State Checker")
    t.setDaemon(true)
    t.start()
    t
  }

  override def stop() {
    stopping = true
    super.stop()
    client.stop
    logInfo("Stopped")
  }

  override def sufficientResourcesRegistered(): Boolean = {
    totalRegisteredExecutors.get() >= totalExpectedExecutors * minRegisteredRatio
  }

  override def applicationId(): Option[String] = Option(appId).map(_.toString())

}