pjfanning commented on code in PR #218:
URL: https://github.com/apache/pekko-management/pull/218#discussion_r1598329574


##########
lease-kubernetes/src/main/scala/org/apache/pekko/coordination/lease/kubernetes/internal/AbstractKubernetesApiImpl.scala:
##########
@@ -0,0 +1,191 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * license agreements; and to You under the Apache License, version 2.0:
+ *
+ *   https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * This file is part of the Apache Pekko project, which was derived from Akka.
+ */
+
+/*
+ * Copyright (C) 2017-2021 Lightbend Inc. <https://www.lightbend.com>
+ */
+
+package org.apache.pekko.coordination.lease.kubernetes.internal
+
+import org.apache.pekko
+import pekko.Done
+import pekko.actor.ActorSystem
+import pekko.annotation.InternalApi
+import pekko.coordination.lease.kubernetes.{ KubernetesApi, 
KubernetesSettings, LeaseResource }
+import pekko.coordination.lease.{ LeaseException, LeaseTimeoutException }
+import pekko.event.{ LogSource, Logging, LoggingAdapter }
+import pekko.http.scaladsl.model._
+import pekko.http.scaladsl.model.headers.{ Authorization, OAuth2BearerToken }
+import pekko.http.scaladsl.unmarshalling.Unmarshal
+import pekko.http.scaladsl.{ ConnectionContext, Http, HttpExt, 
HttpsConnectionContext }
+import pekko.pattern.after
+import pekko.pki.kubernetes.PemManagersProvider
+
+import java.nio.charset.StandardCharsets
+import java.nio.file.{ Files, Paths }
+import java.security.{ KeyStore, SecureRandom }
+import javax.net.ssl.{ KeyManager, KeyManagerFactory, SSLContext, TrustManager 
}
+import scala.collection.immutable
+import scala.concurrent.Future
+import scala.util.control.NonFatal
+
+/**
+ * Could be shared between leases: 
https://github.com/akka/akka-management/issues/680
+ * INTERNAL API
+ */
+@InternalApi private[pekko] abstract class AbstractKubernetesApiImpl(system: 
ActorSystem, settings: KubernetesSettings)
+    extends KubernetesApi
+    with KubernetesJsonSupport {
+
+  import system.dispatcher
+
+  protected implicit val sys: ActorSystem = system
+  protected val log: LoggingAdapter = Logging(system, 
getClass)(LogSource.fromClass)
+  private val http: HttpExt = Http()(system)
+
+  private lazy val sslContext: SSLContext = {
+    val certificates = PemManagersProvider.loadCertificates(settings.apiCaPath)
+    val factory = 
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
+    val keyStore = KeyStore.getInstance("PKCS12")
+    keyStore.load(null)
+    factory.init(keyStore, Array.empty)
+    val km: Array[KeyManager] = factory.getKeyManagers
+    val tm: Array[TrustManager] =
+      PemManagersProvider.buildTrustManagers(certificates)
+    val random: SecureRandom = new SecureRandom
+    val sslContext = SSLContext.getInstance("TLSv1.2")
+    sslContext.init(km, tm, random)
+    sslContext
+  }
+
+  private lazy val clientSslContext: HttpsConnectionContext = 
ConnectionContext.httpsClient(sslContext)
+
+  protected val namespace: String =
+    
settings.namespace.orElse(readConfigVarFromFilesystem(settings.namespacePath, 
"namespace")).getOrElse("default")
+
+  protected val scheme: String = if (settings.secure) "https" else "http"
+  private lazy val apiToken = 
readConfigVarFromFilesystem(settings.apiTokenPath, "api-token").getOrElse("")
+  private lazy val headers = if (settings.secure) 
immutable.Seq(Authorization(OAuth2BearerToken(apiToken))) else Nil
+
+  log.debug("kubernetes access namespace: {}. Secure: {}", namespace, 
settings.secure)
+
+  protected def createLeaseResource(name: String): 
Future[Option[LeaseResource]]
+
+  protected def getLeaseResource(name: String): Future[Option[LeaseResource]]
+
+  protected def pathForLease(name: String): Uri.Path
+
+  override def readOrCreateLeaseResource(name: String): Future[LeaseResource] 
= {
+    // TODO backoff retry
+    val maxTries = 5
+
+    def loop(tries: Int = 0): Future[LeaseResource] = {
+      log.debug("Trying to create lease {}", tries)
+      for {
+        olr <- getLeaseResource(name)
+        lr <- olr match {
+          case Some(found) =>
+            log.debug("{} already exists. Returning {}", name, found)
+            Future.successful(found)
+          case None =>
+            log.info("lease {} does not exist, creating", name)
+            createLeaseResource(name).flatMap {
+              case Some(created) => Future.successful(created)
+              case None =>
+                if (tries < maxTries) loop(tries + 1)
+                else Future.failed(new LeaseException(s"Unable to create or 
read lease after $maxTries tries"))
+            }
+        }
+      } yield lr

Review Comment:
   This is the correct thing to do.
   
   Code moved from around should not be modified unless absolutely necessary. 
Non urgent changes to the moved code could be submitted as separate PRs later.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to