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_r237980039
 
 

 ##########
 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 {
 
 Review comment:
   the synchronization here can block the future - does it make sense to 
synchronize first then run the rest inside the future?
   
   @markusthoemmes might have a better idea.

----------------------------------------------------------------
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