rabbah commented on a change in pull request #4129: Adding 
YARNContainerFactory. This allows OpenWhisk to run actions on Apache Hadoop 
clusters.
URL: 
https://github.com/apache/incubator-openwhisk/pull/4129#discussion_r237981794
 
 

 ##########
 File path: 
common/scala/src/main/scala/org/apache/openwhisk/core/yarn/YARNContainerFactory.scala
 ##########
 @@ -0,0 +1,476 @@
+/*
+ * 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.openwhisk.core.yarn
+
+import java.nio.charset.StandardCharsets
+import java.security.Principal
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.model._
+import akka.stream.ActorMaterializer
+import javax.security.sasl.AuthenticationException
+import org.apache.commons.io.IOUtils
+import org.apache.http.auth.{AuthSchemeProvider, AuthScope, Credentials}
+import org.apache.http.client.CredentialsProvider
+import org.apache.http.client.config.AuthSchemes
+import org.apache.http.client.methods._
+import org.apache.http.config.RegistryBuilder
+import org.apache.http.entity.StringEntity
+import org.apache.http.impl.auth.SPNegoSchemeFactory
+import org.apache.http.impl.client.{CloseableHttpClient, HttpClients, _}
+import org.apache.openwhisk.common.{Logging, TransactionId}
+import org.apache.openwhisk.core.containerpool._
+import org.apache.openwhisk.core.entity.ExecManifest.ImageName
+import org.apache.openwhisk.core.entity.{ByteSize, ExecManifest, 
InvokerInstanceId}
+import org.apache.openwhisk.core.{ConfigKeys, WhiskConfig}
+import pureconfig.loadConfigOrThrow
+import spray.json.{DefaultJsonProtocol, _}
+
+import scala.concurrent.{ExecutionContext, Future}
+
+case class YARNConfig(masterUrl: String,
+                      yarnLinkLogMessage: Boolean,
+                      serviceName: String,
+                      authType: String,
+                      kerberosPrincipal: String,
+                      kerberosKeytab: String,
+                      queue: String,
+                      memory: String,
+                      cpus: Int)
+
+case class KerberosPrincipalDefinition(principal_name: Option[String], keytab: 
Option[String])
+case class YARNResponseDefinition(diagnostics: String)
+case class ConfigurationDefinition(env: Map[String, String])
+case class ArtifactDefinition(id: String, `type`: String)
+case class ResourceDefinition(cpus: Int, memory: String)
+case class ContainerDefinition(ip: Option[String],
+                               bare_host: Option[String],
+                               component_instance_name: String,
+                               hostname: Option[String],
+                               id: String,
+                               launch_time: Long,
+                               state: String)
+case class ComponentDefinition(name: String,
+                               number_of_containers: Int,
+                               launch_command: String,
+                               containers: Option[List[ContainerDefinition]],
+                               artifact: ArtifactDefinition,
+                               resource: ResourceDefinition,
+                               configuration: ConfigurationDefinition)
+case class ServiceDefinition(name: String,
+                             version: Option[String],
+                             description: Option[String],
+                             state: String,
+                             queue: Option[String],
+                             components: List[ComponentDefinition],
+                             kerberos_principal: 
Option[KerberosPrincipalDefinition])
+
+object YARNJsonProtocol extends DefaultJsonProtocol {
+  implicit val KerberosPrincipalDefinitionFormat: 
RootJsonFormat[KerberosPrincipalDefinition] = jsonFormat2(
+    KerberosPrincipalDefinition)
+  implicit val YARNResponseDefinitionFormat: 
RootJsonFormat[YARNResponseDefinition] = jsonFormat1(
+    YARNResponseDefinition)
+  implicit val configurationDefinitionFormat: 
RootJsonFormat[ConfigurationDefinition] = jsonFormat1(
+    ConfigurationDefinition)
+  implicit val artifactDefinitionFormat: RootJsonFormat[ArtifactDefinition] = 
jsonFormat2(ArtifactDefinition)
+  implicit val resourceDefinitionFormat: RootJsonFormat[ResourceDefinition] = 
jsonFormat2(ResourceDefinition)
+  implicit val containerDefinitionFormat: RootJsonFormat[ContainerDefinition] 
= jsonFormat7(ContainerDefinition)
+  implicit val componentDefinitionFormat: RootJsonFormat[ComponentDefinition] 
= jsonFormat7(ComponentDefinition)
+  implicit val serviceDefinitionFormat: RootJsonFormat[ServiceDefinition] = 
jsonFormat7(ServiceDefinition)
+}
+import org.apache.openwhisk.core.yarn.YARNJsonProtocol._
+
+object YARNContainerFactoryProvider extends ContainerFactoryProvider {
+  override def instance(actorSystem: ActorSystem,
+                        logging: Logging,
+                        config: WhiskConfig,
+                        instance: InvokerInstanceId,
+                        parameters: Map[String, Set[String]]): 
ContainerFactory =
+    new YARNContainerFactory(config, actorSystem, logging, parameters)
+}
+
+object YARNContainerFactory {
+  val SIMPLEAUTH = "simple"
+  val KERBEROSAUTH = "kerberos"
+}
+class YARNContainerFactory(config: WhiskConfig,
+                           actorSystem: ActorSystem,
+                           logging: Logging,
+                           parameters: Map[String, Set[String]],
+                           containerArgs: ContainerArgsConfig =
+                             
loadConfigOrThrow[ContainerArgsConfig](ConfigKeys.containerArgs),
+                           yarnConfig: YARNConfig = 
loadConfigOrThrow[YARNConfig](ConfigKeys.yarn))
+    extends ContainerFactory {
+
+  case class httpresponse(statusCode: StatusCode, content: String)
+
+  //The YARN APIs operate at a higher level than containers
+  //Instead of creating and deleting specific containers, service components 
are resized
+  //This lock is necessary to ensure we get information about the specific 
container that was just added
+  private object serviceLock
+
+  val serviceStartTimeoutMS = 60000
+  val containerStartTimeoutMS = 60000
+  val retryWaitMS = 1000
+
+  implicit val as: ActorSystem = actorSystem
+  implicit val materializer: ActorMaterializer = ActorMaterializer()
+  implicit val ec: ExecutionContext = actorSystem.dispatcher
+
+  val runCommand = ""
+  val version = "1.0.0"
+  val description = "OpenWhisk Service"
+
+  var containerCounts = new scala.collection.mutable.HashMap[String, Int]()
+  var containerMap = new scala.collection.mutable.HashMap[String, 
List[ContainerDefinition]]
+
+  override def init(): Unit = {
+    val images: Set[ImageName] = 
ExecManifest.runtimesManifest.runtimes.flatMap(a => a.versions.map(b => 
b.image))
+
+    //Remove service if it already exists
+    if (downloadServiceDefinition() != null)
+      this.cleanup()
+
+    createService(images)
+    waitForServiceStart()
+  }
+
+  def createService(images: Set[ImageName]): Unit = {
+
+    logging.info(this, "Creating Service with images: " + images.map(i => 
i.publicImageName).mkString(", "))
+    serviceLock.synchronized {
+
+      val componentList = images
+        .map(
+          i =>
+            ComponentDefinition(
+              i.name.replace('.', '-'), //name must be [a-z][a-z0-9-]*
+              0, //start with zero containers
+              runCommand,
+              Option.empty,
+              ArtifactDefinition(i.publicImageName, "DOCKER"),
+              ResourceDefinition(yarnConfig.cpus, yarnConfig.memory),
+              
ConfigurationDefinition(Map(("YARN_CONTAINER_RUNTIME_DOCKER_RUN_OVERRIDE_DISABLE",
 "true")))))
+        .toList
+
+      //Add kerberos def if necessary
+      var kerberosDef: Option[KerberosPrincipalDefinition] = None
+      if (yarnConfig.authType.equals(YARNContainerFactory.KERBEROSAUTH))
+        kerberosDef =
+          Some(KerberosPrincipalDefinition(Some(yarnConfig.kerberosPrincipal), 
Some(yarnConfig.kerberosKeytab)))
+
+      val service = ServiceDefinition(
+        yarnConfig.serviceName,
+        Some(version),
+        Some(description),
+        "STABLE",
+        Some(yarnConfig.queue),
+        componentList,
+        kerberosDef)
+
+      //Submit service
+      val response =
+        submitRequestWithAuth(HttpMethods.POST, 
s"${yarnConfig.masterUrl}/app/v1/services", service.toJson.compactPrint)
+
+      //Handle response
+      response match {
+        case httpresponse(StatusCodes.OK, content) =>
+          logging.info(this, s"Service submitted. Response: $content")
+
+        case httpresponse(StatusCodes.Accepted, content) =>
+          logging.info(this, s"Service submitted. Response: $content")
+
+        case httpresponse(_, _) => handleYARNRESTError(response)
+      }
+    }
+  }
+
+  override def createContainer(
+    tid: TransactionId,
+    name: String,
+    actionImage: ExecManifest.ImageName,
+    unuseduserProvidedImage: Boolean,
+    unusedmemory: ByteSize,
+    unusedcpuShares: Int)(implicit config: WhiskConfig, logging: Logging): 
Future[Container] = {
+
+    logging.info(this, s"Using YARN to create a container with image 
${actionImage.name}...")
+
+    Future {
+      serviceLock.synchronized {
+        val newContainerCount = containerCounts.getOrElse(actionImage.name, 0) 
+ 1
+        val body = "{\"number_of_containers\":" + newContainerCount + "}"
+        val response = submitRequestWithAuth(
+          HttpMethods.PUT,
+          
s"${yarnConfig.masterUrl}/app/v1/services/${yarnConfig.serviceName}/components/${actionImage.name}",
+          body)
+        response match {
+          case httpresponse(StatusCodes.OK, content) =>
+            logging.info(this, s"Added container: ${actionImage.name}. 
Response: $content")
+            containerCounts(actionImage.name) = newContainerCount
+
+          case httpresponse(_, _) => handleYARNRESTError(response)
+        }
+
+        //Wait for container to come up
+        val serviceDef = waitForContainerStability(actionImage)
+
+        //Update container list with new container details
+        val updatedContainerList = serviceDef.components
+          .filter(c => c.name.equals(actionImage.name))
+          .flatMap(c => c.containers.getOrElse(List[ContainerDefinition]()))
+        logging.info(this, s"YARN service now has ${updatedContainerList.size} 
total containers")
+
+        val newContainers = updatedContainerList.filter(a =>
+          !containerMap.getOrElse(actionImage.name, 
List[ContainerDefinition]()).contains(a))
+
+        //Synchronized block should prevent this from happening
+        if (newContainers.length > 1)
+          logging.warn(this, "More than one new container...")
+
+        containerMap(actionImage.name) = updatedContainerList
+        val newContainer = newContainers.head
+
+        val containerAddress = 
ContainerAddress(newContainer.ip.getOrElse("127.0.0.1")) //port 8080 is default
+        val containerId = ContainerId(newContainer.id)
+
+        logging.info(this, s"New Container: ${newContainer.id}, 
$containerAddress")
+        new YARNTask(containerId, containerAddress, ec, logging, as, 
actionImage, yarnConfig, this)
+      }
+    }
+  }
+
+  def waitForServiceStart(): Unit = {
+    var started = false
+    var retryCount = 0
+    val maxRetryCount = serviceStartTimeoutMS / retryWaitMS
+    while (!started && retryCount < maxRetryCount) {
+      val serviceDef = downloadServiceDefinition()
+
+      //Should never happen
+      if (serviceDef == null)
+        throw new IllegalArgumentException("Service not found?")
+
+      serviceDef.state match {
+        case "STABLE" | "STARTED" =>
+          logging.info(this, "YARN service achieved stable state")
+          started = true
+
+        case state =>
+          logging.info(
+            this,
+            s"YARN service is not in stable state yet 
($retryCount/$maxRetryCount). Current state: $state")
+          Thread.sleep(retryWaitMS)
+      }
+      retryCount += 1
+    }
+    if (!started)
+      throw new Exception(s"After ${containerStartTimeoutMS}ms YARN service 
did not achieve stable state")
+  }
+  def waitForContainerStability(actionImage: ImageName): ServiceDefinition = {
+    var stable = false
+    var serviceDef: ServiceDefinition = null
+    var retryCount = 0
+    val maxRetryCount = containerStartTimeoutMS / retryWaitMS
+    while (!stable && retryCount < maxRetryCount) {
+      serviceDef = downloadServiceDefinition()
+      val newContainerList = serviceDef.components
+        .filter(c => c.name.equals(actionImage.name))
+        .flatMap(c => c.containers.getOrElse(List[ContainerDefinition]()))
+
+      val previousContainerList = containerMap.getOrElse(actionImage.name, 
List[ContainerDefinition]())
+
+      //If container has not been created yet, or container is not in ready 
state yet
+      if (newContainerList.size > previousContainerList.size && 
newContainerList.forall(c => c.state.equals("READY"))) {
+        logging.info(this, s"YARN container (${actionImage.name}) achieved 
stable state")
+        stable = true
+      } else {
+        logging.info(
+          this,
+          s"YARN container (${actionImage.name}) is not in stable state yet 
($retryCount/$maxRetryCount)")
+      }
+      Thread.sleep(retryWaitMS)
+      retryCount += 1
+    }
+    if (stable)
+      serviceDef
+    else
+      throw new Exception(s"After ${containerStartTimeoutMS}ms YARN container 
did not achieve stable state")
+  }
+
+  def downloadServiceDefinition(): ServiceDefinition = {
+    val response: httpresponse =
+      submitRequestWithAuth(HttpMethods.GET, 
s"${yarnConfig.masterUrl}/app/v1/services/${yarnConfig.serviceName}", "")
+
+    response match {
+      case httpresponse(StatusCodes.OK, content) =>
+        //logging.info(this,"Retrieved service definition from YARN")
+        content.parseJson.convertTo[ServiceDefinition]
+
+      case httpresponse(StatusCodes.NotFound, content) =>
+        logging.info(this, s"Service not found. Response: $content")
+        null
+
+      case httpresponse(_, _) =>
+        handleYARNRESTError(response)
+        null
+    }
+  }
+
+  def removeContainer(task: YARNTask): Unit = {
+
+    serviceLock.synchronized {
 
 Review comment:
   the docker factory also have a mechanism for synchronizing docker operations 
(there's a way to limit the number of concurrent operations) - it might be 
worth looking at how that's implemented for reference.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to