yrenat commented on code in PR #6046:
URL: https://github.com/apache/texera/pull/6046#discussion_r3868401145


##########
computing-unit-managing-service/src/main/scala/org/apache/texera/service/resource/ComputingUnitManagingResource.scala:
##########
@@ -61,18 +67,213 @@ import org.apache.texera.service.util.{
   KubernetesClient
 }
 import org.jooq.{DSLContext, EnumType}
+import org.jooq.impl.DSL.{boolOr, max}
+import org.slf4j.LoggerFactory
 import play.api.libs.json._
 
 import java.sql.Timestamp
 import scala.annotation.unused
 import scala.jdk.CollectionConverters.CollectionHasAsScala
+import scala.util.control.NonFatal
 
 object ComputingUnitManagingResource {
+  private val logger = 
LoggerFactory.getLogger(classOf[ComputingUnitManagingResource])
+
   private def context: DSLContext =
     SqlServer
       .getInstance()
       .createDSLContext()
 
+  private[resource] final class IdleComputingUnitCleanupConfig(
+      val enabled: Boolean,
+      val idleTimeoutMinutes: Long
+  ) {
+    def copy(
+        enabled: Boolean = this.enabled,
+        idleTimeoutMinutes: Long = this.idleTimeoutMinutes
+    ): IdleComputingUnitCleanupConfig =
+      new IdleComputingUnitCleanupConfig(enabled, idleTimeoutMinutes)
+  }
+
+  private[resource] final class IdleComputingUnitCandidate(
+      val unit: WorkflowComputingUnit,
+      val username: Option[String]
+  )
+
+  private[resource] object WorkflowExecutionStatus extends Enumeration {
+    val UninitializedOrReady: Value = Value(0)
+    val Running: Value = Value(1)
+    val Paused: Value = Value(2)
+
+    def toDbStatus(status: Value): java.lang.Short = 
Short.box(status.id.toShort)
+  }
+
+  private[resource] trait KubernetesPodOperations {
+    val podExists: Int => Boolean
+    val deletePod: Int => Unit
+  }
+
+  private[resource] object DefaultKubernetesPodOperations extends 
KubernetesPodOperations {
+    private[resource] var podExistsDelegate: Int => Boolean = 
KubernetesClient.podExists
+    private[resource] var deletePodDelegate: Int => Unit = 
KubernetesClient.deletePod
+
+    override val podExists: Int => Boolean = cuid => podExistsDelegate(cuid)
+    override val deletePod: Int => Unit = cuid => deletePodDelegate(cuid)
+  }
+
+  private[resource] def lastComputingUnitActivityTime(
+      unit: WorkflowComputingUnit,
+      latestUpdateTime: Option[Timestamp],
+      latestStartTime: Option[Timestamp]
+  ): Timestamp =
+    Seq(
+      latestUpdateTime,
+      latestStartTime,
+      Option(unit.getCreationTime)
+    ).flatten.maxBy(_.getTime)
+
+  private[resource] def shouldTerminateIdleComputingUnit(
+      hasActiveExecution: Boolean,
+      lastExecutionTime: Timestamp,
+      cutoff: Timestamp
+  ): Boolean =
+    !hasActiveExecution && lastExecutionTime.before(cutoff)
+
+  def terminateIdleKubernetesComputingUnits(): 
List[TerminatedComputingUnitInfo] =
+    runIdleKubernetesComputingUnitCleanup(
+      new IdleComputingUnitCleanupConfig(
+        KubernetesConfig.kubernetesComputingUnitEnabled,
+        KubernetesConfig.computingUnitIdleTimeoutMinutes
+      ),
+      () => new Timestamp(System.currentTimeMillis()),
+      DefaultKubernetesPodOperations
+    )
+
+  private[resource] def runIdleKubernetesComputingUnitCleanup(
+      cleanupConfig: IdleComputingUnitCleanupConfig,
+      currentTime: () => Timestamp,
+      podOperations: KubernetesPodOperations
+  ): List[TerminatedComputingUnitInfo] = {
+    if (!cleanupConfig.enabled || cleanupConfig.idleTimeoutMinutes <= 0) {
+      return List.empty
+    }
+
+    val now = currentTime()
+    val cutoff = new Timestamp(now.getTime - cleanupConfig.idleTimeoutMinutes 
* 60 * 1000)
+
+    idleKubernetesComputingUnitCandidates(cutoff).flatMap(candidate =>
+      terminateIdleKubernetesComputingUnitCandidate(candidate, now, 
podOperations)
+    )
+  }
+
+  private[resource] def idleKubernetesComputingUnitCandidates(
+      cutoff: Timestamp
+  ): List[IdleComputingUnitCandidate] = {
+    val activeStatuses = Seq(
+      WorkflowExecutionStatus.UninitializedOrReady,
+      WorkflowExecutionStatus.Running,
+      WorkflowExecutionStatus.Paused
+    ).map(WorkflowExecutionStatus.toDbStatus)
+
+    // All three questions asked per computing unit -- is any execution still 
active, when did an
+    // execution last report progress, when did one last start -- are 
aggregates over the same rows
+    // grouped by the same key, so one grouped query answers them for every 
unit at once. The left
+    // joins keep units that have no executions (both max() are NULL) and 
units whose owner row is
+    // gone (name is NULL), matching what a per-unit scan would produce.
+    val latestUpdateTime = max(WORKFLOW_EXECUTIONS.LAST_UPDATE_TIME)
+    val latestStartTime = max(WORKFLOW_EXECUTIONS.STARTING_TIME)
+    val hasActiveExecution = 
boolOr(WORKFLOW_EXECUTIONS.STATUS.in(activeStatuses: _*))

Review Comment:
   The common case — pod gone, evicted or deleted — is already handled by 
`reconcileVanishedKubernetesUnits`. What's left is only an in-place container 
restart where the row stays at `1`, and the user can still terminate that CU 
manually, so nothing is permanently stuck.
   
   I can't use `last_update_time` either: it's written on state changes, not as 
a heartbeat, so timing it out would kill CUs running long workflows. A correct 
fix means reading the container's `startedAt/restartCount` through a new 
`KubernetesClient` call, and the fixes for that seems to be too big. So my 
personal opintion is that, we can leave it for now. 



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

Reply via email to