You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@openwhisk.apache.org by GitBox <gi...@apache.org> on 2021/06/08 09:06:24 UTC

[GitHub] [openwhisk] ningyougang commented on a change in pull request #5125: [New Scheduler] Implement FPCInvokerReactive

ningyougang commented on a change in pull request #5125:
URL: https://github.com/apache/openwhisk/pull/5125#discussion_r647260192



##########
File path: core/invoker/src/main/scala/org/apache/openwhisk/core/invoker/FPCInvokerReactive.scala
##########
@@ -0,0 +1,483 @@
+/*
+ * 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.invoker
+
+import akka.Done
+import akka.actor.{ActorRef, ActorRefFactory, ActorSystem, CoordinatedShutdown, Props}
+import akka.grpc.GrpcClientSettings
+import akka.http.scaladsl.server.Directives._
+import akka.http.scaladsl.server.Route
+import com.ibm.etcd.api.Event.EventType
+import com.ibm.etcd.client.kv.KvClient.Watch
+import com.ibm.etcd.client.kv.WatchUpdate
+import org.apache.kafka.clients.producer.RecordMetadata
+import org.apache.openwhisk.common._
+import org.apache.openwhisk.core.ack.{ActiveAck, HealthActionAck, MessagingActiveAck, UserEventSender}
+import org.apache.openwhisk.core.connector._
+import org.apache.openwhisk.core.containerpool._
+import org.apache.openwhisk.core.containerpool.logging.LogStoreProvider
+import org.apache.openwhisk.core.containerpool.v2._
+import org.apache.openwhisk.core.database.{UserContext, _}
+import org.apache.openwhisk.core.entity._
+import org.apache.openwhisk.core.etcd.EtcdKV.ContainerKeys.{containerPrefix}
+import org.apache.openwhisk.core.etcd.EtcdKV.QueueKeys.queue
+import org.apache.openwhisk.core.etcd.EtcdKV.{ContainerKeys, SchedulerKeys}
+import org.apache.openwhisk.core.etcd.EtcdType._
+import org.apache.openwhisk.core.etcd.{EtcdClient, EtcdConfig}
+import org.apache.openwhisk.core.scheduler.{SchedulerEndpoints, SchedulerStates}
+import org.apache.openwhisk.core.service.{DataManagementService, EtcdWorker, LeaseKeepAliveService, WatcherService}
+import org.apache.openwhisk.core.{ConfigKeys, WarmUp, WhiskConfig}
+import org.apache.openwhisk.grpc.{ActivationServiceClient, FetchRequest}
+import org.apache.openwhisk.spi.SpiLoader
+import pureconfig._
+import pureconfig.generic.auto._
+
+import scala.collection.JavaConverters._
+import scala.collection.concurrent.TrieMap
+import scala.concurrent.duration._
+import scala.concurrent.{ExecutionContext, ExecutionContextExecutor, Future}
+import scala.util.{Failure, Success, Try}
+
+case class GrpcServiceConfig(tls: Boolean)
+
+object FPCInvokerReactive extends InvokerProvider {
+
+  override def instance(
+    config: WhiskConfig,
+    instance: InvokerInstanceId,
+    producer: MessageProducer,
+    poolConfig: ContainerPoolConfig,
+    limitsConfig: ConcurrencyLimitConfig)(implicit actorSystem: ActorSystem, logging: Logging): InvokerCore =
+    new FPCInvokerReactive(config, instance, producer, poolConfig, limitsConfig)
+
+  var invokerHealthManagerActor: Option[ActorRef] = None
+}
+
+class FPCInvokerReactive(config: WhiskConfig,
+                         instance: InvokerInstanceId,
+                         producer: MessageProducer,
+                         poolConfig: ContainerPoolConfig =
+                           loadConfigOrThrow[ContainerPoolConfig](ConfigKeys.containerPool),
+                         limitsConfig: ConcurrencyLimitConfig = loadConfigOrThrow[ConcurrencyLimitConfig](
+                           ConfigKeys.concurrencyLimit))(implicit actorSystem: ActorSystem, logging: Logging)
+    extends InvokerCore {
+
+  implicit val ec: ExecutionContext = actorSystem.dispatcher
+  implicit val exe: ExecutionContextExecutor = actorSystem.dispatcher
+  implicit val cfg: WhiskConfig = config
+
+  private val logsProvider = SpiLoader.get[LogStoreProvider].instance(actorSystem)
+  logging.info(this, s"LogStoreProvider: ${logsProvider.getClass}")
+
+  private val etcdClient = EtcdClient(loadConfigOrThrow[EtcdConfig](ConfigKeys.etcd).hosts)
+
+  private val grpcConfig = loadConfigOrThrow[GrpcServiceConfig](ConfigKeys.schedulerGrpcService)
+
+  val watcherService: ActorRef = actorSystem.actorOf(WatcherService.props(etcdClient))
+
+  private val leaseService =
+    actorSystem.actorOf(LeaseKeepAliveService.props(etcdClient, instance, watcherService))
+
+  private val etcdWorkerFactory =
+    (f: ActorRefFactory) => f.actorOf(EtcdWorker.props(etcdClient, leaseService))
+
+  val dataManagementService: ActorRef =
+    actorSystem.actorOf(DataManagementService.props(watcherService, etcdWorkerFactory))
+
+  private val warmedSchedulers = TrieMap[String, String]()
+  private var warmUpWatcher: Option[Watch] = None
+
+  /**
+   * Factory used by the ContainerProxy to physically create a new container.
+   *
+   * Create and initialize the container factory before kicking off any other
+   * task or actor because further operation does not make sense if something
+   * goes wrong here. Initialization will throw an exception upon failure.
+   */
+  private val containerFactory =
+    SpiLoader
+      .get[ContainerFactoryProvider]
+      .instance(
+        actorSystem,
+        logging,
+        config,
+        instance,
+        Map(
+          "--cap-drop" -> Set("NET_RAW", "NET_ADMIN"),
+          "--ulimit" -> Set("nofile=1024:1024"),
+          "--pids-limit" -> Set("1024")) ++ logsProvider.containerParameters)
+  containerFactory.init()
+
+  CoordinatedShutdown(actorSystem)
+    .addTask(CoordinatedShutdown.PhaseBeforeActorSystemTerminate, "cleanup runtime containers") { () =>
+      containerFactory.cleanup()
+      Future.successful(Done)
+    }
+
+  /** Initialize needed databases */
+  private val entityStore = WhiskEntityStore.datastore()
+  private val activationStore =
+    SpiLoader.get[ActivationStoreProvider].instance(actorSystem, logging)
+
+  private val authStore = WhiskAuthStore.datastore()
+
+  private val namespaceBlacklist: NamespaceBlacklist = new NamespaceBlacklist(authStore)
+
+  Scheduler.scheduleWaitAtMost(loadConfigOrThrow[NamespaceBlacklistConfig](ConfigKeys.blacklist).pollInterval) { () =>
+    logging.debug(this, "running background job to update blacklist")
+    namespaceBlacklist.refreshBlacklist()(ec, TransactionId.invoker).andThen {
+      case Success(set) => logging.info(this, s"updated blacklist to ${set.size} entries")
+      case Failure(t)   => logging.error(this, s"error on updating the blacklist: ${t.getMessage}")
+    }
+  }
+
+  val containerProxyTimeoutConfig = loadConfigOrThrow[ContainerProxyTimeoutConfig](ConfigKeys.containerProxyTimeouts)
+
+  private def getWarmedContainerLimit(invocationNamespace: String): Future[(Int, FiniteDuration)] = {
+    implicit val trasnid = TransactionId.unknown
+    Identity
+      .get(authStore, EntityName(invocationNamespace))(trasnid)
+      .map { identity =>
+        val warmedContainerKeepingCount = identity.limits.warmedContainerKeepingCount.getOrElse(1)
+        val warmedContainerKeepingTimeout = Try {
+          identity.limits.warmedContainerKeepingTimeout.map(Duration(_).toSeconds.seconds).get
+        }.getOrElse(containerProxyTimeoutConfig.keepingDuration)
+        (warmedContainerKeepingCount, warmedContainerKeepingTimeout)

Review comment:
       `warmedContainerKeepingCount, warmedContainerKeepingTimeout` is for `avoid cold start`, doesn't remove one namespace's all warmed containers when container timeout happens, keeps the right amount warmed containers running for some time, when invocation happens next time, have no need to create a container, just uses the non-deleted warmed container.
   
   for a specified namespace, we can configure the warmedContainerKeepingCount, warmedContainerKeepingTimeout in  subjects's limit doucment, e.g.
   ![image](https://user-images.githubusercontent.com/11749867/121156749-9027eb80-c87b-11eb-81ba-128cc1f70cb8.png)
   
   If doesn't configure `warmedContainerKeepingCount, warmedContainerKeepingTimeout` in couchdb, it will use default configuration (warmedContainerKeepingCount: 1, warmedContainerKeepingTimeout: "60 minutes")
   
   




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

For queries about this service, please contact Infrastructure at:
users@infra.apache.org