[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-02-19 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r169139888
 
 

 ##
 File path: 
tests/src/test/scala/whisk/core/containerpool/kubernetes/test/KubernetesClientTests.scala
 ##
 @@ -0,0 +1,272 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes.test
+
+import java.time.LocalDateTime
+
+import akka.actor.ActorSystem
+import akka.stream.ActorMaterializer
+import akka.stream.scaladsl.{Concat, Flow, Framing, Sink, Source}
+import akka.util.ByteString
+
+import scala.concurrent.Await
+import scala.concurrent.ExecutionContext
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent.Future
+import scala.concurrent.duration._
+import spray.json._
+import org.junit.runner.RunWith
+import org.scalatest.BeforeAndAfterEach
+import org.scalatest.concurrent.Eventually
+import org.scalatest.FlatSpec
+import org.scalatest.junit.JUnitRunner
+import org.scalatest.Matchers
+import org.scalatest.time.{Seconds, Span}
+import common.{StreamLogging, WskActorSystem}
+import okio.Buffer
+import whisk.common.LogMarker
+import whisk.common.LoggingMarkers.INVOKER_KUBECTL_CMD
+import whisk.common.TransactionId
+import whisk.core.containerpool.{ContainerAddress, ContainerId}
+import whisk.core.containerpool.kubernetes.{KubernetesApi, KubernetesClient, 
KubernetesRestLogSourceStage}
+import whisk.core.containerpool.docker.ProcessRunningException
+import whisk.core.containerpool.logging.LogLine
+
+import scala.collection.mutable
+import scala.util.Try
+@RunWith(classOf[JUnitRunner])
+class KubernetesClientTests
+extends FlatSpec
+with Matchers
+with StreamLogging
+with BeforeAndAfterEach
+with Eventually
+with WskActorSystem {
+
+  import KubernetesClientTests._
+
+  implicit val materializer: ActorMaterializer = ActorMaterializer()
+
+  /** Reads logs into memory and awaits them */
+  def awaitLogs(source: Source[ByteString, Any], timeout: FiniteDuration = 
1000.milliseconds): Vector[LogLine] =
+Await
+  .result(
+source
+  .via(Framing.delimiter(ByteString("\n"), 1024))
+  .via(Flow[ByteString].map(l => 
Try(l.utf8String.parseJson.convertTo[LogLine]).getOrElse(LogLine("", "", ""
+  .filter(_ != LogLine("", "", ""))
+  .runWith(Sink.seq[LogLine]),
+timeout)
+  .toVector
+
+  override def beforeEach = stream.reset()
+
+  implicit override val patienceConfig = PatienceConfig(timeout = 
scaled(Span(5, Seconds)))
+
+  implicit val transid = TransactionId.testing
+  val id = 
ContainerId("55db56ee082239428b27d3728b4dd324c09068458aad9825727d5bfc1bba6d52")
+
+  val commandTimeout = 500.milliseconds
+  def await[A](f: Future[A], timeout: FiniteDuration = commandTimeout) = 
Await.result(f, timeout)
+
+  val kubectlCommand = "kubectl"
+
+  /** Returns a KubernetesClient with a mocked result for 'executeProcess' and 
'fetchHTTPLogs' */
+  def kubernetesClient(fixture: => Future[String]) = new 
KubernetesClient()(global) {
+override def findKubectlCmd() = kubectlCommand
+override def executeProcess(args: Seq[String], timeout: Duration)(implicit 
ec: ExecutionContext, as: ActorSystem) =
+  fixture
 
 Review comment:
   DISABLED THE TESTS WHAT!?!?! ;)
   Yeah, @bwmcadams  had to set up dummy `Source` objects to validate the log 
parsing logic. I guess we'll need to figure out something similar as we convert 
the other calls to the API.


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


[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-02-06 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r166361954
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/kubernetes/KubernetesContainer.scala
 ##
 @@ -0,0 +1,165 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes
+
+import java.time.Instant
+import java.util.concurrent.atomic.AtomicReference
+
+import akka.stream.StreamLimitReachedException
+import akka.stream.scaladsl.Framing.FramingException
+import akka.stream.scaladsl.{Framing, Source}
+import akka.util.ByteString
+
+import scala.concurrent.ExecutionContext
+import scala.concurrent.Future
+import scala.concurrent.duration._
+import spray.json._
+import whisk.common.Logging
+import whisk.common.TransactionId
+import whisk.core.containerpool.Container
+import whisk.core.containerpool.WhiskContainerStartupError
+import whisk.core.containerpool.ContainerId
+import whisk.core.containerpool.ContainerAddress
+import whisk.core.containerpool.docker.{CompleteAfterOccurrences, 
DockerContainer, OccurrencesNotFoundException}
+import whisk.core.containerpool.logging.LogLine
+import whisk.core.entity.ByteSize
+import whisk.core.entity.size._
+import whisk.http.Messages
+
+object KubernetesContainer {
+
+  /**
+   * Creates a container running in kubernetes
+   *
+   * @param transid transaction creating the container
+   * @param image image to create the container from
+   * @param userProvidedImage whether the image is provided by the user
+   * or is an OpenWhisk provided image
+   * @param labels labels to set on the container
+   * @param name optional name for the container
+   * @return a Future which either completes with a KubernetesContainer or one 
of two specific failures
+   */
+  def create(transid: TransactionId,
+ name: String,
+ image: String,
+ userProvidedImage: Boolean = false,
+ memory: ByteSize = 256.MB,
+ environment: Map[String, String] = Map(),
+ labels: Map[String, String] = Map())
+(implicit kubernetes: KubernetesApi,
+  ec: ExecutionContext,
+  log: Logging): Future[KubernetesContainer] = {
+implicit val tid = transid
+
+val podName = name.replace("_", "-").replaceAll("[()]", "").toLowerCase()
+
+val environmentArgs = environment.flatMap {
+  case (key, value) => Seq("--env", s"$key=$value")
+}.toSeq
+
+val labelArgs = labels.map {
+  case (key, value) => s"$key=$value"
+} match {
+  case Seq() => Seq()
+  case pairs => Seq("-l") ++ pairs
+}
+
+val args = Seq(
+  "--generator",
+  "run-pod/v1",
+  "--restart",
+  "Always",
+  "--limits",
+  s"memory=${memory.toMB}Mi") ++ environmentArgs ++ labelArgs
+
+for {
+  id <- kubernetes.run(podName, image, args).recoverWith {
+case _ => Future.failed(WhiskContainerStartupError(s"Failed to run 
container with image '${image}'."))
 
 Review comment:
   Done


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


[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-02-05 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r166076063
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/kubernetes/KubernetesClient.scala
 ##
 @@ -0,0 +1,218 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes
+
+import java.io.FileNotFoundException
+import java.nio.file.Files
+import java.nio.file.Paths
+
+import akka.actor.ActorSystem
+import akka.event.Logging.{ErrorLevel, InfoLevel}
+import akka.http.scaladsl.model.Uri
+import akka.http.scaladsl.model.Uri.Path
+import akka.http.scaladsl.model.Uri.Query
+import akka.stream.scaladsl.Source
+import akka.util.ByteString
+import pureconfig.loadConfigOrThrow
+import whisk.common.Logging
+import whisk.common.LoggingMarkers
+import whisk.common.TransactionId
+import whisk.core.ConfigKeys
+import whisk.core.containerpool.ContainerId
+import whisk.core.containerpool.ContainerAddress
+import whisk.core.containerpool.docker.ProcessRunner
+import whisk.core.containerpool.logging.LogLine
+import scala.concurrent.duration.Duration
+import scala.concurrent.ExecutionContext
+import scala.concurrent.Future
+import scala.concurrent.blocking
+import scala.concurrent.duration._
+import scala.util.Failure
+import scala.util.Success
+import scala.util.Try
+import spray.json._
+
+import io.fabric8.kubernetes.client.ConfigBuilder
+import io.fabric8.kubernetes.client.DefaultKubernetesClient
+import okhttp3.Request
+
+/**
+ * Configuration for kubernetes client command timeouts.
+ */
+case class KubernetesClientTimeoutConfig(run: Duration, rm: Duration, inspect: 
Duration, logs: Duration)
+
+/**
+ * Serves as interface to the kubectl CLI tool.
+ *
+ * Be cautious with the ExecutionContext passed to this, as the
+ * calls to the CLI are blocking.
+ *
+ * You only need one instance (and you shouldn't get more).
+ */
+class KubernetesClient(
+  timeouts: KubernetesClientTimeoutConfig = 
loadConfigOrThrow[KubernetesClientTimeoutConfig](
+ConfigKeys.kubernetesTimeouts))(executionContext: 
ExecutionContext)(implicit log: Logging, as: ActorSystem)
+extends KubernetesApi
+with ProcessRunner {
+  implicit private val ec = executionContext
+  implicit private val kubeRestClient = new DefaultKubernetesClient(
+new ConfigBuilder()
+  .withConnectionTimeout(timeouts.logs.toMillis.toInt)
+  .withRequestTimeout(timeouts.logs.toMillis.toInt)
+  .build())
+
+  // Determines how to run kubectl. Failure to find a kubectl binary implies
+  // a failure to initialize this instance of KubernetesClient.
+  protected val kubectlCmd: Seq[String] = {
+val alternatives = List("/usr/bin/kubectl", "/usr/local/bin/kubectl")
+
+val kubectlBin = Try {
+  alternatives.find(a => Files.isExecutable(Paths.get(a))).get
+} getOrElse {
+  throw new FileNotFoundException(s"Couldn't locate kubectl binary (tried: 
${alternatives.mkString(", ")}).")
+}
+
+Seq(kubectlBin)
+  }
+
+  def run(image: String, name: String, environment: Map[String, String] = 
Map(), labels: Map[String, String] = Map())(
+implicit transid: TransactionId): Future[ContainerId] = {
+val environmentArgs = environment.flatMap {
+  case (key, value) => Seq("--env", s"$key=$value")
+}.toSeq
+
+val labelArgs = labels.map {
+  case (key, value) => s"$key=$value"
+} match {
+  case Seq() => Seq()
+  case pairs => Seq("-l") ++ pairs
+}
+
+val runArgs = Seq(
+  "run",
+  name,
+  "--image",
+  image,
+  "--generator",
+  "run-pod/v1",
+  "--restart",
+  "Always",
+  "--limits",
+  "memory=256Mi") ++ environmentArgs ++ labelArgs
+
+runCmd(runArgs, timeouts.run)
+  .map(_ => ContainerId(name))
+  }
+
+  def inspectIPAddress(id: ContainerId)(implicit transid: TransactionId): 
Future[ContainerAddress] = {
+Future {
+  blocking {
+val pod =
+  
kubeRestClient.pods().withName(id.asString).waitUntilReady(timeouts.inspect.length,
 timeouts.inspect.unit)
+ContainerAddress(pod.getStatus().getPodIP())
+  }
+

[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-02-05 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r166073411
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/kubernetes/KubernetesClient.scala
 ##
 @@ -0,0 +1,218 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes
+
+import java.io.FileNotFoundException
+import java.nio.file.Files
+import java.nio.file.Paths
+
+import akka.actor.ActorSystem
+import akka.event.Logging.{ErrorLevel, InfoLevel}
+import akka.http.scaladsl.model.Uri
+import akka.http.scaladsl.model.Uri.Path
+import akka.http.scaladsl.model.Uri.Query
+import akka.stream.scaladsl.Source
+import akka.util.ByteString
+import pureconfig.loadConfigOrThrow
+import whisk.common.Logging
+import whisk.common.LoggingMarkers
+import whisk.common.TransactionId
+import whisk.core.ConfigKeys
+import whisk.core.containerpool.ContainerId
+import whisk.core.containerpool.ContainerAddress
+import whisk.core.containerpool.docker.ProcessRunner
+import whisk.core.containerpool.logging.LogLine
+import scala.concurrent.duration.Duration
+import scala.concurrent.ExecutionContext
+import scala.concurrent.Future
+import scala.concurrent.blocking
+import scala.concurrent.duration._
+import scala.util.Failure
+import scala.util.Success
+import scala.util.Try
+import spray.json._
+
+import io.fabric8.kubernetes.client.ConfigBuilder
+import io.fabric8.kubernetes.client.DefaultKubernetesClient
+import okhttp3.Request
+
+/**
+ * Configuration for kubernetes client command timeouts.
+ */
+case class KubernetesClientTimeoutConfig(run: Duration, rm: Duration, inspect: 
Duration, logs: Duration)
+
+/**
+ * Serves as interface to the kubectl CLI tool.
+ *
+ * Be cautious with the ExecutionContext passed to this, as the
+ * calls to the CLI are blocking.
+ *
+ * You only need one instance (and you shouldn't get more).
+ */
+class KubernetesClient(
+  timeouts: KubernetesClientTimeoutConfig = 
loadConfigOrThrow[KubernetesClientTimeoutConfig](
+ConfigKeys.kubernetesTimeouts))(executionContext: 
ExecutionContext)(implicit log: Logging, as: ActorSystem)
+extends KubernetesApi
+with ProcessRunner {
+  implicit private val ec = executionContext
+  implicit private val kubeRestClient = new DefaultKubernetesClient(
+new ConfigBuilder()
+  .withConnectionTimeout(timeouts.logs.toMillis.toInt)
+  .withRequestTimeout(timeouts.logs.toMillis.toInt)
+  .build())
+
+  // Determines how to run kubectl. Failure to find a kubectl binary implies
+  // a failure to initialize this instance of KubernetesClient.
+  protected val kubectlCmd: Seq[String] = {
+val alternatives = List("/usr/bin/kubectl", "/usr/local/bin/kubectl")
+
+val kubectlBin = Try {
+  alternatives.find(a => Files.isExecutable(Paths.get(a))).get
+} getOrElse {
+  throw new FileNotFoundException(s"Couldn't locate kubectl binary (tried: 
${alternatives.mkString(", ")}).")
+}
+
+Seq(kubectlBin)
+  }
+
+  def run(image: String, name: String, environment: Map[String, String] = 
Map(), labels: Map[String, String] = Map())(
+implicit transid: TransactionId): Future[ContainerId] = {
+val environmentArgs = environment.flatMap {
+  case (key, value) => Seq("--env", s"$key=$value")
+}.toSeq
+
+val labelArgs = labels.map {
+  case (key, value) => s"$key=$value"
+} match {
+  case Seq() => Seq()
+  case pairs => Seq("-l") ++ pairs
+}
+
+val runArgs = Seq(
+  "run",
+  name,
+  "--image",
+  image,
+  "--generator",
+  "run-pod/v1",
+  "--restart",
+  "Always",
+  "--limits",
+  "memory=256Mi") ++ environmentArgs ++ labelArgs
 
 Review comment:
   #1 makes sense. I'm gonna refer to @bbrowning for #2 and #3 


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 

[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-02-05 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r166072862
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/kubernetes/KubernetesClient.scala
 ##
 @@ -0,0 +1,218 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes
+
+import java.io.FileNotFoundException
+import java.nio.file.Files
+import java.nio.file.Paths
+
+import akka.actor.ActorSystem
+import akka.event.Logging.{ErrorLevel, InfoLevel}
+import akka.http.scaladsl.model.Uri
+import akka.http.scaladsl.model.Uri.Path
+import akka.http.scaladsl.model.Uri.Query
+import akka.stream.scaladsl.Source
+import akka.util.ByteString
+import pureconfig.loadConfigOrThrow
+import whisk.common.Logging
+import whisk.common.LoggingMarkers
+import whisk.common.TransactionId
+import whisk.core.ConfigKeys
+import whisk.core.containerpool.ContainerId
+import whisk.core.containerpool.ContainerAddress
+import whisk.core.containerpool.docker.ProcessRunner
+import whisk.core.containerpool.logging.LogLine
+import scala.concurrent.duration.Duration
+import scala.concurrent.ExecutionContext
+import scala.concurrent.Future
+import scala.concurrent.blocking
+import scala.concurrent.duration._
+import scala.util.Failure
+import scala.util.Success
+import scala.util.Try
+import spray.json._
+
+import io.fabric8.kubernetes.client.ConfigBuilder
+import io.fabric8.kubernetes.client.DefaultKubernetesClient
+import okhttp3.Request
+
+/**
+ * Configuration for kubernetes client command timeouts.
+ */
+case class KubernetesClientTimeoutConfig(run: Duration, rm: Duration, inspect: 
Duration, logs: Duration)
+
+/**
+ * Serves as interface to the kubectl CLI tool.
+ *
+ * Be cautious with the ExecutionContext passed to this, as the
+ * calls to the CLI are blocking.
+ *
+ * You only need one instance (and you shouldn't get more).
+ */
+class KubernetesClient(
+  timeouts: KubernetesClientTimeoutConfig = 
loadConfigOrThrow[KubernetesClientTimeoutConfig](
+ConfigKeys.kubernetesTimeouts))(executionContext: 
ExecutionContext)(implicit log: Logging, as: ActorSystem)
+extends KubernetesApi
+with ProcessRunner {
+  implicit private val ec = executionContext
+  implicit private val kubeRestClient = new DefaultKubernetesClient(
+new ConfigBuilder()
+  .withConnectionTimeout(timeouts.logs.toMillis.toInt)
+  .withRequestTimeout(timeouts.logs.toMillis.toInt)
+  .build())
+
+  // Determines how to run kubectl. Failure to find a kubectl binary implies
+  // a failure to initialize this instance of KubernetesClient.
+  protected val kubectlCmd: Seq[String] = {
+val alternatives = List("/usr/bin/kubectl", "/usr/local/bin/kubectl")
+
+val kubectlBin = Try {
+  alternatives.find(a => Files.isExecutable(Paths.get(a))).get
+} getOrElse {
+  throw new FileNotFoundException(s"Couldn't locate kubectl binary (tried: 
${alternatives.mkString(", ")}).")
+}
+
+Seq(kubectlBin)
+  }
+
+  def run(image: String, name: String, environment: Map[String, String] = 
Map(), labels: Map[String, String] = Map())(
+implicit transid: TransactionId): Future[ContainerId] = {
+val environmentArgs = environment.flatMap {
+  case (key, value) => Seq("--env", s"$key=$value")
+}.toSeq
+
+val labelArgs = labels.map {
+  case (key, value) => s"$key=$value"
+} match {
+  case Seq() => Seq()
+  case pairs => Seq("-l") ++ pairs
+}
+
+val runArgs = Seq(
+  "run",
+  name,
+  "--image",
+  image,
+  "--generator",
+  "run-pod/v1",
+  "--restart",
+  "Always",
+  "--limits",
+  "memory=256Mi") ++ environmentArgs ++ labelArgs
+
+runCmd(runArgs, timeouts.run)
+  .map(_ => ContainerId(name))
+  }
+
+  def inspectIPAddress(id: ContainerId)(implicit transid: TransactionId): 
Future[ContainerAddress] = {
+Future {
+  blocking {
+val pod =
+  
kubeRestClient.pods().withName(id.asString).waitUntilReady(timeouts.inspect.length,
 timeouts.inspect.unit)
+ContainerAddress(pod.getStatus().getPodIP())
+  }
+

[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-02-05 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r166072639
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/kubernetes/KubernetesClient.scala
 ##
 @@ -0,0 +1,218 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes
+
+import java.io.FileNotFoundException
+import java.nio.file.Files
+import java.nio.file.Paths
+
+import akka.actor.ActorSystem
+import akka.event.Logging.{ErrorLevel, InfoLevel}
+import akka.http.scaladsl.model.Uri
+import akka.http.scaladsl.model.Uri.Path
+import akka.http.scaladsl.model.Uri.Query
+import akka.stream.scaladsl.Source
+import akka.util.ByteString
+import pureconfig.loadConfigOrThrow
+import whisk.common.Logging
+import whisk.common.LoggingMarkers
+import whisk.common.TransactionId
+import whisk.core.ConfigKeys
+import whisk.core.containerpool.ContainerId
+import whisk.core.containerpool.ContainerAddress
+import whisk.core.containerpool.docker.ProcessRunner
+import whisk.core.containerpool.logging.LogLine
+import scala.concurrent.duration.Duration
+import scala.concurrent.ExecutionContext
+import scala.concurrent.Future
+import scala.concurrent.blocking
+import scala.concurrent.duration._
+import scala.util.Failure
+import scala.util.Success
+import scala.util.Try
+import spray.json._
+
+import io.fabric8.kubernetes.client.ConfigBuilder
+import io.fabric8.kubernetes.client.DefaultKubernetesClient
+import okhttp3.Request
+
+/**
+ * Configuration for kubernetes client command timeouts.
+ */
+case class KubernetesClientTimeoutConfig(run: Duration, rm: Duration, inspect: 
Duration, logs: Duration)
+
+/**
+ * Serves as interface to the kubectl CLI tool.
+ *
+ * Be cautious with the ExecutionContext passed to this, as the
+ * calls to the CLI are blocking.
+ *
+ * You only need one instance (and you shouldn't get more).
+ */
+class KubernetesClient(
+  timeouts: KubernetesClientTimeoutConfig = 
loadConfigOrThrow[KubernetesClientTimeoutConfig](
+ConfigKeys.kubernetesTimeouts))(executionContext: 
ExecutionContext)(implicit log: Logging, as: ActorSystem)
+extends KubernetesApi
+with ProcessRunner {
+  implicit private val ec = executionContext
+  implicit private val kubeRestClient = new DefaultKubernetesClient(
+new ConfigBuilder()
+  .withConnectionTimeout(timeouts.logs.toMillis.toInt)
+  .withRequestTimeout(timeouts.logs.toMillis.toInt)
+  .build())
+
+  // Determines how to run kubectl. Failure to find a kubectl binary implies
+  // a failure to initialize this instance of KubernetesClient.
+  protected val kubectlCmd: Seq[String] = {
+val alternatives = List("/usr/bin/kubectl", "/usr/local/bin/kubectl")
+
+val kubectlBin = Try {
+  alternatives.find(a => Files.isExecutable(Paths.get(a))).get
+} getOrElse {
+  throw new FileNotFoundException(s"Couldn't locate kubectl binary (tried: 
${alternatives.mkString(", ")}).")
+}
+
+Seq(kubectlBin)
+  }
+
+  def run(image: String, name: String, environment: Map[String, String] = 
Map(), labels: Map[String, String] = Map())(
+implicit transid: TransactionId): Future[ContainerId] = {
+val environmentArgs = environment.flatMap {
+  case (key, value) => Seq("--env", s"$key=$value")
+}.toSeq
+
+val labelArgs = labels.map {
+  case (key, value) => s"$key=$value"
+} match {
+  case Seq() => Seq()
+  case pairs => Seq("-l") ++ pairs
+}
+
+val runArgs = Seq(
+  "run",
+  name,
+  "--image",
+  image,
+  "--generator",
+  "run-pod/v1",
+  "--restart",
+  "Always",
+  "--limits",
+  "memory=256Mi") ++ environmentArgs ++ labelArgs
+
+runCmd(runArgs, timeouts.run)
+  .map(_ => ContainerId(name))
+  }
+
+  def inspectIPAddress(id: ContainerId)(implicit transid: TransactionId): 
Future[ContainerAddress] = {
+Future {
+  blocking {
+val pod =
+  
kubeRestClient.pods().withName(id.asString).waitUntilReady(timeouts.inspect.length,
 timeouts.inspect.unit)
+ContainerAddress(pod.getStatus().getPodIP())
+  }
+

[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-02-01 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r165375269
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/kubernetes/KubernetesContainer.scala
 ##
 @@ -0,0 +1,159 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes
+
+import java.time.Instant
+import java.util.concurrent.atomic.AtomicReference
+
+import akka.stream.StreamLimitReachedException
+import akka.stream.scaladsl.Framing.FramingException
+import akka.stream.scaladsl.{Framing, Source}
+import akka.util.ByteString
+
+import scala.concurrent.ExecutionContext
+import scala.concurrent.Future
+import scala.concurrent.duration._
+import spray.json._
+import spray.json.DefaultJsonProtocol._
+import whisk.common.Logging
+import whisk.common.TransactionId
+import whisk.core.containerpool.Container
+import whisk.core.containerpool.WhiskContainerStartupError
+import whisk.core.containerpool.ContainerId
+import whisk.core.containerpool.ContainerAddress
+import whisk.core.containerpool.docker.{CompleteAfterOccurrences, 
DockerContainer, OccurrencesNotFoundException}
+import whisk.core.containerpool.logging.LogLine
+import whisk.core.entity.ByteSize
+import whisk.http.Messages
+
+object KubernetesContainer {
+
+  /**
+   * Creates a container running in kubernetes
+   *
+   * @param transid transaction creating the container
+   * @param image image to create the container from
+   * @param userProvidedImage whether the image is provided by the user
+   * or is an OpenWhisk provided image
+   * @param labels labels to set on the container
+   * @param name optional name for the container
+   * @return a Future which either completes with a KubernetesContainer or one 
of two specific failures
+   */
+  def create(transid: TransactionId,
+ image: String,
+ userProvidedImage: Boolean = false,
+ environment: Map[String, String] = Map(),
+ labels: Map[String, String] = Map(),
+ name: Option[String] = None)(implicit kubernetes: KubernetesApi,
+  ec: ExecutionContext,
+  log: Logging): 
Future[KubernetesContainer] = {
+implicit val tid = transid
+
+val podName = name.getOrElse("").replace("_", "-").replaceAll("[()]", 
"").toLowerCase()
+for {
+  id <- kubernetes.run(image, podName, environment, labels).recoverWith {
+case _ => Future.failed(WhiskContainerStartupError(s"Failed to run 
container with image '${image}'."))
+  }
+  ip <- kubernetes.inspectIPAddress(id).recoverWith {
+// remove the container immediately if inspect failed as
+// we cannot recover that case automatically
+case _ =>
+  kubernetes.rm(id)
+  Future.failed(WhiskContainerStartupError(s"Failed to obtain IP 
address of container '${id.asString}'."))
+  }
+} yield new KubernetesContainer(id, ip)
+  }
+}
+
+/**
+ * Represents a container as run by kubernetes.
+ *
+ * This class contains OpenWhisk specific behavior and as such does not 
necessarily
+ * use kubernetes commands to achieve the effects needed.
+ *
+ * @constructor
+ * @param id the id of the container
+ * @param addr the ip & port of the container
+ */
+class KubernetesContainer(protected val id: ContainerId, protected val addr: 
ContainerAddress)(
+  implicit kubernetes: KubernetesApi,
+  protected val ec: ExecutionContext,
+  protected val logging: Logging)
+extends Container {
+
+  /** The last read timestamp in the log file */
+  private val lastTimestamp = new AtomicReference("")
+
+  protected val logsRetryCount = 15
+  protected val logsRetryWait = 100.millis
+
+  // no-op under Kubernetes
+  def suspend()(implicit transid: TransactionId): Future[Unit] = 
Future.successful({})
+
+  // no-op under Kubernetes
+  def resume()(implicit transid: TransactionId): Future[Unit] = 
Future.successful({})
+
+  override def destroy()(implicit transid: TransactionId): Future[Unit] = {
+super.destroy()
+kubernetes.rm(id)
+  }
+
+  def 

[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-01-31 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r165127138
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/kubernetes/KubernetesClient.scala
 ##
 @@ -0,0 +1,222 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes
+
+import java.io.FileNotFoundException
+import java.net.URL
+import java.nio.file.Files
+import java.nio.file.Paths
+
+import akka.actor.ActorSystem
+import akka.event.Logging.ErrorLevel
+import akka.stream.scaladsl.Source
+import akka.util.ByteString
+import pureconfig.loadConfigOrThrow
+import whisk.common.Logging
+import whisk.common.LoggingMarkers
+import whisk.common.TransactionId
+import whisk.core.containerpool.ContainerId
+import whisk.core.containerpool.ContainerAddress
+import whisk.core.containerpool.docker.ProcessRunner
+import scala.concurrent.duration.Duration
+import scala.concurrent.ExecutionContext
+import scala.concurrent.Future
+import scala.concurrent.blocking
+import scala.concurrent.duration._
+import scala.util.Failure
+import scala.util.Success
+import scala.util.Try
+
+import io.fabric8.kubernetes.client.ConfigBuilder
+import spray.json._
+import spray.json.DefaultJsonProtocol._
+import io.fabric8.kubernetes.client.DefaultKubernetesClient
+import io.fabric8.kubernetes.client.utils.URLUtils
+import okhttp3.Request
+
+/**
+ * Configuration for kubernetes client command timeouts.
+ */
+case class KubernetesClientTimeoutConfig(run: Duration, rm: Duration, inspect: 
Duration, logs: Duration)
+
+/**
+ * Serves as interface to the kubectl CLI tool.
+ *
+ * Be cautious with the ExecutionContext passed to this, as the
+ * calls to the CLI are blocking.
+ *
+ * You only need one instance (and you shouldn't get more).
+ */
+class KubernetesClient(
+  timeouts: KubernetesClientTimeoutConfig = 
loadConfigOrThrow[KubernetesClientTimeoutConfig](
+"whisk.kubernetes.timeouts"))(executionContext: ExecutionContext)(implicit 
log: Logging, as: ActorSystem)
+extends KubernetesApi
+with ProcessRunner {
+  implicit private val ec = executionContext
+  implicit private val kubeRestClient = new DefaultKubernetesClient(
+new ConfigBuilder()
+  .withConnectionTimeout(timeouts.logs.toMillis.toInt)
+  .withRequestTimeout(timeouts.logs.toMillis.toInt)
+  .build())
+
+  // Determines how to run kubectl. Failure to find a kubectl binary implies
+  // a failure to initialize this instance of KubernetesClient.
+  protected val kubectlCmd: Seq[String] = {
+val alternatives = List("/usr/bin/kubectl", "/usr/local/bin/kubectl")
+
+val kubectlBin = Try {
+  alternatives.find(a => Files.isExecutable(Paths.get(a))).get
+} getOrElse {
+  throw new FileNotFoundException(s"Couldn't locate kubectl binary (tried: 
${alternatives.mkString(", ")}).")
+}
+
+Seq(kubectlBin)
+  }
+
+  def run(image: String, name: String, environment: Map[String, String] = 
Map(), labels: Map[String, String] = Map())(
+implicit transid: TransactionId): Future[ContainerId] = {
+val environmentArgs = environment.flatMap {
+  case (key, value) => Seq("--env", s"$key=$value")
+}.toSeq
+
+val labelArgs = labels.map {
+  case (key, value) => s"$key=$value"
+} match {
+  case Seq() => Seq()
+  case pairs => Seq("-l") ++ pairs
+}
+
+val runArgs = Seq(
+  "run",
+  name,
+  "--image",
+  image,
+  "--generator",
+  "run-pod/v1",
+  "--restart",
+  "Always",
+  "--limits",
+  "memory=256Mi") ++ environmentArgs ++ labelArgs
+
+runCmd(runArgs, timeouts.run)
+  .map { _ =>
+name
+  }
+  .map(ContainerId.apply)
+  }
+
+  def inspectIPAddress(id: ContainerId)(implicit transid: TransactionId): 
Future[ContainerAddress] = {
+Future {
+  blocking {
+val pod =
+  
kubeRestClient.pods().withName(id.asString).waitUntilReady(timeouts.inspect.length,
 timeouts.inspect.unit)
+ContainerAddress(pod.getStatus().getPodIP())
+  }
+}.recoverWith {
+  case e =>
+log.error(this, 

[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-01-31 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r165117766
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/kubernetes/KubernetesClient.scala
 ##
 @@ -0,0 +1,222 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes
+
+import java.io.FileNotFoundException
+import java.net.URL
+import java.nio.file.Files
+import java.nio.file.Paths
+
+import akka.actor.ActorSystem
+import akka.event.Logging.ErrorLevel
+import akka.stream.scaladsl.Source
+import akka.util.ByteString
+import pureconfig.loadConfigOrThrow
+import whisk.common.Logging
+import whisk.common.LoggingMarkers
+import whisk.common.TransactionId
+import whisk.core.containerpool.ContainerId
+import whisk.core.containerpool.ContainerAddress
+import whisk.core.containerpool.docker.ProcessRunner
+import scala.concurrent.duration.Duration
+import scala.concurrent.ExecutionContext
+import scala.concurrent.Future
+import scala.concurrent.blocking
+import scala.concurrent.duration._
+import scala.util.Failure
+import scala.util.Success
+import scala.util.Try
+
+import io.fabric8.kubernetes.client.ConfigBuilder
+import spray.json._
+import spray.json.DefaultJsonProtocol._
+import io.fabric8.kubernetes.client.DefaultKubernetesClient
+import io.fabric8.kubernetes.client.utils.URLUtils
+import okhttp3.Request
+
+/**
+ * Configuration for kubernetes client command timeouts.
+ */
+case class KubernetesClientTimeoutConfig(run: Duration, rm: Duration, inspect: 
Duration, logs: Duration)
+
+/**
+ * Serves as interface to the kubectl CLI tool.
+ *
+ * Be cautious with the ExecutionContext passed to this, as the
+ * calls to the CLI are blocking.
+ *
+ * You only need one instance (and you shouldn't get more).
+ */
+class KubernetesClient(
+  timeouts: KubernetesClientTimeoutConfig = 
loadConfigOrThrow[KubernetesClientTimeoutConfig](
+"whisk.kubernetes.timeouts"))(executionContext: ExecutionContext)(implicit 
log: Logging, as: ActorSystem)
+extends KubernetesApi
+with ProcessRunner {
+  implicit private val ec = executionContext
+  implicit private val kubeRestClient = new DefaultKubernetesClient(
+new ConfigBuilder()
+  .withConnectionTimeout(timeouts.logs.toMillis.toInt)
+  .withRequestTimeout(timeouts.logs.toMillis.toInt)
+  .build())
+
+  // Determines how to run kubectl. Failure to find a kubectl binary implies
+  // a failure to initialize this instance of KubernetesClient.
+  protected val kubectlCmd: Seq[String] = {
+val alternatives = List("/usr/bin/kubectl", "/usr/local/bin/kubectl")
+
+val kubectlBin = Try {
+  alternatives.find(a => Files.isExecutable(Paths.get(a))).get
+} getOrElse {
+  throw new FileNotFoundException(s"Couldn't locate kubectl binary (tried: 
${alternatives.mkString(", ")}).")
+}
+
+Seq(kubectlBin)
+  }
+
+  def run(image: String, name: String, environment: Map[String, String] = 
Map(), labels: Map[String, String] = Map())(
+implicit transid: TransactionId): Future[ContainerId] = {
+val environmentArgs = environment.flatMap {
+  case (key, value) => Seq("--env", s"$key=$value")
+}.toSeq
+
+val labelArgs = labels.map {
+  case (key, value) => s"$key=$value"
+} match {
+  case Seq() => Seq()
+  case pairs => Seq("-l") ++ pairs
+}
 
 Review comment:
   I wouldn't call it a bug. The code does work for multiple labels, in the way 
I would expect if I did pass multiple labels. I get what you're saying about 
changing the code to work for one label since that's how we're currently using 
it, but to me that conflicts with how one might generically use `kubectl` 
itself. I don't feel that strongly about it, though, especially in light of 
@dgrove-oss attempt to obviate it. :)


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


[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-01-31 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r165083489
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/kubernetes/KubernetesClient.scala
 ##
 @@ -0,0 +1,222 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes
+
+import java.io.FileNotFoundException
+import java.net.URL
+import java.nio.file.Files
+import java.nio.file.Paths
+
+import akka.actor.ActorSystem
+import akka.event.Logging.ErrorLevel
+import akka.stream.scaladsl.Source
+import akka.util.ByteString
+import pureconfig.loadConfigOrThrow
+import whisk.common.Logging
+import whisk.common.LoggingMarkers
+import whisk.common.TransactionId
+import whisk.core.containerpool.ContainerId
+import whisk.core.containerpool.ContainerAddress
+import whisk.core.containerpool.docker.ProcessRunner
+import scala.concurrent.duration.Duration
+import scala.concurrent.ExecutionContext
+import scala.concurrent.Future
+import scala.concurrent.blocking
+import scala.concurrent.duration._
+import scala.util.Failure
+import scala.util.Success
+import scala.util.Try
+
+import io.fabric8.kubernetes.client.ConfigBuilder
+import spray.json._
+import spray.json.DefaultJsonProtocol._
+import io.fabric8.kubernetes.client.DefaultKubernetesClient
+import io.fabric8.kubernetes.client.utils.URLUtils
+import okhttp3.Request
+
+/**
+ * Configuration for kubernetes client command timeouts.
+ */
+case class KubernetesClientTimeoutConfig(run: Duration, rm: Duration, inspect: 
Duration, logs: Duration)
+
+/**
+ * Serves as interface to the kubectl CLI tool.
+ *
+ * Be cautious with the ExecutionContext passed to this, as the
+ * calls to the CLI are blocking.
+ *
+ * You only need one instance (and you shouldn't get more).
+ */
+class KubernetesClient(
+  timeouts: KubernetesClientTimeoutConfig = 
loadConfigOrThrow[KubernetesClientTimeoutConfig](
+"whisk.kubernetes.timeouts"))(executionContext: ExecutionContext)(implicit 
log: Logging, as: ActorSystem)
+extends KubernetesApi
+with ProcessRunner {
+  implicit private val ec = executionContext
+  implicit private val kubeRestClient = new DefaultKubernetesClient(
+new ConfigBuilder()
+  .withConnectionTimeout(timeouts.logs.toMillis.toInt)
+  .withRequestTimeout(timeouts.logs.toMillis.toInt)
+  .build())
+
+  // Determines how to run kubectl. Failure to find a kubectl binary implies
+  // a failure to initialize this instance of KubernetesClient.
+  protected val kubectlCmd: Seq[String] = {
+val alternatives = List("/usr/bin/kubectl", "/usr/local/bin/kubectl")
+
+val kubectlBin = Try {
+  alternatives.find(a => Files.isExecutable(Paths.get(a))).get
+} getOrElse {
+  throw new FileNotFoundException(s"Couldn't locate kubectl binary (tried: 
${alternatives.mkString(", ")}).")
+}
+
+Seq(kubectlBin)
+  }
+
+  def run(image: String, name: String, environment: Map[String, String] = 
Map(), labels: Map[String, String] = Map())(
+implicit transid: TransactionId): Future[ContainerId] = {
+val environmentArgs = environment.flatMap {
+  case (key, value) => Seq("--env", s"$key=$value")
+}.toSeq
+
+val labelArgs = labels.map {
+  case (key, value) => s"$key=$value"
+} match {
+  case Seq() => Seq()
+  case pairs => Seq("-l") ++ pairs
+}
 
 Review comment:
   When selecting by multiple labels, you can either use multiple `"-l"`flags 
or a single `"-l"` with a comma-delimited list. The logic for the former is 
"any can match" and the logic for the latter is "all must match". At least I 
think that's how it works. ;)
   
   Right now, I believe we only ever pass one label anyway, so I'm inclined to 
leave it as is for now. 


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


[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-01-30 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r164815549
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/kubernetes/KubernetesClient.scala
 ##
 @@ -0,0 +1,222 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes
+
+import java.io.FileNotFoundException
+import java.net.URL
+import java.nio.file.Files
+import java.nio.file.Paths
+
+import akka.actor.ActorSystem
+import akka.event.Logging.ErrorLevel
+import akka.stream.scaladsl.Source
+import akka.util.ByteString
+import pureconfig.loadConfigOrThrow
+import whisk.common.Logging
+import whisk.common.LoggingMarkers
+import whisk.common.TransactionId
+import whisk.core.containerpool.ContainerId
+import whisk.core.containerpool.ContainerAddress
+import whisk.core.containerpool.docker.ProcessRunner
+import scala.concurrent.duration.Duration
+import scala.concurrent.ExecutionContext
+import scala.concurrent.Future
+import scala.concurrent.blocking
+import scala.concurrent.duration._
+import scala.util.Failure
+import scala.util.Success
+import scala.util.Try
+
+import io.fabric8.kubernetes.client.ConfigBuilder
+import spray.json._
+import spray.json.DefaultJsonProtocol._
+import io.fabric8.kubernetes.client.DefaultKubernetesClient
+import io.fabric8.kubernetes.client.utils.URLUtils
+import okhttp3.Request
+
+/**
+ * Configuration for kubernetes client command timeouts.
+ */
+case class KubernetesClientTimeoutConfig(run: Duration, rm: Duration, inspect: 
Duration, logs: Duration)
+
+/**
+ * Serves as interface to the kubectl CLI tool.
+ *
+ * Be cautious with the ExecutionContext passed to this, as the
+ * calls to the CLI are blocking.
+ *
+ * You only need one instance (and you shouldn't get more).
+ */
+class KubernetesClient(
+  timeouts: KubernetesClientTimeoutConfig = 
loadConfigOrThrow[KubernetesClientTimeoutConfig](
+"whisk.kubernetes.timeouts"))(executionContext: ExecutionContext)(implicit 
log: Logging, as: ActorSystem)
+extends KubernetesApi
+with ProcessRunner {
+  implicit private val ec = executionContext
+  implicit private val kubeRestClient = new DefaultKubernetesClient(
+new ConfigBuilder()
+  .withConnectionTimeout(timeouts.logs.toMillis.toInt)
+  .withRequestTimeout(timeouts.logs.toMillis.toInt)
+  .build())
+
+  // Determines how to run kubectl. Failure to find a kubectl binary implies
+  // a failure to initialize this instance of KubernetesClient.
+  protected val kubectlCmd: Seq[String] = {
+val alternatives = List("/usr/bin/kubectl", "/usr/local/bin/kubectl")
+
+val kubectlBin = Try {
+  alternatives.find(a => Files.isExecutable(Paths.get(a))).get
+} getOrElse {
+  throw new FileNotFoundException(s"Couldn't locate kubectl binary (tried: 
${alternatives.mkString(", ")}).")
+}
+
+Seq(kubectlBin)
+  }
+
+  def run(image: String, name: String, environment: Map[String, String] = 
Map(), labels: Map[String, String] = Map())(
+implicit transid: TransactionId): Future[ContainerId] = {
+val environmentArgs = environment.flatMap {
+  case (key, value) => Seq("--env", s"$key=$value")
+}.toSeq
+
+val labelArgs = labels.map {
+  case (key, value) => s"$key=$value"
+} match {
+  case Seq() => Seq()
+  case pairs => Seq("-l") ++ pairs
+}
+
+val runArgs = Seq(
+  "run",
+  name,
+  "--image",
+  image,
+  "--generator",
+  "run-pod/v1",
+  "--restart",
+  "Always",
+  "--limits",
+  "memory=256Mi") ++ environmentArgs ++ labelArgs
+
+runCmd(runArgs, timeouts.run)
+  .map { _ =>
+name
+  }
+  .map(ContainerId.apply)
+  }
+
+  def inspectIPAddress(id: ContainerId)(implicit transid: TransactionId): 
Future[ContainerAddress] = {
+Future {
+  blocking {
+val pod =
+  
kubeRestClient.pods().withName(id.asString).waitUntilReady(timeouts.inspect.length,
 timeouts.inspect.unit)
+ContainerAddress(pod.getStatus().getPodIP())
+  }
+}.recoverWith {
+  case e =>
+log.error(this, 

[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-01-30 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r164812589
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/kubernetes/KubernetesClient.scala
 ##
 @@ -0,0 +1,222 @@
+/*
+ * 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 whisk.core.containerpool.kubernetes
+
+import java.io.FileNotFoundException
+import java.net.URL
+import java.nio.file.Files
+import java.nio.file.Paths
+
+import akka.actor.ActorSystem
+import akka.event.Logging.ErrorLevel
+import akka.stream.scaladsl.Source
+import akka.util.ByteString
+import pureconfig.loadConfigOrThrow
+import whisk.common.Logging
+import whisk.common.LoggingMarkers
+import whisk.common.TransactionId
+import whisk.core.containerpool.ContainerId
+import whisk.core.containerpool.ContainerAddress
+import whisk.core.containerpool.docker.ProcessRunner
+import scala.concurrent.duration.Duration
+import scala.concurrent.ExecutionContext
+import scala.concurrent.Future
+import scala.concurrent.blocking
+import scala.concurrent.duration._
+import scala.util.Failure
+import scala.util.Success
+import scala.util.Try
+
+import io.fabric8.kubernetes.client.ConfigBuilder
+import spray.json._
+import spray.json.DefaultJsonProtocol._
+import io.fabric8.kubernetes.client.DefaultKubernetesClient
+import io.fabric8.kubernetes.client.utils.URLUtils
+import okhttp3.Request
+
+/**
+ * Configuration for kubernetes client command timeouts.
+ */
+case class KubernetesClientTimeoutConfig(run: Duration, rm: Duration, inspect: 
Duration, logs: Duration)
+
+/**
+ * Serves as interface to the kubectl CLI tool.
+ *
+ * Be cautious with the ExecutionContext passed to this, as the
+ * calls to the CLI are blocking.
+ *
+ * You only need one instance (and you shouldn't get more).
+ */
+class KubernetesClient(
+  timeouts: KubernetesClientTimeoutConfig = 
loadConfigOrThrow[KubernetesClientTimeoutConfig](
+"whisk.kubernetes.timeouts"))(executionContext: ExecutionContext)(implicit 
log: Logging, as: ActorSystem)
+extends KubernetesApi
+with ProcessRunner {
+  implicit private val ec = executionContext
+  implicit private val kubeRestClient = new DefaultKubernetesClient(
+new ConfigBuilder()
+  .withConnectionTimeout(timeouts.logs.toMillis.toInt)
+  .withRequestTimeout(timeouts.logs.toMillis.toInt)
+  .build())
+
+  // Determines how to run kubectl. Failure to find a kubectl binary implies
+  // a failure to initialize this instance of KubernetesClient.
+  protected val kubectlCmd: Seq[String] = {
+val alternatives = List("/usr/bin/kubectl", "/usr/local/bin/kubectl")
+
+val kubectlBin = Try {
+  alternatives.find(a => Files.isExecutable(Paths.get(a))).get
+} getOrElse {
+  throw new FileNotFoundException(s"Couldn't locate kubectl binary (tried: 
${alternatives.mkString(", ")}).")
+}
+
+Seq(kubectlBin)
+  }
+
+  def run(image: String, name: String, environment: Map[String, String] = 
Map(), labels: Map[String, String] = Map())(
+implicit transid: TransactionId): Future[ContainerId] = {
+val environmentArgs = environment.flatMap {
+  case (key, value) => Seq("--env", s"$key=$value")
+}.toSeq
+
+val labelArgs = labels.map {
+  case (key, value) => s"$key=$value"
+} match {
+  case Seq() => Seq()
+  case pairs => Seq("-l") ++ pairs
+}
+
+val runArgs = Seq(
+  "run",
+  name,
+  "--image",
+  image,
+  "--generator",
+  "run-pod/v1",
+  "--restart",
+  "Always",
+  "--limits",
+  "memory=256Mi") ++ environmentArgs ++ labelArgs
+
+runCmd(runArgs, timeouts.run)
+  .map { _ =>
+name
+  }
+  .map(ContainerId.apply)
+  }
 
 Review comment:
   Good call


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


[GitHub] jcrossley3 commented on a change in pull request #3219: Kubernetes ContainerFactoryProvider implementation

2018-01-30 Thread GitBox
jcrossley3 commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r164811802
 
 

 ##
 File path: 
core/invoker/src/main/scala/whisk/core/containerpool/docker/DockerContainer.scala
 ##
 @@ -37,7 +37,7 @@ import akka.stream.scaladsl.{Framing, Source}
 import akka.stream.stage._
 import akka.util.ByteString
 import spray.json._
-import whisk.core.containerpool.logging.LogLine
+import whisk.core.containerpool.logging.{LogLine => CoreLogLine}
 import whisk.http.Messages
 
 Review comment:
   Don't think there's a good reason now, but may have been necessary due to 
the state of our fork at the time. I'll fix once @bwmcadams confirms


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