markusthoemmes commented on a change in pull request #3219: Kubernetes 
ContainerFactoryProvider implementation
URL: 
https://github.com/apache/incubator-openwhisk/pull/3219#discussion_r164699548
 
 

 ##########
 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, s"Failed to get IP of Pod '${id.asString}' within 
timeout: ${e.getClass} - ${e.getMessage}")
+        Future.failed(new Exception(s"Failed to get IP of Pod 
'${id.asString}'"))
+    }
+  }
+
+  def rm(id: ContainerId)(implicit transid: TransactionId): Future[Unit] =
+    runCmd(Seq("delete", "--now", "pod", id.asString), timeouts.rm).map(_ => 
())
+
+  def rm(key: String, value: String)(implicit transid: TransactionId): 
Future[Unit] =
+    runCmd(Seq("delete", "--now", "pod", "-l", s"$key=$value"), 
timeouts.rm).map(_ => ())
+
+  def logs(id: ContainerId, sinceTime: String)(implicit transid: 
TransactionId): Source[ByteString, Any] = {
+
+    Source.fromFuture(Future {
+      blocking {
+        val sinceTimePart = if (!sinceTime.isEmpty) {
+          s"&sinceTime=${sinceTime}"
+        } else ""
+        val url = new URL(
+          URLUtils.join(
+            kubeRestClient.getMasterUrl.toString,
+            "api",
+            "v1",
+            "namespaces",
+            kubeRestClient.getNamespace,
+            "pods",
+            id.asString,
+            "log?timestamps=true" ++ sinceTimePart))
+        val request = new Request.Builder().get().url(url).build
 
 Review comment:
   Would it make sense to use Akka's URI building capabilities here? Could get 
much more readable.
   
   ```scala
   val sinceTime = Some("abc")
   
   val path = Path / "api" / "v1" / "namespaces" / "namespace" / "pods" / "pod"
   val query = Seq("timestamp" -> true.toString) ++ sinceTime.map(time => 
"sinceTime" -> time)
   val url = Uri("https://google.de";)
     .withPath(path)
     .withQuery(Query(query: _*))
   ```
   
   That assumes that `sinceTime` is an `Option[String]` to denote the possible 
absence of it in the type. In general, it'll make your code much easier to 
grasp if you make use of `Option` whenever it is possible that something is 
missing rather than passing an empty String and checking for it to be empty.

----------------------------------------------------------------
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:
[email protected]


With regards,
Apache Git Services

Reply via email to