You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@livy.apache.org by GitBox <gi...@apache.org> on 2019/11/02 11:56:15 UTC

[GitHub] [incubator-livy] jahstreet commented on a change in pull request #249: [LIVY-702]: Submit Spark apps to Kubernetes

jahstreet commented on a change in pull request #249: [LIVY-702]: Submit Spark apps to Kubernetes
URL: https://github.com/apache/incubator-livy/pull/249#discussion_r341379306
 
 

 ##########
 File path: server/src/main/scala/org/apache/livy/utils/SparkKubernetesApp.scala
 ##########
 @@ -0,0 +1,458 @@
+/*
+ * 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.livy.utils
+
+import java.util.concurrent.TimeoutException
+
+import scala.annotation.tailrec
+import scala.collection.mutable.ArrayBuffer
+import scala.concurrent._
+import scala.concurrent.duration._
+import scala.language.postfixOps
+import scala.util.{Failure, Success, Try}
+import scala.util.control.NonFatal
+
+import io.fabric8.kubernetes.api.model._
+import io.fabric8.kubernetes.client._
+
+import org.apache.livy.{LivyConf, Logging, Utils}
+
+object SparkKubernetesApp extends Logging {
+
+  private val RETRY_BACKOFF_MILLIS = 1000
+
+  lazy val kubernetesClient: LivyKubernetesClient =
+    KubernetesClientFactory.createKubernetesClient(livyConf)
+
+  private var livyConf: LivyConf = _
+  private var sessionLeakageCheckTimeout: Long = _
+  private var sessionLeakageCheckInterval: Long = _
+  private val leakedAppTags = new java.util.concurrent.ConcurrentHashMap[String, Long]()
+
+  private val leakedAppsGCThread = new Thread() {
+    override def run(): Unit = {
+      while (true) {
+        if (!leakedAppTags.isEmpty) {
+          // kill the app if found it or remove it if exceeding a threshold
+          val leakedApps = leakedAppTags.entrySet().iterator()
+          val now = System.currentTimeMillis()
+          val apps = withRetry(kubernetesClient.getApplications()).groupBy(_.getApplicationTag)
+          while (leakedApps.hasNext) {
+            val leakedApp = leakedApps.next()
+            apps.get(leakedApp.getKey) match {
+              case Some(seq) =>
+                seq.foreach(app =>
+                  if (withRetry(kubernetesClient.killApplication(app))) {
+                    leakedApps.remove()
+                    info(s"Killed leaked app with tag ${leakedApp.getKey}")
+                  }
+                )
+              case None if (leakedApp.getValue - now) > sessionLeakageCheckTimeout =>
+                leakedApps.remove()
+                info(s"Remove leaked Kubernetes app tag ${leakedApp.getKey}")
+            }
+          }
+        }
+        Thread.sleep(sessionLeakageCheckInterval)
+      }
+    }
+  }
+
+  def init(livyConf: LivyConf): Unit = {
+    this.livyConf = livyConf
+    sessionLeakageCheckInterval =
+      livyConf.getTimeAsMs(LivyConf.KUBERNETES_APP_LEAKAGE_CHECK_INTERVAL)
+    sessionLeakageCheckTimeout = livyConf.getTimeAsMs(LivyConf.KUBERNETES_APP_LEAKAGE_CHECK_TIMEOUT)
+    leakedAppsGCThread.setDaemon(true)
+    leakedAppsGCThread.setName("LeakedAppsGCThread")
+    leakedAppsGCThread.start()
+  }
+
+  // Returning T, throwing the exception on failure
+  @tailrec
+  private def withRetry[T](fn: => T, retries: Int = 3): T =
+    Try { fn } match {
+      case Success(x) => x
+      case _ if retries > 1 =>
+        Thread.sleep(RETRY_BACKOFF_MILLIS)
+        withRetry(fn, retries - 1)
+      case Failure(e) => throw e
+    }
+}
+
+class SparkKubernetesApp private[utils](
+  appTag: String,
+  appIdOption: Option[String],
+  process: Option[LineBufferedProcess],
+  listener: Option[SparkAppListener],
+  livyConf: LivyConf,
+  kubernetesClient: => LivyKubernetesClient = SparkKubernetesApp.kubernetesClient) // For unit tests
+  extends SparkApp with Logging {
+
+  import SparkKubernetesApp._
+
+  private val appLookupTimeout =
+    livyConf.getTimeAsMs(LivyConf.KUBERNETES_APP_LOOKUP_TIMEOUT).milliseconds
+  private val cacheLogSize = livyConf.getInt(LivyConf.SPARK_LOGS_SIZE)
+  private val pollInterval = livyConf.getTimeAsMs(LivyConf.KUBERNETES_POLL_INTERVAL).milliseconds
+
+  private var kubernetesAppLog: IndexedSeq[String] = IndexedSeq.empty[String]
+  private var kubernetesDiagnostics: IndexedSeq[String] = IndexedSeq.empty[String]
+
+  private var state: SparkApp.State = SparkApp.State.STARTING
+  private val appPromise: Promise[KubernetesApplication] = Promise()
+
+  private[utils] val kubernetesAppMonitorThread = Utils
+    .startDaemonThread(s"kubernetesAppMonitorThread-$this") {
+      try {
+        val app = try {
+          getAppFromTag(appTag, pollInterval, appLookupTimeout.fromNow)
+        } catch {
+          case e: Exception =>
+            appPromise.failure(e)
+            throw e
+        }
+        appPromise.success(app)
+        val appId = app.getApplicationId
+
+        Thread.currentThread().setName(s"kubernetesAppMonitorThread-$appId")
+        listener.foreach(_.appIdKnown(appId))
+
+        while (isRunning) {
+          val appReport = withRetry(kubernetesClient.getApplicationReport(app, cacheLogSize))
+          kubernetesAppLog = appReport.getApplicationLog
+          kubernetesDiagnostics = appReport.getApplicationDiagnostics
+          changeState(mapKubernetesState(appReport.getApplicationState, appTag))
+
+          Clock.sleep(pollInterval.toMillis)
+        }
+        debug(s"Application $appId is in state $state\nDiagnostics:" +
+          s"\n${kubernetesDiagnostics.mkString("\n")}")
+      } catch {
+        case _: InterruptedException =>
+          kubernetesDiagnostics = ArrayBuffer("Application stopped by user.")
+          changeState(SparkApp.State.KILLED)
+        case NonFatal(e) =>
+          error("Error while refreshing Kubernetes state", e)
+          kubernetesDiagnostics = ArrayBuffer(e.getMessage)
+          changeState(SparkApp.State.FAILED)
+      } finally {
+        listener.foreach(_.infoChanged(AppInfo(sparkUiUrl = None)))
 
 Review comment:
   ```suggestion
   ```
   Suggestion: It shouldn't be unset cause it hasn't been set.
   
   As a first iteration this PR provides a way to submit and track the Spark apps by Livy, as well to integrate Interactive sessions with Notebooks (or whatever). To access Spark UI user still needs to handle access on its own so far. The easiest way I guess is to use `kubectl port-forward ...` manually.
   
   There could be multiple points of view on how is it better to compose base PR splitting or whether it even makes sense to do it, unfortunately... But would be nice to let it go at some point. I propose to create small PRs representing single aspect of the whole project each. We can merge them to bigger ones at any time, but splitting out is a bit more painful. In the meantime you can take a look at the following one : https://github.com/apache/incubator-livy/pull/252 .
   
   Or we can always roll back to the original PR and just refactor it up to the acceptable state.
   
   WDYT?
   
   

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services