Iilun commented on code in PR #218: URL: https://github.com/apache/pekko-management/pull/218#discussion_r1598325966
########## lease-kubernetes/src/main/scala/org/apache/pekko/coordination/lease/kubernetes/internal/NativeKubernetesApiImpl.scala: ########## @@ -0,0 +1,196 @@ +/* + * 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.pekko.coordination.lease.kubernetes.internal + +import org.apache.pekko +import pekko.actor.ActorSystem +import pekko.annotation.InternalApi +import pekko.coordination.lease.kubernetes.internal.NativeKubernetesApiImpl.RFC3339MICRO_FORMATTER +import pekko.coordination.lease.kubernetes.{ KubernetesSettings, LeaseResource } +import pekko.coordination.lease.LeaseException +import pekko.http.scaladsl.marshalling.Marshal +import pekko.http.scaladsl.model._ +import pekko.http.scaladsl.unmarshalling.Unmarshal +import java.time.{ Instant, LocalDateTime, ZoneId } +import java.time.format.{ DateTimeFormatter, DateTimeFormatterBuilder } +import java.time.temporal.ChronoField +import scala.concurrent.Future + +object NativeKubernetesApiImpl { + // From https://github.com/kubernetes-client/java/blob/e50fb2a6f30d4f07e3922430307e5e09058aaea1/kubernetes/src/main/java/io/kubernetes/client/openapi/JSON.java#L57 + val RFC3339MICRO_FORMATTER: DateTimeFormatter = + new DateTimeFormatterBuilder().parseDefaulting(ChronoField.OFFSET_SECONDS, + 0).append(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")).optionalStart.appendFraction( + ChronoField.NANO_OF_SECOND, 6, 6, true).optionalEnd.appendLiteral("Z").toFormatter +} + +/** + * Could be shared between leases: https://github.com/akka/akka-management/issues/680 + * INTERNAL API + */ +@InternalApi private[pekko] class NativeKubernetesApiImpl(system: ActorSystem, settings: KubernetesSettings) + extends AbstractKubernetesApiImpl(system, settings) { + + import system.dispatcher + + /** + * Update the named resource. + * + * Must [[readOrCreateLeaseResource]] to first to get a resource version. + * + * Can return one of three things: + * - Future.Failure, e.g. timed out waiting for k8s api server to respond + * - Future.sucess[Left(resource)]: the update failed due to version not matching current in the k8s api server. + * In this case the current resource is returned so the version can be used for subsequent calls + * - Future.sucess[Right(resource)]: Returns the LeaseResource that contains the clientName and new version. + * The new version should be used for any subsequent calls + */ + override def updateLeaseResource( + leaseName: String, + ownerName: String, + version: String, + time: Long = System.currentTimeMillis()): Future[Either[LeaseResource, LeaseResource]] = { + val lcr = NativeLeaseResource(Metadata(leaseName, Some(version)), NativeSpec(ownerName, currentTimeRFC3339)) + for { + entity <- Marshal(lcr).to[RequestEntity] + response <- { + log.debug("updating {} to {}", leaseName, lcr) + makeRequest( + requestForPath(pathForLease(leaseName), method = HttpMethods.PUT, entity), + s"Timed out updating lease [$leaseName] to owner [$ownerName]. It is not known if the update happened") + } + result <- response.status match { + case StatusCodes.OK => + Unmarshal(response.entity) + .to[NativeLeaseResource] + .map(updatedLcr => { + log.debug("LCR after update: {}", updatedLcr) + Right(toLeaseResource(updatedLcr)) + }) + case StatusCodes.Conflict => + getLeaseResource(leaseName).flatMap { + case None => + Future.failed( + new LeaseException(s"GET after PUT conflict did not return a lease. Lease[$leaseName-$ownerName]")) + case Some(lr) => + log.debug("LeaseResource read after conflict: {}", lr) + Future.successful(Left(lr)) + } + case StatusCodes.Unauthorized => + handleUnauthorized(response) + case unexpected => + Unmarshal(response.entity) + .to[String] + .flatMap(body => { + Future.failed( + new LeaseException( + s"PUT for lease $leaseName returned unexpected status code $unexpected. Body: $body")) + }) + } + } yield result + } + + override def getLeaseResource(name: String): Future[Option[LeaseResource]] = { + val fResponse = makeRequest(requestForPath(pathForLease(name)), s"Timed out reading lease $name") + for { + response <- fResponse Review Comment: This is the syntax used by the existing class (`KubernetesApiImpl`) to handle the futures ########## 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 could be changed, but every line in AbstractKubernetesApiImpl is simply moved from the previous classes so I did no modification to existing code -- 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]
