openwhisk-issues mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From GitBox <...@apache.org>
Subject [GitHub] [incubator-openwhisk] ddragosd commented on a change in pull request #4326: Invoker backpressure
Date Tue, 19 Mar 2019 00:18:30 GMT
ddragosd commented on a change in pull request #4326: Invoker backpressure
URL: https://github.com/apache/incubator-openwhisk/pull/4326#discussion_r266677478
 
 

 ##########
 File path: core/invoker/src/main/scala/org/apache/openwhisk/core/containerpool/AkkaClusterContainerResourceManager.scala
 ##########
 @@ -0,0 +1,376 @@
+/*
+ * 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.containerpool
+import akka.Done
+import akka.actor.Actor
+import akka.actor.ActorRef
+import akka.actor.ActorSystem
+import akka.actor.CoordinatedShutdown
+import akka.actor.Props
+import akka.cluster.Cluster
+import akka.cluster.ddata.DistributedData
+import akka.cluster.ddata.LWWRegister
+import akka.cluster.ddata.LWWRegisterKey
+import akka.cluster.ddata.ORSet
+import akka.cluster.ddata.ORSetKey
+import akka.cluster.ddata.Replicator.Changed
+import akka.cluster.ddata.Replicator.Subscribe
+import akka.cluster.ddata.Replicator.Unsubscribe
+import akka.cluster.ddata.Replicator.Update
+import akka.cluster.ddata.Replicator.UpdateFailure
+import akka.cluster.ddata.Replicator.UpdateSuccess
+import akka.cluster.ddata.Replicator.WriteLocal
+import akka.cluster.pubsub.DistributedPubSub
+import akka.cluster.pubsub.DistributedPubSubMediator.Put
+import akka.cluster.pubsub.DistributedPubSubMediator.Send
+import java.time.Instant
+import org.apache.openwhisk.common.Logging
+import org.apache.openwhisk.core.entity.ByteSize
+import org.apache.openwhisk.core.entity.InvokerInstanceId
+import org.apache.openwhisk.core.entity.size._
+import org.apache.openwhisk.utils.NodeStats
+import org.apache.openwhisk.utils.NodeStatsUpdate
+import scala.collection.immutable
+import scala.collection.mutable.ListBuffer
+import scala.concurrent.Future
+import scala.concurrent.duration._
+import scala.util.Try
+
+class AkkaClusterContainerResourceManager(system: ActorSystem,
+                                          instanceId: InvokerInstanceId,
+                                          poolActor: ActorRef,
+                                          poolConfig: ContainerPoolConfig)(implicit logging:
Logging)
+    extends ContainerResourceManager {
+
+  /** cluster state tracking */
+  private var localReservations: Map[ActorRef, Reservation] = Map.empty //this pool's own
reservations
+  private var remoteReservations: Map[Int, List[Reservation]] = Map.empty //other pool's
reservations
+  private var localUnused: Map[ActorRef, ContainerData] = Map.empty // this pool's unused
containers
+  private var remoteUnused
+    : Map[Int, List[RemoteContainerRef]] = Map.empty //invoker akka address -> List[RemoteContainerRef]
+
+  var clusterActionHostStats = Map.empty[String, NodeStats] //track the most recent node
stats per action host (host that is able to run action containers)
+  var clusterActionHostsCount = 0
+  var prewarmsInitialized = false
+  val clusterPoolData: ActorRef =
+    system.actorOf(
+      Props(new ContainerPoolClusterData(instanceId, poolActor)),
+      ContainerPoolClusterData.clusterPoolActorName(instanceId.toInt))
+
+  //invoker keys
+  val InvokerIdsKey = ORSetKey[Int]("invokerIds")
+  //my keys
+  val myId = instanceId.toInt
+  val myReservationsKey = LWWRegisterKey[List[Reservation]]("reservation" + myId)
+  val myUnusedKey = LWWRegisterKey[List[RemoteContainerRef]]("unused" + myId)
+  //remote keys
+  var reservationKeys: immutable.Map[Int, LWWRegisterKey[List[Reservation]]] = Map.empty
+  var unusedKeys: immutable.Map[Int, LWWRegisterKey[List[RemoteContainerRef]]] = Map.empty
+
+  //cachedValues
+  var idMap: immutable.Set[Int] = Set.empty
+
+  def activationStartLogMessage(): String =
+    s"node stats ${clusterActionHostStats} reserved ${localReservations.size} (of max ${poolConfig.clusterManagedResourceMaxStarts})
containers ${reservedSize}MB " +
+      s"${reservedStartCount} pending starts ${reservedStopCount} pending stops " +
+      s"${scheduledStartCount} scheduled starts ${scheduledStopCount} scheduled stops"
+
+  def rescheduleLogMessage() = {
+    s"reservations: ${localReservations.size}"
+  }
+
+  def requestSpace(size: ByteSize) = {
+    val bufferedSize = size * 10 //request 10x the required space to allow for failures and
additional traffic
+    //find idles up to this size
+    val removable = remoteUnused.map(u => u._2.map(u._1 -> _)).flatten.to[ListBuffer]
+    val removed = remove(removable, bufferedSize) //add some buffer so that any accumulating
activations will have better chance
+    if (removed.nonEmpty) {
+      val removing = removed.groupBy(_._1).map(k => k._1 -> k._2.map(_._2)) //group
the removables by invoker, will send single message per invoker
+      logging.info(this, s"requesting removal of ${removed.size} eligible idle containers
${removing}")
+      removing.foreach { r =>
+        clusterPoolData ! RequestReleaseFree(r._1, r._2)
+        //update unusedPool (we won't ask them to be removed twice)
+        remoteUnused = remoteUnused + (r._1 -> remoteUnused(r._1).filterNot(r._2.toSet))
+
+      }
+    }
+
+  }
+
+  def reservedSize = localReservations.values.map(_.size.toMB).sum
+  def remoteReservedSize = remoteReservations.values.map(_.map(_.size.toMB).sum).sum
+  def reservedStartCount = localReservations.values.count {
+    case p: Reservation => p.size.toMB >= 0
+    case _              => false
+  }
+  def reservedStopCount = localReservations.values.count {
+    case p: Reservation => p.size.toMB < 0
+    case _              => false
+  }
+  def scheduledStartCount = localReservations.values.count {
+    case p: Reservation => p.size.toMB >= 0
+    case _              => false
+  }
+  def scheduledStopCount = localReservations.values.count {
+    case p: Reservation => p.size.toMB < 0
+    case _              => false
+  }
+  private var clusterResourcesAvailable
+    : Boolean = false //track to log whenever there is a switch from cluster resources being
available to not being available
+
+  def canLaunch(memory: ByteSize, poolMemory: Long, poolConfig: ContainerPoolConfig): Boolean
= {
+
+    val localRes = localReservations.values.map(_.size) //active local reservations
+    val remoteRes = remoteReservations.values.toList.flatten.map(_.size) //remote/stale reservations
+
+    val allRes = localRes ++ remoteRes
+    //make sure there is at least one node with unreserved mem > memory
+    val canLaunch = clusterHasPotentialMemoryCapacity(memory.toMB, allRes) //consider all
reservations blocking till they are removed during NodeStatsUpdate
+    //log only when changing value
+    if (canLaunch != clusterResourcesAvailable) {
+      if (canLaunch) {
+        logging.info(this, s"cluster can launch action with ${memory.toMB}MB reserved:${reservedSize}")
+      } else {
+        logging.warn(this, s"cluster cannot launch action with ${memory.toMB}MB reserved:${reservedSize}")
+      }
+    }
+    clusterResourcesAvailable = canLaunch
+    canLaunch
+  }
+
+  /** Return true to indicate there is expectation that there is "room" to launch a task
with these memory/cpu/ports specs */
+  def clusterHasPotentialMemoryCapacity(memory: Double, reserve: Iterable[ByteSize]): Boolean
= {
+    //copy AgentStats, then deduct pending tasks
+    var availableResources = clusterActionHostStats.toList.sortBy(_._2.mem).toMap //sort
by mem to match lowest value
+    val inNeedReserved = ListBuffer.empty ++ reserve
+
+    var unmatched = 0
+
+    inNeedReserved.foreach { p =>
+      //for each pending find an available offer that fits
+      availableResources.find(_._2.mem > p.toMB) match {
+        case Some(o) =>
+          availableResources = availableResources + (o._1 -> o._2.copy(mem = o._2.mem
- p.toMB))
+          inNeedReserved -= p
+        case None => unmatched += 1
+      }
+    }
+    unmatched == 0 && availableResources.exists(_._2.mem > memory)
+  }
+
+  /** reservation adjustments */
+  def addReservation(ref: ActorRef, size: ByteSize): Unit = {
+    localReservations = localReservations + (ref -> Reservation(size))
+  }
+  def releaseReservation(ref: ActorRef): Unit = {
+    localReservations = localReservations - ref
+  }
+  def allowMoreStarts(config: ContainerPoolConfig): Boolean =
+    localReservations
+      .count({ case (_, state) => state.size.toMB > 0 }) < config.clusterManagedResourceMaxStarts
//only positive reservations affect ability to start
+
+  class ContainerPoolClusterData(instanceId: InvokerInstanceId, pool: ActorRef) extends Actor
{
+    implicit val cluster = Cluster(system)
+    implicit val ec = context.dispatcher
+    val mediator = DistributedPubSub(system).mediator
+    val replicator = DistributedData(system).replicator
+
+    mediator ! Put(clusterPoolData) //allow point to point messaging based on the actor name:
use Send(/user/<myname>) to send messages to me in the cluster
 
 Review comment:
   why not ```mediator ! Put(self)``` ?

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


With regards,
Apache Git Services

Mime
View raw message