You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by "nlippis (via GitHub)" <gi...@apache.org> on 2023/04/25 05:15:01 UTC

[GitHub] [druid] nlippis opened a new pull request, #14156: queue tasks if all slots in use

nlippis opened a new pull request, #14156:
URL: https://github.com/apache/druid/pull/14156

   <!-- Thanks for trying to help us make Apache Druid be the best it can be! Please fill out as much of the following information as is possible (where relevant, and remove it when irrelevant) to help make the intention and scope of this PR clear in order to ease review. -->
   
   <!-- Please read the doc for contribution (https://github.com/apache/druid/blob/master/CONTRIBUTING.md) before making this PR. Also, once you open a PR, please _avoid using force pushes and rebasing_ since these make it difficult for reviewers to see what you've changed in response to their reviews. See [the 'If your pull request shows conflicts with master' section](https://github.com/apache/druid/blob/master/CONTRIBUTING.md#if-your-pull-request-shows-conflicts-with-master) for more details. -->
   
   Fixes #XXXX.
   
   <!-- Replace XXXX with the id of the issue fixed in this PR. Remove this section if there is no corresponding issue. Don't reference the issue in the title of this pull-request. -->
   
   <!-- If you are a committer, follow the PR action item checklist for committers:
   https://github.com/apache/druid/blob/master/dev/committer-instructions.md#pr-and-issue-action-item-checklist-for-committers. -->
   
   ### Queue tasks for Kubernetes task runner if capacity is fully utilized
   
   <!-- Describe the goal of this PR, what problem are you fixing. If there is a corresponding issue (referenced above), it's not necessary to repeat the description here, however, you may choose to keep one summary sentence. -->
   
   <!-- Describe your patch: what did you change in code? How did you fix the problem? -->
   
   <!-- If there are several relatively logically separate changes in this PR, create a mini-section for each of them. For example: -->
   
   #### Fixed the bug ...
   #### Renamed the class ...
   #### Added a forbidden-apis entry ...
   
   <!--
   In each section, please describe design decisions made, including:
    - Choice of algorithms
    - Behavioral aspects. What configuration values are acceptable? How are corner cases and error conditions handled, such as when there are insufficient resources?
    - Class organization and design (how the logic is split between classes, inheritance, composition, design patterns)
    - Method organization and design (how the logic is split between methods, parameters and return types)
    - Naming (class, method, API, configuration, HTTP endpoint, names of emitted metrics)
   -->
   
   
   <!-- It's good to describe an alternative design (or mention an alternative name) for every design (or naming) decision point and compare the alternatives with the designs that you've implemented (or the names you've chosen) to highlight the advantages of the chosen designs and names. -->
   
   <!-- If there was a discussion of the design of the feature implemented in this PR elsewhere (e. g. a "Proposal" issue, any other issue, or a thread in the development mailing list), link to that discussion from this PR description and explain what have changed in your final design compared to your original proposal or the consensus version in the end of the discussion. If something hasn't changed since the original discussion, you can omit a detailed discussion of those aspects of the design here, perhaps apart from brief mentioning for the sake of readability of this PR description. -->
   
   <!-- Some of the aspects mentioned above may be omitted for simple and small changes. -->
   
   #### Release note
   <!-- Give your best effort to summarize your changes in a couple of sentences aimed toward Druid users. 
   
   If your change doesn't have end user impact, you can skip this section.
   
   For tips about how to write a good release note, see [Release notes](https://github.com/apache/druid/blob/master/CONTRIBUTING.md#release-notes).
   
   -->
   
   
   <hr>
   
   ##### Key changed/added classes in this PR
    * `MyFoo`
    * `OurBar`
    * `TheirBaz`
   
   <hr>
   
   <!-- Check the items by putting "x" in the brackets for the done things. Not all of these items apply to every PR. Remove the items which are not done or not relevant to the PR. None of the items from the checklist below are strictly necessary, but it would be very helpful if you at least self-review the PR. -->
   
   This PR has:
   
   - [ ] been self-reviewed.
      - [ ] using the [concurrency checklist](https://github.com/apache/druid/blob/master/dev/code-review/concurrency.md) (Remove this item if the PR doesn't have any relation to concurrency.)
   - [ ] added documentation for new or modified features or behaviors.
   - [ ] a release note entry in the PR description.
   - [ ] added Javadocs for most classes and all non-trivial methods. Linked related entities via Javadoc links.
   - [ ] added or updated version, license, or notice information in [licenses.yaml](https://github.com/apache/druid/blob/master/dev/license.md)
   - [ ] added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
   - [ ] added unit tests or modified existing tests to cover new code paths, ensuring the threshold for [code coverage](https://github.com/apache/druid/blob/master/dev/code-review/code-coverage.md) is met.
   - [ ] added integration tests.
   - [ ] been tested in a test Druid cluster.
   


-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] github-code-scanning[bot] commented on a diff in pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "github-code-scanning[bot] (via GitHub)" <gi...@apache.org>.
github-code-scanning[bot] commented on code in PR #14156:
URL: https://github.com/apache/druid/pull/14156#discussion_r1176032643


##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunnerFactory.java:
##########
@@ -126,15 +124,15 @@
         TYPE_NAME
     ));
 
-    if (adapter != null && !MultiContainerTaskAdapter.TYPE.equals(adapter) && kubernetesTaskRunnerConfig.sidecarSupport) {
+    if (adapter != null && !MultiContainerTaskAdapter.TYPE.equals(adapter) && kubernetesTaskRunnerConfig.isSidecarSupport()) {

Review Comment:
   ## Deprecated method or constructor invocation
   
   Invoking [KubernetesTaskRunnerConfig.isSidecarSupport](1) should be avoided because it has been deprecated.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/4887)



##########
extensions-contrib/kubernetes-overlord-extensions/src/test/java/org/apache/druid/k8s/overlord/KubernetesTaskRunnerConfigTest.java:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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.druid.k8s.overlord;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import org.joda.time.Period;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class KubernetesTaskRunnerConfigTest
+{
+  @Test
+  public void test_builder_preservesDefaults()
+  {
+    KubernetesTaskRunnerConfig config = KubernetesTaskRunnerConfig.builder()
+        .withNamespace("namespace")
+        .withDisableClientProxy(true)
+        .build();
+
+    Assert.assertEquals("namespace", config.getNamespace());
+    Assert.assertFalse(config.isDebugJobs());
+    Assert.assertFalse(config.isSidecarSupport());

Review Comment:
   ## Deprecated method or constructor invocation
   
   Invoking [KubernetesTaskRunnerConfig.isSidecarSupport](1) should be avoided because it has been deprecated.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/4889)



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunnerFactory.java:
##########
@@ -126,15 +124,15 @@
         TYPE_NAME
     ));
 
-    if (adapter != null && !MultiContainerTaskAdapter.TYPE.equals(adapter) && kubernetesTaskRunnerConfig.sidecarSupport) {
+    if (adapter != null && !MultiContainerTaskAdapter.TYPE.equals(adapter) && kubernetesTaskRunnerConfig.isSidecarSupport()) {
       throw new IAE(
           "Invalid pod adapter [%s], only pod adapter [%s] can be specified when sidecarSupport is enabled",
           adapter,
           MultiContainerTaskAdapter.TYPE
       );
     }
 
-    if (MultiContainerTaskAdapter.TYPE.equals(adapter) || kubernetesTaskRunnerConfig.sidecarSupport) {
+    if (MultiContainerTaskAdapter.TYPE.equals(adapter) || kubernetesTaskRunnerConfig.isSidecarSupport()) {

Review Comment:
   ## Deprecated method or constructor invocation
   
   Invoking [KubernetesTaskRunnerConfig.isSidecarSupport](1) should be avoided because it has been deprecated.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/4888)



##########
extensions-contrib/kubernetes-overlord-extensions/src/test/java/org/apache/druid/k8s/overlord/KubernetesTaskRunnerConfigTest.java:
##########
@@ -0,0 +1,95 @@
+/*
+ * 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.druid.k8s.overlord;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import org.joda.time.Period;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class KubernetesTaskRunnerConfigTest
+{
+  @Test
+  public void test_builder_preservesDefaults()
+  {
+    KubernetesTaskRunnerConfig config = KubernetesTaskRunnerConfig.builder()
+        .withNamespace("namespace")
+        .withDisableClientProxy(true)
+        .build();
+
+    Assert.assertEquals("namespace", config.getNamespace());
+    Assert.assertFalse(config.isDebugJobs());
+    Assert.assertFalse(config.isSidecarSupport());
+    Assert.assertNull(config.getPrimaryContainerName());
+    Assert.assertEquals("karlkfi/kubexit:v0.3.2", config.getKubexitImage());
+    Assert.assertNull(config.getGraceTerminationPeriodSeconds());
+    Assert.assertTrue(config.isDisableClientProxy());
+    Assert.assertEquals(new Period("PT4H"), config.getTaskTimeout());
+    Assert.assertEquals(new Period("P2D"), config.getTaskCleanupDelay());
+    Assert.assertEquals(new Period("PT10m"), config.getTaskCleanupInterval());
+    Assert.assertEquals(new Period("PT1H"), config.getTaskLaunchTimeout());
+    Assert.assertEquals(ImmutableList.of(), config.getPeonMonitors());
+    Assert.assertEquals(ImmutableList.of(), config.getJavaOptsArray());
+    Assert.assertEquals(ImmutableMap.of(), config.getLabels());
+    Assert.assertEquals(ImmutableMap.of(), config.getAnnotations());
+    Assert.assertEquals(Integer.valueOf(Integer.MAX_VALUE), config.getCapacity());
+  }
+
+  @Test
+  public void test_builder()
+  {
+    KubernetesTaskRunnerConfig config = KubernetesTaskRunnerConfig.builder()
+        .withNamespace("namespace")
+        .withDebugJob(true)
+        .withSidecarSupport(true)
+        .withPrimaryContainerName("primary")
+        .withKubexitImage("image")
+        .withGraceTerminationPeriodSeconds(0L)
+        .withDisableClientProxy(true)
+        .withTaskTimeout(new Period("PT2H"))
+        .withTaskCleanupDelay(new Period("P1D"))
+        .withTaskCleanupInterval(new Period("PT1H"))
+        .withK8sJobLaunchTimeout(new Period("PT1H"))
+        .withPeonMonitors(ImmutableList.of("monitor"))
+        .withJavaOptsArray(ImmutableList.of("option"))
+        .withLabels(ImmutableMap.of("key", "value"))
+        .withAnnotations(ImmutableMap.of("key", "value"))
+        .withCapacity(1)
+        .build();
+
+    Assert.assertEquals("namespace", config.getNamespace());
+    Assert.assertTrue(config.isDebugJobs());
+    Assert.assertTrue(config.isSidecarSupport());

Review Comment:
   ## Deprecated method or constructor invocation
   
   Invoking [KubernetesTaskRunnerConfig.isSidecarSupport](1) should be avoided because it has been deprecated.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/4890)



-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] nlippis commented on a diff in pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "nlippis (via GitHub)" <gi...@apache.org>.
nlippis commented on code in PR #14156:
URL: https://github.com/apache/druid/pull/14156#discussion_r1178162786


##########
extensions-contrib/kubernetes-overlord-extensions/pom.xml:
##########
@@ -157,6 +157,18 @@
       <version>5.8.2</version>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.hamcrest</groupId>
+      <artifactId>hamcrest-core</artifactId>

Review Comment:
   The dependency checker complained that this was an undeclared dependency so I added it.



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/common/KubernetesPeonClient.java:
##########
@@ -19,37 +19,244 @@
 
 package org.apache.druid.k8s.overlord.common;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Optional;
 import io.fabric8.kubernetes.api.model.Pod;
 import io.fabric8.kubernetes.api.model.batch.v1.Job;
+import io.fabric8.kubernetes.client.KubernetesClient;
+import io.fabric8.kubernetes.client.dsl.LogWatch;
+import org.apache.druid.java.util.common.RetryUtils;
+import org.apache.druid.java.util.emitter.EmittingLogger;
 
 import java.io.InputStream;
+import java.sql.Timestamp;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
 
-/**
- * A Kubernetes client wrapper to assist with peon task managment.
- * It provides a high level api to retreive jobs, launch jobs, delete jobs and various other
- * tasks like getting task logs, listing all active tasks.
- */
-public interface KubernetesPeonClient
+public class KubernetesPeonClient
 {
+  private static final EmittingLogger log = new EmittingLogger(KubernetesPeonClient.class);
+
+  private final KubernetesClientApi clientApi;
+  private final String namespace;
+  private final boolean debugJobs;
+
+  public KubernetesPeonClient(KubernetesClientApi clientApi, String namespace, boolean debugJobs)
+  {
+    this.clientApi = clientApi;
+    this.namespace = namespace;
+    this.debugJobs = debugJobs;
+  }
+
+  public Optional<Job> getPeonJob(K8sTaskId taskId)
+  {
+    return clientApi.executeRequest(
+        client -> {
+          return Optional.fromNullable(
+              client.batch()
+                    .v1()
+                    .jobs()
+                    .inNamespace(namespace)
+                    .withName(taskId.getK8sTaskId())
+                    .get());
+        }
+    );
+  }
+
+  public Pod launchPeonJobAndWaitForStart(Job job, long howLong, TimeUnit timeUnit)
+  {
+    long start = System.currentTimeMillis();
+    // launch job
+    return clientApi.executeRequest(client -> {
+      client.batch().v1().jobs().inNamespace(namespace).resource(job).create();
+      K8sTaskId taskId = new K8sTaskId(job.getMetadata().getName());
+      log.info("Successfully submitted job: %s ... waiting for job to launch", taskId);
+      // wait until the pod is running or complete or failed, any of those is fine
+      // TODO: I believe we can do the following instead and remove getPeonPodWithRetries
+      // Pod result = client.pods()
+      //     .inNamespace(namespace)
+      //     .withLabel("job-name", job.getMetadata().getName())
+      //     .waitUntilCondition(pod -> {
+      //       if (pod == null || pod.getStatus() == null) {
+      //         return false;
+      //       }
+      //       return pod.getStatus().getPodIP() != null;
+      //     }, howLong, timeUnit);
+      Pod mainPod = getPeonPodWithRetries(taskId);
+      Pod result = client.pods().inNamespace(namespace).withName(mainPod.getMetadata().getName())

Review Comment:
   Is this the case you are thinking of?
   
   Thread 1: client.launchPeonJobAndWaitForStart(...)
   Thread 1: client.launchPeonJobAndWaitForStart::getPeonPodWithRetries(...) -> Pod
   Thread 2: client.deletePeonJob(...) -> true
   Thread 1: client.launchPeonJobAndWaitForStart::waitUntilCondition -> false
   
   



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/PeonLifecycleFactory.java:
##########
@@ -0,0 +1,27 @@
+/*
+ * 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.druid.k8s.overlord;
+
+import org.apache.druid.indexing.common.task.Task;
+
+public interface PeonLifecycleFactory
+{
+  KubernetesPeonLifecycle build(Task task);

Review Comment:
   We are using it for testing, otherwise there is no way to mock/stub behavior for the PeonLifecycle in the unit tests.  Having to set up mocks for the classes/methods that the KubernetesPeonLifecycle object uses would tightly couple the KubernetesTaskRunner unit tests to the implementation of KubernetesPeonLifecycle.



-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] georgew5656 commented on a diff in pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "georgew5656 (via GitHub)" <gi...@apache.org>.
georgew5656 commented on code in PR #14156:
URL: https://github.com/apache/druid/pull/14156#discussion_r1177969905


##########
extensions-contrib/kubernetes-overlord-extensions/pom.xml:
##########
@@ -157,6 +157,18 @@
       <version>5.8.2</version>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.hamcrest</groupId>
+      <artifactId>hamcrest-core</artifactId>

Review Comment:
   is this actually needed? it looks like its deprecated and I don't see it used



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunner.java:
##########
@@ -89,174 +69,128 @@
 
 /**
  * Runs tasks as k8s jobs using the "internal peon" verb.
- * One additional feature of this class is that kubernetes is the source of truth, so if you launch a task
- * shutdown druid, bring up druid, the task will keep running and the state will be updated when the cluster
- * comes back.  Thus while no tasks are technically restorable, all tasks once launched will run in isolation to the
- * extent possible without requiring the overlord consistently up during their lifetime.
  */
-
 public class KubernetesTaskRunner implements TaskLogStreamer, TaskRunner
 {
-
   private static final EmittingLogger log = new EmittingLogger(KubernetesTaskRunner.class);
   private final CopyOnWriteArrayList<Pair<TaskRunnerListener, Executor>> listeners = new CopyOnWriteArrayList<>();
 
   // to cleanup old jobs that might not have been deleted.
   private final ScheduledExecutorService cleanupExecutor;
 
-  protected final ConcurrentHashMap<String, K8sWorkItem> tasks = new ConcurrentHashMap<>();
+  protected final ConcurrentHashMap<String, KubernetesWorkItem> tasks = new ConcurrentHashMap<>();
   protected final TaskAdapter adapter;
-  protected final KubernetesPeonClient client;
 
-  private final ObjectMapper mapper;
-  private final KubernetesTaskRunnerConfig k8sConfig;
-  private final TaskQueueConfig taskQueueConfig;
-  private final TaskLogs taskLogs;
+  private final KubernetesPeonClient client;
+  private final KubernetesTaskRunnerConfig config;
   private final ListeningExecutorService exec;
   private final HttpClient httpClient;
+  private final PeonLifecycleFactory peonLifecycleFactory;
 
 
   public KubernetesTaskRunner(
-      ObjectMapper mapper,
       TaskAdapter adapter,
-      KubernetesTaskRunnerConfig k8sConfig,
-      TaskQueueConfig taskQueueConfig,
-      TaskLogs taskLogs,
+      KubernetesTaskRunnerConfig config,
       KubernetesPeonClient client,
-      HttpClient httpClient
+      HttpClient httpClient,
+      PeonLifecycleFactory peonLifecycleFactory
   )
   {
-    this.mapper = mapper;
     this.adapter = adapter;
-    this.k8sConfig = k8sConfig;
-    this.taskQueueConfig = taskQueueConfig;
-    this.taskLogs = taskLogs;
+    this.config = config;
     this.client = client;
     this.httpClient = httpClient;
+    this.peonLifecycleFactory = peonLifecycleFactory;
     this.cleanupExecutor = Executors.newScheduledThreadPool(1);
     this.exec = MoreExecutors.listeningDecorator(
-        Execs.multiThreaded(taskQueueConfig.getMaxSize(), "k8s-task-runner-%d")
-    );
-    Preconditions.checkArgument(

Review Comment:
   we probably still want to check that capacity is less than the max queue size



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunner.java:
##########
@@ -89,174 +69,128 @@
 
 /**
  * Runs tasks as k8s jobs using the "internal peon" verb.
- * One additional feature of this class is that kubernetes is the source of truth, so if you launch a task

Review Comment:
   it seems to me this comment still applies, since the running k8s jobs will still be rehydrated into the KubernetesTaskRunner by the restore() call



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/common/KubernetesPeonClient.java:
##########
@@ -19,37 +19,244 @@
 
 package org.apache.druid.k8s.overlord.common;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Optional;
 import io.fabric8.kubernetes.api.model.Pod;
 import io.fabric8.kubernetes.api.model.batch.v1.Job;
+import io.fabric8.kubernetes.client.KubernetesClient;
+import io.fabric8.kubernetes.client.dsl.LogWatch;
+import org.apache.druid.java.util.common.RetryUtils;
+import org.apache.druid.java.util.emitter.EmittingLogger;
 
 import java.io.InputStream;
+import java.sql.Timestamp;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
 
-/**
- * A Kubernetes client wrapper to assist with peon task managment.
- * It provides a high level api to retreive jobs, launch jobs, delete jobs and various other
- * tasks like getting task logs, listing all active tasks.
- */
-public interface KubernetesPeonClient
+public class KubernetesPeonClient
 {
+  private static final EmittingLogger log = new EmittingLogger(KubernetesPeonClient.class);
+
+  private final KubernetesClientApi clientApi;
+  private final String namespace;
+  private final boolean debugJobs;
+
+  public KubernetesPeonClient(KubernetesClientApi clientApi, String namespace, boolean debugJobs)
+  {
+    this.clientApi = clientApi;
+    this.namespace = namespace;
+    this.debugJobs = debugJobs;
+  }
+
+  public Optional<Job> getPeonJob(K8sTaskId taskId)
+  {
+    return clientApi.executeRequest(
+        client -> {
+          return Optional.fromNullable(
+              client.batch()
+                    .v1()
+                    .jobs()
+                    .inNamespace(namespace)
+                    .withName(taskId.getK8sTaskId())
+                    .get());
+        }
+    );
+  }
+
+  public Pod launchPeonJobAndWaitForStart(Job job, long howLong, TimeUnit timeUnit)
+  {
+    long start = System.currentTimeMillis();
+    // launch job
+    return clientApi.executeRequest(client -> {
+      client.batch().v1().jobs().inNamespace(namespace).resource(job).create();
+      K8sTaskId taskId = new K8sTaskId(job.getMetadata().getName());
+      log.info("Successfully submitted job: %s ... waiting for job to launch", taskId);
+      // wait until the pod is running or complete or failed, any of those is fine
+      // TODO: I believe we can do the following instead and remove getPeonPodWithRetries
+      // Pod result = client.pods()
+      //     .inNamespace(namespace)
+      //     .withLabel("job-name", job.getMetadata().getName())
+      //     .waitUntilCondition(pod -> {
+      //       if (pod == null || pod.getStatus() == null) {
+      //         return false;
+      //       }
+      //       return pod.getStatus().getPodIP() != null;
+      //     }, howLong, timeUnit);
+      Pod mainPod = getPeonPodWithRetries(taskId);
+      Pod result = client.pods().inNamespace(namespace).withName(mainPod.getMetadata().getName())

Review Comment:
   this is unrelated but i think there might be a race condition here still (i've never encountered it) where a task is shutdown during this logic and it gets stuck, but I don't think we should worry about it until it happens



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/PeonLifecycleFactory.java:
##########
@@ -0,0 +1,27 @@
+/*
+ * 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.druid.k8s.overlord;
+
+import org.apache.druid.indexing.common.task.Task;
+
+public interface PeonLifecycleFactory
+{
+  KubernetesPeonLifecycle build(Task task);

Review Comment:
   is there a reason we need this interface right now considering its in the k8s overlord extensions directory? feels pretty similar to the KubernetesPeonClient interface that was removed in this PR



-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] abhishekagarwal87 commented on a diff in pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "abhishekagarwal87 (via GitHub)" <gi...@apache.org>.
abhishekagarwal87 commented on code in PR #14156:
URL: https://github.com/apache/druid/pull/14156#discussion_r1192020779


##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunner.java:
##########
@@ -89,174 +69,142 @@
 
 /**
  * Runs tasks as k8s jobs using the "internal peon" verb.
- * One additional feature of this class is that kubernetes is the source of truth, so if you launch a task
- * shutdown druid, bring up druid, the task will keep running and the state will be updated when the cluster
- * comes back.  Thus while no tasks are technically restorable, all tasks once launched will run in isolation to the
- * extent possible without requiring the overlord consistently up during their lifetime.
+ * The KubernetesTaskRunner runs tasks by transforming the task spec into a K8s Job spec based
+ * on the TaskAdapter it is configured with. The KubernetesTaskRunner has a pool of threads
+ * (configurable with the capacity configuration) to track the jobs (1 thread tracks 1 job).
+ *
+ * Each thread calls down to the KubernetesPeonLifecycle class to submit the Job to K8s and then
+ * waits for the lifecycle class to report back with the Job's status (success/failure).
+ *
+ * If there are not enough threads in the thread pool to execute and wait for a job, then the
+ * task is put in a queue and left in WAITING state until another task completes.
+ *
+ * When the KubernetesTaskRunner comes up it attempts to restore its internal mapping of tasks
+ * from Kubernetes by listing running jobs and calling join on each job, which spawns a thread to
+ * wait for the fabric8 client library to report back, similar to what happens when a new
+ * job is run.

Review Comment:
   Nice. 



-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] github-code-scanning[bot] commented on a diff in pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "github-code-scanning[bot] (via GitHub)" <gi...@apache.org>.
github-code-scanning[bot] commented on code in PR #14156:
URL: https://github.com/apache/druid/pull/14156#discussion_r1177329416


##########
extensions-contrib/kubernetes-overlord-extensions/src/test/java/org/apache/druid/k8s/overlord/KubernetesTaskRunnerConfigTest.java:
##########
@@ -0,0 +1,126 @@
+/*
+ * 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.druid.k8s.overlord;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import org.apache.druid.jackson.DefaultObjectMapper;
+import org.joda.time.Period;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.io.IOException;
+
+public class KubernetesTaskRunnerConfigTest
+{
+  @Test
+  public void test_deserializable() throws IOException
+  {
+    ObjectMapper mapper = new DefaultObjectMapper();
+    KubernetesTaskRunnerConfig config = mapper.readValue(
+        this.getClass().getClassLoader().getResource("kubernetesTaskRunnerConfig.json"),
+        KubernetesTaskRunnerConfig.class
+    );
+
+    Assert.assertEquals("namespace", config.getNamespace());
+    Assert.assertFalse(config.isDebugJobs());
+    Assert.assertFalse(config.isSidecarSupport());

Review Comment:
   ## Deprecated method or constructor invocation
   
   Invoking [KubernetesTaskRunnerConfig.isSidecarSupport](1) should be avoided because it has been deprecated.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/4896)



-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] georgew5656 commented on a diff in pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "georgew5656 (via GitHub)" <gi...@apache.org>.
georgew5656 commented on code in PR #14156:
URL: https://github.com/apache/druid/pull/14156#discussion_r1186294614


##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunner.java:
##########
@@ -89,174 +69,128 @@
 
 /**
  * Runs tasks as k8s jobs using the "internal peon" verb.
- * One additional feature of this class is that kubernetes is the source of truth, so if you launch a task
- * shutdown druid, bring up druid, the task will keep running and the state will be updated when the cluster
- * comes back.  Thus while no tasks are technically restorable, all tasks once launched will run in isolation to the
- * extent possible without requiring the overlord consistently up during their lifetime.
  */
-
 public class KubernetesTaskRunner implements TaskLogStreamer, TaskRunner
 {
-
   private static final EmittingLogger log = new EmittingLogger(KubernetesTaskRunner.class);
   private final CopyOnWriteArrayList<Pair<TaskRunnerListener, Executor>> listeners = new CopyOnWriteArrayList<>();
 
   // to cleanup old jobs that might not have been deleted.
   private final ScheduledExecutorService cleanupExecutor;
 
-  protected final ConcurrentHashMap<String, K8sWorkItem> tasks = new ConcurrentHashMap<>();
+  protected final ConcurrentHashMap<String, KubernetesWorkItem> tasks = new ConcurrentHashMap<>();
   protected final TaskAdapter adapter;
-  protected final KubernetesPeonClient client;
 
-  private final ObjectMapper mapper;
-  private final KubernetesTaskRunnerConfig k8sConfig;
-  private final TaskQueueConfig taskQueueConfig;
-  private final TaskLogs taskLogs;
+  private final KubernetesPeonClient client;
+  private final KubernetesTaskRunnerConfig config;
   private final ListeningExecutorService exec;
   private final HttpClient httpClient;
+  private final PeonLifecycleFactory peonLifecycleFactory;
 
 
   public KubernetesTaskRunner(
-      ObjectMapper mapper,
       TaskAdapter adapter,
-      KubernetesTaskRunnerConfig k8sConfig,
-      TaskQueueConfig taskQueueConfig,
-      TaskLogs taskLogs,
+      KubernetesTaskRunnerConfig config,
       KubernetesPeonClient client,
-      HttpClient httpClient
+      HttpClient httpClient,
+      PeonLifecycleFactory peonLifecycleFactory
   )
   {
-    this.mapper = mapper;
     this.adapter = adapter;
-    this.k8sConfig = k8sConfig;
-    this.taskQueueConfig = taskQueueConfig;
-    this.taskLogs = taskLogs;
+    this.config = config;
     this.client = client;
     this.httpClient = httpClient;
+    this.peonLifecycleFactory = peonLifecycleFactory;
     this.cleanupExecutor = Executors.newScheduledThreadPool(1);
     this.exec = MoreExecutors.listeningDecorator(
-        Execs.multiThreaded(taskQueueConfig.getMaxSize(), "k8s-task-runner-%d")
-    );
-    Preconditions.checkArgument(
-        taskQueueConfig.getMaxSize() < Integer.MAX_VALUE,
-        "The task queue bounds how many concurrent k8s tasks you can have"
+        Execs.multiThreaded(config.getCapacity(), "k8s-task-runner-%d")
     );
   }
 
-
   @Override
   public Optional<InputStream> streamTaskLog(String taskid, long offset)
   {
-    return client.getPeonLogs(new K8sTaskId(taskid));
+    KubernetesWorkItem workItem = tasks.get(taskid);
+    if (workItem == null) {
+      return Optional.absent();
+    }
+    return workItem.streamTaskLogs();
   }
 
   @Override
   public ListenableFuture<TaskStatus> run(Task task)
   {
     synchronized (tasks) {
-      tasks.computeIfAbsent(
-          task.getId(), k -> new K8sWorkItem(
-              client,
-              task,
-              exec.submit(() -> {
-                K8sTaskId k8sTaskId = new K8sTaskId(task);
-                try {
-                  JobResponse completedPhase;
-                  Optional<Job> existingJob = client.jobExists(k8sTaskId);
-                  if (!existingJob.isPresent()) {
-                    Job job = adapter.fromTask(task);
-                    log.info("Job created %s and ready to launch", k8sTaskId);
-                    Pod peonPod = client.launchJobAndWaitForStart(
-                        job,
-                        KubernetesTaskRunnerConfig.toMilliseconds(k8sConfig.k8sjobLaunchTimeout),
-                        TimeUnit.MILLISECONDS
-                    );
-                    log.info("Job %s launched in k8s", k8sTaskId);
-                    completedPhase = monitorJob(peonPod, k8sTaskId);
-                  } else {
-                    Job job = existingJob.get();
-                    if (job.getStatus().getActive() == null) {
-                      if (job.getStatus().getSucceeded() != null) {
-                        completedPhase = new JobResponse(job, PeonPhase.SUCCEEDED);
-                      } else {
-                        completedPhase = new JobResponse(job, PeonPhase.FAILED);
-                      }
-                    } else {
-                      // the job is active lets monitor it
-                      completedPhase = monitorJob(k8sTaskId);
-                    }
-                  }
-                  TaskStatus status = getTaskStatus(k8sTaskId, completedPhase);
-                  if (completedPhase.getJobDuration().isPresent()) {
-                    status = status.withDuration(completedPhase.getJobDuration().get());
-                  }
-                  updateStatus(task, status);
-                  return status;
-                }
-                catch (Exception e) {
-                  log.error(e, "Error with task: %s", k8sTaskId);
-                  throw e;
-                }
-                finally {
-                  // publish task logs
-                  Path log = Files.createTempFile(task.getId(), "log");
-                  try {
-                    Optional<InputStream> logStream = client.getPeonLogs(new K8sTaskId(task.getId()));
-                    if (logStream.isPresent()) {
-                      FileUtils.copyInputStreamToFile(logStream.get(), log.toFile());
-                    }
-                    taskLogs.pushTaskLog(task.getId(), log.toFile());
-                  }
-                  finally {
-                    Files.deleteIfExists(log);
-                  }
-                  client.cleanUpJob(new K8sTaskId(task.getId()));
-                  synchronized (tasks) {
-                    tasks.remove(task.getId());
-                  }
-                }
-              })
-          ));
+      tasks.computeIfAbsent(task.getId(), k -> new KubernetesWorkItem(task, exec.submit(() -> runTask(task))));
+      return tasks.get(task.getId()).getResult();
+    }
+  }
+
+  protected ListenableFuture<TaskStatus> join(Task task)
+  {
+    synchronized (tasks) {
+      tasks.computeIfAbsent(task.getId(), k -> new KubernetesWorkItem(task, exec.submit(() -> joinTask(task))));
       return tasks.get(task.getId()).getResult();
     }
   }
 
-  JobResponse monitorJob(K8sTaskId k8sTaskId)
+  private TaskStatus runTask(Task task)
   {
-    return monitorJob(client.getMainJobPod(k8sTaskId), k8sTaskId);
+    return doTask(task, true);
   }
 
-  JobResponse monitorJob(Pod peonPod, K8sTaskId k8sTaskId)
+  private TaskStatus joinTask(Task task)
   {
-    if (peonPod == null) {
-      throw new ISE("Error in k8s launching peon pod for task %s", k8sTaskId);
-    }
-    return client.waitForJobCompletion(
-        k8sTaskId,
-        KubernetesTaskRunnerConfig.toMilliseconds(k8sConfig.maxTaskDuration),
-        TimeUnit.MILLISECONDS
-    );
+    return doTask(task, false);
   }
 
-  private TaskStatus getTaskStatus(K8sTaskId task, JobResponse jobResponse) throws IOException
+  @VisibleForTesting
+  protected TaskStatus doTask(Task task, boolean run)
   {
-    Optional<InputStream> maybeTaskStatusStream = taskLogs.streamTaskStatus(task.getOriginalTaskId());
-    if (maybeTaskStatusStream.isPresent()) {
-      String taskStatus = IOUtils.toString(maybeTaskStatusStream.get(), StandardCharsets.UTF_8);
-      return mapper.readValue(taskStatus, TaskStatus.class);
-    } else if (PeonPhase.SUCCEEDED.equals(jobResponse.getPhase())) {
-      // fallback to behavior before the introduction of task status streaming for backwards compatibility
-      return TaskStatus.success(task.getOriginalTaskId());
-    } else if (Objects.isNull(jobResponse.getJob())) {
-      return TaskStatus.failure(
-          task.getOriginalTaskId(),
-          StringUtils.format("Task [%s] failed kubernetes job disappeared before completion", task.getOriginalTaskId())
-      );
-    } else {
-      return TaskStatus.failure(
-          task.getOriginalTaskId(),
-          StringUtils.format("Task [%s] failed", task.getOriginalTaskId())
-      );
+    KubernetesPeonLifecycle peonLifecycle = peonLifecycleFactory.build(task);
+
+    synchronized (tasks) {
+      KubernetesWorkItem workItem = tasks.get(task.getId());
+
+      if (workItem == null) {
+        throw new ISE("Task [%s] disappeared", task.getId());
+      }
+
+      if (workItem.isShutdownRequested()) {
+        throw new ISE("Task [%s] has been shut down", task.getId());
+      }
+
+      workItem.setKubernetesPeonLifecycle(peonLifecycle);
+    }
+
+    try {
+      TaskStatus taskStatus;
+      if (run) {
+        taskStatus = peonLifecycle.run(
+            adapter.fromTask(task),
+            config.getTaskLaunchTimeout().toStandardDuration().getMillis(),
+            config.getTaskTimeout().toStandardDuration().getMillis()
+        );
+      } else {
+        taskStatus = peonLifecycle.join(
+            config.getTaskTimeout().toStandardDuration().getMillis()
+        );
+      }
+
+      updateStatus(task, taskStatus);
+
+      return taskStatus;
+    }
+
+    catch (Exception e) {
+      log.error(e, "Task [%s] execution caught an exception", task.getId());

Review Comment:
   In the join method of the KubernetesPeonLifecycle class, there's a finally block that cleans up the K8s Job. this will get run even if the main try logic throws an error.
   
   
   if there's some problem with this logic in the lifecycle class (like k8s being offline or something), there is a cleanup executor that delete jobs that have been around for a while
   
   
   
   



-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] nlippis commented on a diff in pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "nlippis (via GitHub)" <gi...@apache.org>.
nlippis commented on code in PR #14156:
URL: https://github.com/apache/druid/pull/14156#discussion_r1178292269


##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunner.java:
##########
@@ -89,174 +69,128 @@
 
 /**
  * Runs tasks as k8s jobs using the "internal peon" verb.
- * One additional feature of this class is that kubernetes is the source of truth, so if you launch a task

Review Comment:
   I wanted to rewrite this comment so that it accurately describes how tasks are handled in the new system.  I can put together a follow up PR with the description. 



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunner.java:
##########
@@ -89,174 +69,128 @@
 
 /**
  * Runs tasks as k8s jobs using the "internal peon" verb.
- * One additional feature of this class is that kubernetes is the source of truth, so if you launch a task
- * shutdown druid, bring up druid, the task will keep running and the state will be updated when the cluster
- * comes back.  Thus while no tasks are technically restorable, all tasks once launched will run in isolation to the
- * extent possible without requiring the overlord consistently up during their lifetime.
  */
-
 public class KubernetesTaskRunner implements TaskLogStreamer, TaskRunner
 {
-
   private static final EmittingLogger log = new EmittingLogger(KubernetesTaskRunner.class);
   private final CopyOnWriteArrayList<Pair<TaskRunnerListener, Executor>> listeners = new CopyOnWriteArrayList<>();
 
   // to cleanup old jobs that might not have been deleted.
   private final ScheduledExecutorService cleanupExecutor;
 
-  protected final ConcurrentHashMap<String, K8sWorkItem> tasks = new ConcurrentHashMap<>();
+  protected final ConcurrentHashMap<String, KubernetesWorkItem> tasks = new ConcurrentHashMap<>();
   protected final TaskAdapter adapter;
-  protected final KubernetesPeonClient client;
 
-  private final ObjectMapper mapper;
-  private final KubernetesTaskRunnerConfig k8sConfig;
-  private final TaskQueueConfig taskQueueConfig;
-  private final TaskLogs taskLogs;
+  private final KubernetesPeonClient client;
+  private final KubernetesTaskRunnerConfig config;
   private final ListeningExecutorService exec;
   private final HttpClient httpClient;
+  private final PeonLifecycleFactory peonLifecycleFactory;
 
 
   public KubernetesTaskRunner(
-      ObjectMapper mapper,
       TaskAdapter adapter,
-      KubernetesTaskRunnerConfig k8sConfig,
-      TaskQueueConfig taskQueueConfig,
-      TaskLogs taskLogs,
+      KubernetesTaskRunnerConfig config,
       KubernetesPeonClient client,
-      HttpClient httpClient
+      HttpClient httpClient,
+      PeonLifecycleFactory peonLifecycleFactory
   )
   {
-    this.mapper = mapper;
     this.adapter = adapter;
-    this.k8sConfig = k8sConfig;
-    this.taskQueueConfig = taskQueueConfig;
-    this.taskLogs = taskLogs;
+    this.config = config;
     this.client = client;
     this.httpClient = httpClient;
+    this.peonLifecycleFactory = peonLifecycleFactory;
     this.cleanupExecutor = Executors.newScheduledThreadPool(1);
     this.exec = MoreExecutors.listeningDecorator(
-        Execs.multiThreaded(taskQueueConfig.getMaxSize(), "k8s-task-runner-%d")
-    );
-    Preconditions.checkArgument(

Review Comment:
   I don't really see the value in doing that.  If k8s task runner capacity > max queue size then only max queue size tasks will be running.  This is the behavior the user would expect, and since capacity is virtual (we don't spin any long lived resources based on the value of capacity) there aren't any performance/cost drawbacks.



-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] dclim merged pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "dclim (via GitHub)" <gi...@apache.org>.
dclim merged PR #14156:
URL: https://github.com/apache/druid/pull/14156


-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] nlippis commented on pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "nlippis (via GitHub)" <gi...@apache.org>.
nlippis commented on PR #14156:
URL: https://github.com/apache/druid/pull/14156#issuecomment-1546144197

   🏎️ 


-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] nlippis commented on pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "nlippis (via GitHub)" <gi...@apache.org>.
nlippis commented on PR #14156:
URL: https://github.com/apache/druid/pull/14156#issuecomment-1523900915

   > this is mostly for my own understanding, but as I understand there is a alternative solution where you could still have getKnownTasks directly query k8s to get the list of peon jobs and then join each of them to be more in line with the original "use k8s for everything" idea?
   > 
   > I think I like this current system better since it still gets info from k8s but doesn't have to do so many call each time tasks are listed, but just wanted to confirm this was a conscious choice
   
   Reading from state local to the `KubernetesTaskRunner` (in this case the `tasks` hashmap) instead of directly calling K8S was required.  When the tasks are queued in the thread queue (not running) there won't be any corresponding K8S job so making a direct call in `getKnownTasks()` won't return all tasks that the task runner knows about.  While there is a solution that calls both K8S and checks state local to the task runner it is complicated to get that code right and in the end is unnecessary.
   
   Another unstated goal of this approach is to improve performance when the task runner is managing hundreds of tasks.  Reading from local state improves performance of in many ways.


-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] georgew5656 commented on a diff in pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "georgew5656 (via GitHub)" <gi...@apache.org>.
georgew5656 commented on code in PR #14156:
URL: https://github.com/apache/druid/pull/14156#discussion_r1179265880


##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/common/KubernetesPeonClient.java:
##########
@@ -19,37 +19,244 @@
 
 package org.apache.druid.k8s.overlord.common;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Optional;
 import io.fabric8.kubernetes.api.model.Pod;
 import io.fabric8.kubernetes.api.model.batch.v1.Job;
+import io.fabric8.kubernetes.client.KubernetesClient;
+import io.fabric8.kubernetes.client.dsl.LogWatch;
+import org.apache.druid.java.util.common.RetryUtils;
+import org.apache.druid.java.util.emitter.EmittingLogger;
 
 import java.io.InputStream;
+import java.sql.Timestamp;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
 
-/**
- * A Kubernetes client wrapper to assist with peon task managment.
- * It provides a high level api to retreive jobs, launch jobs, delete jobs and various other
- * tasks like getting task logs, listing all active tasks.
- */
-public interface KubernetesPeonClient
+public class KubernetesPeonClient
 {
+  private static final EmittingLogger log = new EmittingLogger(KubernetesPeonClient.class);
+
+  private final KubernetesClientApi clientApi;
+  private final String namespace;
+  private final boolean debugJobs;
+
+  public KubernetesPeonClient(KubernetesClientApi clientApi, String namespace, boolean debugJobs)
+  {
+    this.clientApi = clientApi;
+    this.namespace = namespace;
+    this.debugJobs = debugJobs;
+  }
+
+  public Optional<Job> getPeonJob(K8sTaskId taskId)
+  {
+    return clientApi.executeRequest(
+        client -> {
+          return Optional.fromNullable(
+              client.batch()
+                    .v1()
+                    .jobs()
+                    .inNamespace(namespace)
+                    .withName(taskId.getK8sTaskId())
+                    .get());
+        }
+    );
+  }
+
+  public Pod launchPeonJobAndWaitForStart(Job job, long howLong, TimeUnit timeUnit)
+  {
+    long start = System.currentTimeMillis();
+    // launch job
+    return clientApi.executeRequest(client -> {
+      client.batch().v1().jobs().inNamespace(namespace).resource(job).create();
+      K8sTaskId taskId = new K8sTaskId(job.getMetadata().getName());
+      log.info("Successfully submitted job: %s ... waiting for job to launch", taskId);
+      // wait until the pod is running or complete or failed, any of those is fine
+      // TODO: I believe we can do the following instead and remove getPeonPodWithRetries
+      // Pod result = client.pods()
+      //     .inNamespace(namespace)
+      //     .withLabel("job-name", job.getMetadata().getName())
+      //     .waitUntilCondition(pod -> {
+      //       if (pod == null || pod.getStatus() == null) {
+      //         return false;
+      //       }
+      //       return pod.getStatus().getPodIP() != null;
+      //     }, howLong, timeUnit);
+      Pod mainPod = getPeonPodWithRetries(taskId);
+      Pod result = client.pods().inNamespace(namespace).withName(mainPod.getMetadata().getName())

Review Comment:
   yeah, it seems pretty unlikely but is technically possible



-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


[GitHub] [druid] abhishekagarwal87 commented on a diff in pull request #14156: queue tasks in kubernetes task runner if capacity is fully utilized

Posted by "abhishekagarwal87 (via GitHub)" <gi...@apache.org>.
abhishekagarwal87 commented on code in PR #14156:
URL: https://github.com/apache/druid/pull/14156#discussion_r1182425149


##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesPeonLifecycle.java:
##########
@@ -0,0 +1,279 @@
+/*
+ * 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.druid.k8s.overlord;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import io.fabric8.kubernetes.api.model.Pod;
+import io.fabric8.kubernetes.api.model.PodStatus;
+import io.fabric8.kubernetes.api.model.batch.v1.Job;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.druid.indexer.TaskLocation;
+import org.apache.druid.indexer.TaskStatus;
+import org.apache.druid.indexing.common.task.Task;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.emitter.EmittingLogger;
+import org.apache.druid.k8s.overlord.common.DruidK8sConstants;
+import org.apache.druid.k8s.overlord.common.JobResponse;
+import org.apache.druid.k8s.overlord.common.K8sTaskId;
+import org.apache.druid.k8s.overlord.common.KubernetesPeonClient;
+import org.apache.druid.tasklogs.TaskLogs;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+public class KubernetesPeonLifecycle
+{
+  private static final EmittingLogger log = new EmittingLogger(KubernetesPeonLifecycle.class);
+
+  protected enum State
+  {
+    /** Lifecycle's state before {@link #run(Job, long, long)} or {@link #join(long)} is called. */
+    NOT_STARTED,
+    /** Lifecycle's state since {@link #run(Job, long, long)} is called. */
+    PENDING,
+    /** Lifecycle's state since {@link #join(long)} is called. */
+    RUNNING,
+    /** Lifecycle's state since the task has completed. */
+    STOPPED
+  }
+
+  private final AtomicReference<State> state = new AtomicReference<>(State.NOT_STARTED);
+  private final K8sTaskId taskId;
+  private final TaskLogs taskLogs;
+  private final KubernetesPeonClient kubernetesClient;
+  private final ObjectMapper mapper;
+
+  protected KubernetesPeonLifecycle(
+      Task task,
+      KubernetesPeonClient kubernetesClient,
+      TaskLogs taskLogs,
+      ObjectMapper mapper
+  )
+  {
+    this.taskId = new K8sTaskId(task);
+    this.kubernetesClient = kubernetesClient;
+    this.taskLogs = taskLogs;
+    this.mapper = mapper;
+  }
+
+  /**
+   * Run a Kubernetes Job
+   *
+   * @param job
+   * @param launchTimeout
+   * @param timeout
+   * @return
+   * @throws IllegalStateException
+   */
+  protected synchronized TaskStatus run(Job job, long launchTimeout, long timeout) throws IllegalStateException
+  {
+    try {
+      Preconditions.checkState(
+          state.compareAndSet(State.NOT_STARTED, State.PENDING),
+          "Task [%s] failed to run: invalid peon lifecycle state transition [%s]->[%s]",
+          taskId.getOriginalTaskId(),
+          state.get(),
+          State.PENDING
+      );
+
+      kubernetesClient.launchPeonJobAndWaitForStart(
+          job,
+          launchTimeout,
+          TimeUnit.MILLISECONDS
+      );
+
+      return join(timeout);
+    }
+    finally {
+      state.set(State.STOPPED);
+    }
+  }
+
+  /**
+   * Join existing Kubernetes Job
+   *
+   * @param timeout
+   * @return
+   * @throws IllegalStateException
+   */
+  protected synchronized TaskStatus join(long timeout) throws IllegalStateException
+  {
+    try {
+      Preconditions.checkState(
+          (
+              state.compareAndSet(State.NOT_STARTED, State.RUNNING) ||
+              state.compareAndSet(State.PENDING, State.RUNNING)
+          ),
+          "Task [%s] failed to join: invalid peon lifecycle state transition [%s]->[%s]",
+          taskId.getOriginalTaskId(),
+          state.get(),
+          State.RUNNING
+      );
+
+      JobResponse jobResponse = kubernetesClient.waitForPeonJobCompletion(
+          taskId,
+          timeout,
+          TimeUnit.MILLISECONDS
+      );
+
+      saveLogs();
+
+      return getTaskStatus(jobResponse.getJobDuration());
+    }
+    finally {
+      try {
+        shutdown();
+      }
+      catch (Exception e) {
+        log.warn(e, "Task [%s] shutdown failed", taskId);
+      }
+
+      state.set(State.STOPPED);
+    }
+  }
+
+  /**
+   * Shutdown Kubernetes job and associated pods
+   *
+   * Behavior: Deletes Kubernetes job which a kill signal to the containers running in
+   * the job's associated pod.
+   *
+   * Task state will be set by the thread running the run(...) or join(...) commands
+   */
+  protected void shutdown()
+  {
+    if (State.PENDING.equals(state.get()) || State.RUNNING.equals(state.get())) {
+      kubernetesClient.deletePeonJob(taskId);
+    }
+  }
+
+  /**
+   * Stream logs from the Kubernetes pod running the peon process
+   *
+   * @return
+   */
+  protected Optional<InputStream> streamLogs()
+  {
+    if (!State.RUNNING.equals(state.get())) {
+      return Optional.absent();
+    }
+    return kubernetesClient.getPeonLogs(taskId);
+  }
+
+  /**
+   * Get peon lifecycle state
+   *
+   * @return
+   */
+  protected State getState()
+  {
+    return state.get();
+  }
+
+  /**
+   * Get task location for the Kubernetes pod running the peon process
+   *
+   * @return
+   */
+  protected TaskLocation getTaskLocation()
+  {
+    if (!State.RUNNING.equals(state.get())) {
+      return TaskLocation.unknown();
+    }
+
+    Optional<Pod> maybePod = kubernetesClient.getPeonPod(taskId);
+    if (!maybePod.isPresent()) {
+      return TaskLocation.unknown();
+    }
+
+    Pod pod = maybePod.get();
+    PodStatus podStatus = pod.getStatus();
+
+    if (podStatus == null || podStatus.getPodIP() == null) {
+      return TaskLocation.unknown();
+    }
+
+    return TaskLocation.create(
+        podStatus.getPodIP(),
+        DruidK8sConstants.PORT,
+        DruidK8sConstants.TLS_PORT,
+        Boolean.parseBoolean(pod.getMetadata()
+            .getAnnotations()
+            .getOrDefault(DruidK8sConstants.TLS_ENABLED, "false")
+        )
+    );
+  }
+
+  private TaskStatus getTaskStatus(long duration)
+  {
+    TaskStatus taskStatus;
+    try {
+      Optional<InputStream> maybeTaskStatusStream = taskLogs.streamTaskStatus(taskId.getOriginalTaskId());
+      if (maybeTaskStatusStream.isPresent()) {
+        taskStatus = mapper.readValue(
+            IOUtils.toString(maybeTaskStatusStream.get(), StandardCharsets.UTF_8),
+            TaskStatus.class
+        );
+      } else {
+        taskStatus = TaskStatus.failure(taskId.getOriginalTaskId(), "task status not found");
+      }
+    }
+    catch (IOException e) {
+      log.error(e, "Failed to load task status for task [%s]", taskId.getOriginalTaskId());
+      taskStatus = TaskStatus.failure(
+          taskId.getOriginalTaskId(),
+          StringUtils.format("error loading status: %s", e.getMessage())
+      );
+    }
+
+    return taskStatus.withDuration(duration);
+  }
+
+  private void saveLogs()
+  {
+    try {
+      Path file = Files.createTempFile(taskId.getOriginalTaskId(), "file");
+      try {
+        Optional<InputStream> maybeLogStream = streamLogs();
+        if (maybeLogStream.isPresent()) {
+          FileUtils.copyInputStreamToFile(maybeLogStream.get(), file.toFile());
+        }

Review Comment:
   again a debug log here will be helpful. 



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesPeonLifecycle.java:
##########
@@ -0,0 +1,279 @@
+/*
+ * 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.druid.k8s.overlord;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import io.fabric8.kubernetes.api.model.Pod;
+import io.fabric8.kubernetes.api.model.PodStatus;
+import io.fabric8.kubernetes.api.model.batch.v1.Job;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.druid.indexer.TaskLocation;
+import org.apache.druid.indexer.TaskStatus;
+import org.apache.druid.indexing.common.task.Task;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.emitter.EmittingLogger;
+import org.apache.druid.k8s.overlord.common.DruidK8sConstants;
+import org.apache.druid.k8s.overlord.common.JobResponse;
+import org.apache.druid.k8s.overlord.common.K8sTaskId;
+import org.apache.druid.k8s.overlord.common.KubernetesPeonClient;
+import org.apache.druid.tasklogs.TaskLogs;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+public class KubernetesPeonLifecycle
+{
+  private static final EmittingLogger log = new EmittingLogger(KubernetesPeonLifecycle.class);
+
+  protected enum State
+  {
+    /** Lifecycle's state before {@link #run(Job, long, long)} or {@link #join(long)} is called. */
+    NOT_STARTED,
+    /** Lifecycle's state since {@link #run(Job, long, long)} is called. */
+    PENDING,
+    /** Lifecycle's state since {@link #join(long)} is called. */
+    RUNNING,
+    /** Lifecycle's state since the task has completed. */
+    STOPPED
+  }
+
+  private final AtomicReference<State> state = new AtomicReference<>(State.NOT_STARTED);
+  private final K8sTaskId taskId;
+  private final TaskLogs taskLogs;
+  private final KubernetesPeonClient kubernetesClient;
+  private final ObjectMapper mapper;
+
+  protected KubernetesPeonLifecycle(
+      Task task,
+      KubernetesPeonClient kubernetesClient,
+      TaskLogs taskLogs,
+      ObjectMapper mapper
+  )
+  {
+    this.taskId = new K8sTaskId(task);
+    this.kubernetesClient = kubernetesClient;
+    this.taskLogs = taskLogs;
+    this.mapper = mapper;
+  }
+
+  /**
+   * Run a Kubernetes Job
+   *
+   * @param job
+   * @param launchTimeout
+   * @param timeout
+   * @return
+   * @throws IllegalStateException
+   */
+  protected synchronized TaskStatus run(Job job, long launchTimeout, long timeout) throws IllegalStateException
+  {
+    try {
+      Preconditions.checkState(
+          state.compareAndSet(State.NOT_STARTED, State.PENDING),
+          "Task [%s] failed to run: invalid peon lifecycle state transition [%s]->[%s]",
+          taskId.getOriginalTaskId(),
+          state.get(),
+          State.PENDING
+      );
+
+      kubernetesClient.launchPeonJobAndWaitForStart(
+          job,
+          launchTimeout,
+          TimeUnit.MILLISECONDS
+      );
+
+      return join(timeout);
+    }
+    finally {
+      state.set(State.STOPPED);
+    }
+  }
+
+  /**
+   * Join existing Kubernetes Job
+   *
+   * @param timeout
+   * @return
+   * @throws IllegalStateException
+   */
+  protected synchronized TaskStatus join(long timeout) throws IllegalStateException
+  {
+    try {
+      Preconditions.checkState(
+          (
+              state.compareAndSet(State.NOT_STARTED, State.RUNNING) ||
+              state.compareAndSet(State.PENDING, State.RUNNING)
+          ),
+          "Task [%s] failed to join: invalid peon lifecycle state transition [%s]->[%s]",
+          taskId.getOriginalTaskId(),
+          state.get(),
+          State.RUNNING
+      );
+
+      JobResponse jobResponse = kubernetesClient.waitForPeonJobCompletion(
+          taskId,
+          timeout,
+          TimeUnit.MILLISECONDS
+      );
+
+      saveLogs();
+
+      return getTaskStatus(jobResponse.getJobDuration());
+    }
+    finally {
+      try {
+        shutdown();
+      }
+      catch (Exception e) {
+        log.warn(e, "Task [%s] shutdown failed", taskId);
+      }
+
+      state.set(State.STOPPED);
+    }
+  }
+
+  /**
+   * Shutdown Kubernetes job and associated pods
+   *
+   * Behavior: Deletes Kubernetes job which a kill signal to the containers running in
+   * the job's associated pod.
+   *
+   * Task state will be set by the thread running the run(...) or join(...) commands
+   */
+  protected void shutdown()
+  {
+    if (State.PENDING.equals(state.get()) || State.RUNNING.equals(state.get())) {
+      kubernetesClient.deletePeonJob(taskId);
+    }
+  }
+
+  /**
+   * Stream logs from the Kubernetes pod running the peon process
+   *
+   * @return
+   */
+  protected Optional<InputStream> streamLogs()
+  {
+    if (!State.RUNNING.equals(state.get())) {
+      return Optional.absent();
+    }
+    return kubernetesClient.getPeonLogs(taskId);
+  }
+
+  /**
+   * Get peon lifecycle state
+   *
+   * @return
+   */
+  protected State getState()
+  {
+    return state.get();
+  }
+
+  /**
+   * Get task location for the Kubernetes pod running the peon process
+   *
+   * @return
+   */
+  protected TaskLocation getTaskLocation()
+  {
+    if (!State.RUNNING.equals(state.get())) {
+      return TaskLocation.unknown();
+    }
+
+    Optional<Pod> maybePod = kubernetesClient.getPeonPod(taskId);
+    if (!maybePod.isPresent()) {
+      return TaskLocation.unknown();
+    }
+
+    Pod pod = maybePod.get();
+    PodStatus podStatus = pod.getStatus();
+
+    if (podStatus == null || podStatus.getPodIP() == null) {
+      return TaskLocation.unknown();
+    }
+
+    return TaskLocation.create(
+        podStatus.getPodIP(),
+        DruidK8sConstants.PORT,
+        DruidK8sConstants.TLS_PORT,
+        Boolean.parseBoolean(pod.getMetadata()
+            .getAnnotations()
+            .getOrDefault(DruidK8sConstants.TLS_ENABLED, "false")
+        )
+    );
+  }
+
+  private TaskStatus getTaskStatus(long duration)
+  {
+    TaskStatus taskStatus;
+    try {
+      Optional<InputStream> maybeTaskStatusStream = taskLogs.streamTaskStatus(taskId.getOriginalTaskId());
+      if (maybeTaskStatusStream.isPresent()) {
+        taskStatus = mapper.readValue(
+            IOUtils.toString(maybeTaskStatusStream.get(), StandardCharsets.UTF_8),
+            TaskStatus.class
+        );
+      } else {
+        taskStatus = TaskStatus.failure(taskId.getOriginalTaskId(), "task status not found");
+      }
+    }
+    catch (IOException e) {
+      log.error(e, "Failed to load task status for task [%s]", taskId.getOriginalTaskId());
+      taskStatus = TaskStatus.failure(
+          taskId.getOriginalTaskId(),
+          StringUtils.format("error loading status: %s", e.getMessage())
+      );
+    }
+
+    return taskStatus.withDuration(duration);
+  }
+
+  private void saveLogs()
+  {
+    try {
+      Path file = Files.createTempFile(taskId.getOriginalTaskId(), "file");

Review Comment:
   why not name the file as "log"?



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesPeonLifecycle.java:
##########
@@ -0,0 +1,279 @@
+/*
+ * 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.druid.k8s.overlord;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import io.fabric8.kubernetes.api.model.Pod;
+import io.fabric8.kubernetes.api.model.PodStatus;
+import io.fabric8.kubernetes.api.model.batch.v1.Job;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.druid.indexer.TaskLocation;
+import org.apache.druid.indexer.TaskStatus;
+import org.apache.druid.indexing.common.task.Task;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.emitter.EmittingLogger;
+import org.apache.druid.k8s.overlord.common.DruidK8sConstants;
+import org.apache.druid.k8s.overlord.common.JobResponse;
+import org.apache.druid.k8s.overlord.common.K8sTaskId;
+import org.apache.druid.k8s.overlord.common.KubernetesPeonClient;
+import org.apache.druid.tasklogs.TaskLogs;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+public class KubernetesPeonLifecycle
+{
+  private static final EmittingLogger log = new EmittingLogger(KubernetesPeonLifecycle.class);
+
+  protected enum State
+  {
+    /** Lifecycle's state before {@link #run(Job, long, long)} or {@link #join(long)} is called. */
+    NOT_STARTED,
+    /** Lifecycle's state since {@link #run(Job, long, long)} is called. */
+    PENDING,
+    /** Lifecycle's state since {@link #join(long)} is called. */
+    RUNNING,
+    /** Lifecycle's state since the task has completed. */
+    STOPPED
+  }
+
+  private final AtomicReference<State> state = new AtomicReference<>(State.NOT_STARTED);
+  private final K8sTaskId taskId;
+  private final TaskLogs taskLogs;
+  private final KubernetesPeonClient kubernetesClient;
+  private final ObjectMapper mapper;
+
+  protected KubernetesPeonLifecycle(
+      Task task,
+      KubernetesPeonClient kubernetesClient,
+      TaskLogs taskLogs,
+      ObjectMapper mapper
+  )
+  {
+    this.taskId = new K8sTaskId(task);
+    this.kubernetesClient = kubernetesClient;
+    this.taskLogs = taskLogs;
+    this.mapper = mapper;
+  }
+
+  /**
+   * Run a Kubernetes Job
+   *
+   * @param job
+   * @param launchTimeout
+   * @param timeout
+   * @return
+   * @throws IllegalStateException
+   */
+  protected synchronized TaskStatus run(Job job, long launchTimeout, long timeout) throws IllegalStateException
+  {
+    try {
+      Preconditions.checkState(
+          state.compareAndSet(State.NOT_STARTED, State.PENDING),
+          "Task [%s] failed to run: invalid peon lifecycle state transition [%s]->[%s]",
+          taskId.getOriginalTaskId(),
+          state.get(),
+          State.PENDING
+      );
+
+      kubernetesClient.launchPeonJobAndWaitForStart(
+          job,
+          launchTimeout,
+          TimeUnit.MILLISECONDS
+      );
+
+      return join(timeout);
+    }
+    finally {
+      state.set(State.STOPPED);
+    }
+  }
+
+  /**
+   * Join existing Kubernetes Job
+   *
+   * @param timeout
+   * @return
+   * @throws IllegalStateException
+   */
+  protected synchronized TaskStatus join(long timeout) throws IllegalStateException
+  {
+    try {
+      Preconditions.checkState(
+          (
+              state.compareAndSet(State.NOT_STARTED, State.RUNNING) ||
+              state.compareAndSet(State.PENDING, State.RUNNING)
+          ),
+          "Task [%s] failed to join: invalid peon lifecycle state transition [%s]->[%s]",
+          taskId.getOriginalTaskId(),
+          state.get(),
+          State.RUNNING
+      );
+
+      JobResponse jobResponse = kubernetesClient.waitForPeonJobCompletion(
+          taskId,
+          timeout,
+          TimeUnit.MILLISECONDS
+      );
+
+      saveLogs();
+
+      return getTaskStatus(jobResponse.getJobDuration());
+    }
+    finally {
+      try {
+        shutdown();
+      }
+      catch (Exception e) {
+        log.warn(e, "Task [%s] shutdown failed", taskId);
+      }
+
+      state.set(State.STOPPED);
+    }
+  }
+
+  /**
+   * Shutdown Kubernetes job and associated pods
+   *
+   * Behavior: Deletes Kubernetes job which a kill signal to the containers running in
+   * the job's associated pod.
+   *
+   * Task state will be set by the thread running the run(...) or join(...) commands
+   */
+  protected void shutdown()
+  {
+    if (State.PENDING.equals(state.get()) || State.RUNNING.equals(state.get())) {
+      kubernetesClient.deletePeonJob(taskId);
+    }
+  }
+
+  /**
+   * Stream logs from the Kubernetes pod running the peon process
+   *
+   * @return
+   */
+  protected Optional<InputStream> streamLogs()
+  {
+    if (!State.RUNNING.equals(state.get())) {
+      return Optional.absent();
+    }
+    return kubernetesClient.getPeonLogs(taskId);
+  }
+
+  /**
+   * Get peon lifecycle state
+   *
+   * @return
+   */
+  protected State getState()
+  {
+    return state.get();
+  }
+
+  /**
+   * Get task location for the Kubernetes pod running the peon process
+   *
+   * @return
+   */
+  protected TaskLocation getTaskLocation()
+  {
+    if (!State.RUNNING.equals(state.get())) {
+      return TaskLocation.unknown();

Review Comment:
   some debug logging here will be useful in case we see a problem where task location is somehow always unknown. 



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesPeonLifecycle.java:
##########
@@ -0,0 +1,279 @@
+/*
+ * 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.druid.k8s.overlord;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import io.fabric8.kubernetes.api.model.Pod;
+import io.fabric8.kubernetes.api.model.PodStatus;
+import io.fabric8.kubernetes.api.model.batch.v1.Job;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.druid.indexer.TaskLocation;
+import org.apache.druid.indexer.TaskStatus;
+import org.apache.druid.indexing.common.task.Task;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.emitter.EmittingLogger;
+import org.apache.druid.k8s.overlord.common.DruidK8sConstants;
+import org.apache.druid.k8s.overlord.common.JobResponse;
+import org.apache.druid.k8s.overlord.common.K8sTaskId;
+import org.apache.druid.k8s.overlord.common.KubernetesPeonClient;
+import org.apache.druid.tasklogs.TaskLogs;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+public class KubernetesPeonLifecycle
+{
+  private static final EmittingLogger log = new EmittingLogger(KubernetesPeonLifecycle.class);
+
+  protected enum State
+  {
+    /** Lifecycle's state before {@link #run(Job, long, long)} or {@link #join(long)} is called. */
+    NOT_STARTED,
+    /** Lifecycle's state since {@link #run(Job, long, long)} is called. */
+    PENDING,
+    /** Lifecycle's state since {@link #join(long)} is called. */
+    RUNNING,
+    /** Lifecycle's state since the task has completed. */
+    STOPPED
+  }
+
+  private final AtomicReference<State> state = new AtomicReference<>(State.NOT_STARTED);
+  private final K8sTaskId taskId;
+  private final TaskLogs taskLogs;
+  private final KubernetesPeonClient kubernetesClient;
+  private final ObjectMapper mapper;
+
+  protected KubernetesPeonLifecycle(

Review Comment:
   is this class expected to be overridden? what is the reason for methods in this class to be marked protected? 



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesPeonLifecycle.java:
##########
@@ -0,0 +1,279 @@
+/*
+ * 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.druid.k8s.overlord;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import io.fabric8.kubernetes.api.model.Pod;
+import io.fabric8.kubernetes.api.model.PodStatus;
+import io.fabric8.kubernetes.api.model.batch.v1.Job;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.druid.indexer.TaskLocation;
+import org.apache.druid.indexer.TaskStatus;
+import org.apache.druid.indexing.common.task.Task;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.emitter.EmittingLogger;
+import org.apache.druid.k8s.overlord.common.DruidK8sConstants;
+import org.apache.druid.k8s.overlord.common.JobResponse;
+import org.apache.druid.k8s.overlord.common.K8sTaskId;
+import org.apache.druid.k8s.overlord.common.KubernetesPeonClient;
+import org.apache.druid.tasklogs.TaskLogs;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+public class KubernetesPeonLifecycle

Review Comment:
   Please add some javadocs here to understand what this class does



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesPeonLifecycle.java:
##########
@@ -0,0 +1,279 @@
+/*
+ * 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.druid.k8s.overlord;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import io.fabric8.kubernetes.api.model.Pod;
+import io.fabric8.kubernetes.api.model.PodStatus;
+import io.fabric8.kubernetes.api.model.batch.v1.Job;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.druid.indexer.TaskLocation;
+import org.apache.druid.indexer.TaskStatus;
+import org.apache.druid.indexing.common.task.Task;
+import org.apache.druid.java.util.common.StringUtils;
+import org.apache.druid.java.util.emitter.EmittingLogger;
+import org.apache.druid.k8s.overlord.common.DruidK8sConstants;
+import org.apache.druid.k8s.overlord.common.JobResponse;
+import org.apache.druid.k8s.overlord.common.K8sTaskId;
+import org.apache.druid.k8s.overlord.common.KubernetesPeonClient;
+import org.apache.druid.tasklogs.TaskLogs;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+public class KubernetesPeonLifecycle
+{
+  private static final EmittingLogger log = new EmittingLogger(KubernetesPeonLifecycle.class);
+
+  protected enum State
+  {
+    /** Lifecycle's state before {@link #run(Job, long, long)} or {@link #join(long)} is called. */
+    NOT_STARTED,
+    /** Lifecycle's state since {@link #run(Job, long, long)} is called. */
+    PENDING,
+    /** Lifecycle's state since {@link #join(long)} is called. */
+    RUNNING,
+    /** Lifecycle's state since the task has completed. */
+    STOPPED
+  }
+
+  private final AtomicReference<State> state = new AtomicReference<>(State.NOT_STARTED);
+  private final K8sTaskId taskId;
+  private final TaskLogs taskLogs;
+  private final KubernetesPeonClient kubernetesClient;
+  private final ObjectMapper mapper;
+
+  protected KubernetesPeonLifecycle(
+      Task task,
+      KubernetesPeonClient kubernetesClient,
+      TaskLogs taskLogs,
+      ObjectMapper mapper
+  )
+  {
+    this.taskId = new K8sTaskId(task);
+    this.kubernetesClient = kubernetesClient;
+    this.taskLogs = taskLogs;
+    this.mapper = mapper;
+  }
+
+  /**
+   * Run a Kubernetes Job
+   *
+   * @param job
+   * @param launchTimeout
+   * @param timeout
+   * @return
+   * @throws IllegalStateException
+   */
+  protected synchronized TaskStatus run(Job job, long launchTimeout, long timeout) throws IllegalStateException
+  {
+    try {
+      Preconditions.checkState(
+          state.compareAndSet(State.NOT_STARTED, State.PENDING),
+          "Task [%s] failed to run: invalid peon lifecycle state transition [%s]->[%s]",
+          taskId.getOriginalTaskId(),
+          state.get(),
+          State.PENDING
+      );
+
+      kubernetesClient.launchPeonJobAndWaitForStart(

Review Comment:
   maybe not in this PR but if there is a timeout exception here, we should try to kill the pod if any was launched. maybe inside the implementation of this method itself. 



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunner.java:
##########
@@ -89,174 +69,128 @@
 
 /**
  * Runs tasks as k8s jobs using the "internal peon" verb.
- * One additional feature of this class is that kubernetes is the source of truth, so if you launch a task
- * shutdown druid, bring up druid, the task will keep running and the state will be updated when the cluster
- * comes back.  Thus while no tasks are technically restorable, all tasks once launched will run in isolation to the
- * extent possible without requiring the overlord consistently up during their lifetime.
  */
-
 public class KubernetesTaskRunner implements TaskLogStreamer, TaskRunner
 {
-
   private static final EmittingLogger log = new EmittingLogger(KubernetesTaskRunner.class);
   private final CopyOnWriteArrayList<Pair<TaskRunnerListener, Executor>> listeners = new CopyOnWriteArrayList<>();
 
   // to cleanup old jobs that might not have been deleted.
   private final ScheduledExecutorService cleanupExecutor;
 
-  protected final ConcurrentHashMap<String, K8sWorkItem> tasks = new ConcurrentHashMap<>();
+  protected final ConcurrentHashMap<String, KubernetesWorkItem> tasks = new ConcurrentHashMap<>();
   protected final TaskAdapter adapter;
-  protected final KubernetesPeonClient client;
 
-  private final ObjectMapper mapper;
-  private final KubernetesTaskRunnerConfig k8sConfig;
-  private final TaskQueueConfig taskQueueConfig;
-  private final TaskLogs taskLogs;
+  private final KubernetesPeonClient client;
+  private final KubernetesTaskRunnerConfig config;
   private final ListeningExecutorService exec;
   private final HttpClient httpClient;
+  private final PeonLifecycleFactory peonLifecycleFactory;
 
 
   public KubernetesTaskRunner(
-      ObjectMapper mapper,
       TaskAdapter adapter,
-      KubernetesTaskRunnerConfig k8sConfig,
-      TaskQueueConfig taskQueueConfig,
-      TaskLogs taskLogs,
+      KubernetesTaskRunnerConfig config,
       KubernetesPeonClient client,
-      HttpClient httpClient
+      HttpClient httpClient,
+      PeonLifecycleFactory peonLifecycleFactory
   )
   {
-    this.mapper = mapper;
     this.adapter = adapter;
-    this.k8sConfig = k8sConfig;
-    this.taskQueueConfig = taskQueueConfig;
-    this.taskLogs = taskLogs;
+    this.config = config;
     this.client = client;
     this.httpClient = httpClient;
+    this.peonLifecycleFactory = peonLifecycleFactory;
     this.cleanupExecutor = Executors.newScheduledThreadPool(1);
     this.exec = MoreExecutors.listeningDecorator(
-        Execs.multiThreaded(taskQueueConfig.getMaxSize(), "k8s-task-runner-%d")
-    );
-    Preconditions.checkArgument(
-        taskQueueConfig.getMaxSize() < Integer.MAX_VALUE,
-        "The task queue bounds how many concurrent k8s tasks you can have"
+        Execs.multiThreaded(config.getCapacity(), "k8s-task-runner-%d")
     );
   }
 
-
   @Override
   public Optional<InputStream> streamTaskLog(String taskid, long offset)
   {
-    return client.getPeonLogs(new K8sTaskId(taskid));
+    KubernetesWorkItem workItem = tasks.get(taskid);
+    if (workItem == null) {
+      return Optional.absent();
+    }
+    return workItem.streamTaskLogs();
   }
 
   @Override
   public ListenableFuture<TaskStatus> run(Task task)
   {
     synchronized (tasks) {
-      tasks.computeIfAbsent(
-          task.getId(), k -> new K8sWorkItem(
-              client,
-              task,
-              exec.submit(() -> {
-                K8sTaskId k8sTaskId = new K8sTaskId(task);
-                try {
-                  JobResponse completedPhase;
-                  Optional<Job> existingJob = client.jobExists(k8sTaskId);
-                  if (!existingJob.isPresent()) {
-                    Job job = adapter.fromTask(task);
-                    log.info("Job created %s and ready to launch", k8sTaskId);
-                    Pod peonPod = client.launchJobAndWaitForStart(
-                        job,
-                        KubernetesTaskRunnerConfig.toMilliseconds(k8sConfig.k8sjobLaunchTimeout),
-                        TimeUnit.MILLISECONDS
-                    );
-                    log.info("Job %s launched in k8s", k8sTaskId);
-                    completedPhase = monitorJob(peonPod, k8sTaskId);
-                  } else {
-                    Job job = existingJob.get();
-                    if (job.getStatus().getActive() == null) {
-                      if (job.getStatus().getSucceeded() != null) {
-                        completedPhase = new JobResponse(job, PeonPhase.SUCCEEDED);
-                      } else {
-                        completedPhase = new JobResponse(job, PeonPhase.FAILED);
-                      }
-                    } else {
-                      // the job is active lets monitor it
-                      completedPhase = monitorJob(k8sTaskId);
-                    }
-                  }
-                  TaskStatus status = getTaskStatus(k8sTaskId, completedPhase);
-                  if (completedPhase.getJobDuration().isPresent()) {
-                    status = status.withDuration(completedPhase.getJobDuration().get());
-                  }
-                  updateStatus(task, status);
-                  return status;
-                }
-                catch (Exception e) {
-                  log.error(e, "Error with task: %s", k8sTaskId);
-                  throw e;
-                }
-                finally {
-                  // publish task logs
-                  Path log = Files.createTempFile(task.getId(), "log");
-                  try {
-                    Optional<InputStream> logStream = client.getPeonLogs(new K8sTaskId(task.getId()));
-                    if (logStream.isPresent()) {
-                      FileUtils.copyInputStreamToFile(logStream.get(), log.toFile());
-                    }
-                    taskLogs.pushTaskLog(task.getId(), log.toFile());
-                  }
-                  finally {
-                    Files.deleteIfExists(log);
-                  }
-                  client.cleanUpJob(new K8sTaskId(task.getId()));
-                  synchronized (tasks) {
-                    tasks.remove(task.getId());
-                  }
-                }
-              })
-          ));
+      tasks.computeIfAbsent(task.getId(), k -> new KubernetesWorkItem(task, exec.submit(() -> runTask(task))));
+      return tasks.get(task.getId()).getResult();
+    }
+  }
+
+  protected ListenableFuture<TaskStatus> join(Task task)

Review Comment:
   can this be renamed to `joinAsync`? We use similar convention elsewhere. E.g. `stopAsync` / `stop` methods in SeekableStreamSupervisor. 



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunner.java:
##########
@@ -318,61 +261,56 @@ public Optional<InputStream> streamTaskReports(String taskid) throws IOException
   @Override
   public List<Pair<Task, ListenableFuture<TaskStatus>>> restore()
   {
-    return ImmutableList.of();
+    List<Pair<Task, ListenableFuture<TaskStatus>>> tasks = new ArrayList<>();
+    for (Job job : client.getPeonJobs()) {
+      try {
+        Task task = adapter.toTask(job);
+        tasks.add(Pair.of(task, join(task)));
+      }
+      catch (IOException e) {
+        log.error("Error deserializing task from job [%s]", job.getMetadata().getName());

Review Comment:
   please log the original exception as well. 



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/common/KubernetesPeonClient.java:
##########
@@ -19,37 +19,218 @@
 
 package org.apache.druid.k8s.overlord.common;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Optional;
 import io.fabric8.kubernetes.api.model.Pod;
 import io.fabric8.kubernetes.api.model.batch.v1.Job;
+import io.fabric8.kubernetes.client.KubernetesClient;
+import io.fabric8.kubernetes.client.dsl.LogWatch;
+import org.apache.druid.java.util.common.RetryUtils;
+import org.apache.druid.java.util.emitter.EmittingLogger;
 
 import java.io.InputStream;
+import java.sql.Timestamp;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
 
-/**
- * A Kubernetes client wrapper to assist with peon task managment.
- * It provides a high level api to retreive jobs, launch jobs, delete jobs and various other
- * tasks like getting task logs, listing all active tasks.
- */
-public interface KubernetesPeonClient
+public class KubernetesPeonClient
 {
+  private static final EmittingLogger log = new EmittingLogger(KubernetesPeonClient.class);
+
+  private final KubernetesClientApi clientApi;
+  private final String namespace;
+  private final boolean debugJobs;
+
+  public KubernetesPeonClient(KubernetesClientApi clientApi, String namespace, boolean debugJobs)
+  {
+    this.clientApi = clientApi;
+    this.namespace = namespace;
+    this.debugJobs = debugJobs;
+  }
+
+  public Pod launchPeonJobAndWaitForStart(Job job, long howLong, TimeUnit timeUnit)
+  {
+    long start = System.currentTimeMillis();
+    // launch job
+    return clientApi.executeRequest(client -> {
+      client.batch().v1().jobs().inNamespace(namespace).resource(job).create();
+      K8sTaskId taskId = new K8sTaskId(job.getMetadata().getName());
+      log.info("Successfully submitted job: %s ... waiting for job to launch", taskId);
+      // wait until the pod is running or complete or failed, any of those is fine
+      Pod mainPod = getPeonPodWithRetries(taskId);
+      Pod result = client.pods().inNamespace(namespace).withName(mainPod.getMetadata().getName())
+                         .waitUntilCondition(pod -> {
+                           if (pod == null) {
+                             return false;
+                           }
+                           return pod.getStatus() != null && pod.getStatus().getPodIP() != null;
+                         }, howLong, timeUnit);
+      long duration = System.currentTimeMillis() - start;
+      log.info("Took task %s %d ms for pod to startup", taskId, duration);
+      return result;
+    });
+  }
 
-  Optional<Job> jobExists(K8sTaskId taskId);
+  public JobResponse waitForPeonJobCompletion(K8sTaskId taskId, long howLong, TimeUnit unit)
+  {
+    return clientApi.executeRequest(client -> {
+      Job job = client.batch()
+                      .v1()
+                      .jobs()
+                      .inNamespace(namespace)
+                      .withName(taskId.getK8sTaskId())
+                      .waitUntilCondition(
+                          x -> (x == null) || (x.getStatus() != null && x.getStatus().getActive() == null
+                          && (x.getStatus().getFailed() != null || x.getStatus().getSucceeded() != null)),
+                          howLong,
+                          unit
+                      );
+      if (job == null) {
+        log.info("K8s job for the task [%s] was not found. It can happen if the task was canceled", taskId);
+        return new JobResponse(null, PeonPhase.FAILED);
+      }
+      if (job.getStatus().getSucceeded() != null) {
+        return new JobResponse(job, PeonPhase.SUCCEEDED);
+      }
+      log.warn("Task %s failed with status %s", taskId, job.getStatus());
+      return new JobResponse(job, PeonPhase.FAILED);
+    });
+  }
 
-  Pod launchJobAndWaitForStart(Job job, long howLong, TimeUnit timeUnit);
+  public boolean deletePeonJob(K8sTaskId taskId)
+  {
+    if (!debugJobs) {
+      Boolean result = clientApi.executeRequest(client -> !client.batch()
+                                                                 .v1()
+                                                                 .jobs()
+                                                                 .inNamespace(namespace)
+                                                                 .withName(taskId.getK8sTaskId())
+                                                                 .delete().isEmpty());
+      if (result) {
+        log.info("Cleaned up k8s task: %s", taskId);
+      } else {
+        log.info("K8s task does not exist: %s", taskId);
+      }
+      return result;
+    } else {
+      log.info("Not cleaning up task %s due to flag: debugJobs=true", taskId);
+      return true;
+    }
+  }
 
-  JobResponse waitForJobCompletion(K8sTaskId taskId, long howLong, TimeUnit timeUnit);
+  public Optional<InputStream> getPeonLogs(K8sTaskId taskId)
+  {
+    KubernetesClient k8sClient = clientApi.getClient();
+    try {
+      LogWatch logWatch = k8sClient.batch()
+                                   .v1()
+                                   .jobs()
+                                   .inNamespace(namespace)
+                                   .withName(taskId.getK8sTaskId())
+                                   .inContainer("main")
+                                   .watchLog();
+      if (logWatch == null) {
+        k8sClient.close();
+        return Optional.absent();
+      }
+      return Optional.of(new LogWatchInputStream(k8sClient, logWatch));
+    }
+    catch (Exception e) {
+      log.error(e, "Error streaming logs from task: %s", taskId);
+      k8sClient.close();
+      return Optional.absent();
+    }
+  }
 
-  boolean cleanUpJob(K8sTaskId taskId);
+  public List<Job> getPeonJobs()
+  {
+    return clientApi.executeRequest(client -> client.batch()
+                                                    .v1()
+                                                    .jobs()
+                                                    .inNamespace(namespace)
+                                                    .withLabel(DruidK8sConstants.LABEL_KEY)
+                                                    .list()
+                                                    .getItems());
+  }
 
-  Optional<InputStream> getPeonLogs(K8sTaskId taskId);
+  public int deleteCompletedPeonJobsOlderThan(long howFarBack, TimeUnit timeUnit)
+  {
+    AtomicInteger numDeleted = new AtomicInteger();
+    return clientApi.executeRequest(client -> {
+      List<Job> jobs = getJobsToCleanup(getPeonJobs(), howFarBack, timeUnit);
+      jobs.forEach(x -> {
+        if (!client.batch()
+                   .v1()
+                   .jobs()
+                   .inNamespace(namespace)
+                   .withName(x.getMetadata().getName())
+                   .delete().isEmpty()) {
+          numDeleted.incrementAndGet();

Review Comment:
   we should log a warning if deleting a job failed. 



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/common/KubernetesPeonClient.java:
##########
@@ -19,37 +19,218 @@
 
 package org.apache.druid.k8s.overlord.common;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Optional;
 import io.fabric8.kubernetes.api.model.Pod;
 import io.fabric8.kubernetes.api.model.batch.v1.Job;
+import io.fabric8.kubernetes.client.KubernetesClient;
+import io.fabric8.kubernetes.client.dsl.LogWatch;
+import org.apache.druid.java.util.common.RetryUtils;
+import org.apache.druid.java.util.emitter.EmittingLogger;
 
 import java.io.InputStream;
+import java.sql.Timestamp;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
 
-/**
- * A Kubernetes client wrapper to assist with peon task managment.
- * It provides a high level api to retreive jobs, launch jobs, delete jobs and various other
- * tasks like getting task logs, listing all active tasks.
- */
-public interface KubernetesPeonClient
+public class KubernetesPeonClient
 {
+  private static final EmittingLogger log = new EmittingLogger(KubernetesPeonClient.class);
+
+  private final KubernetesClientApi clientApi;
+  private final String namespace;
+  private final boolean debugJobs;
+
+  public KubernetesPeonClient(KubernetesClientApi clientApi, String namespace, boolean debugJobs)
+  {
+    this.clientApi = clientApi;
+    this.namespace = namespace;
+    this.debugJobs = debugJobs;
+  }
+
+  public Pod launchPeonJobAndWaitForStart(Job job, long howLong, TimeUnit timeUnit)
+  {
+    long start = System.currentTimeMillis();
+    // launch job
+    return clientApi.executeRequest(client -> {
+      client.batch().v1().jobs().inNamespace(namespace).resource(job).create();
+      K8sTaskId taskId = new K8sTaskId(job.getMetadata().getName());
+      log.info("Successfully submitted job: %s ... waiting for job to launch", taskId);
+      // wait until the pod is running or complete or failed, any of those is fine
+      Pod mainPod = getPeonPodWithRetries(taskId);
+      Pod result = client.pods().inNamespace(namespace).withName(mainPod.getMetadata().getName())
+                         .waitUntilCondition(pod -> {
+                           if (pod == null) {
+                             return false;
+                           }
+                           return pod.getStatus() != null && pod.getStatus().getPodIP() != null;
+                         }, howLong, timeUnit);
+      long duration = System.currentTimeMillis() - start;
+      log.info("Took task %s %d ms for pod to startup", taskId, duration);

Review Comment:
   https://github.com/apache/druid/blob/master/dev/style-conventions.md#message-formatting-logs-and-exceptions



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunner.java:
##########
@@ -89,174 +69,128 @@
 
 /**
  * Runs tasks as k8s jobs using the "internal peon" verb.
- * One additional feature of this class is that kubernetes is the source of truth, so if you launch a task
- * shutdown druid, bring up druid, the task will keep running and the state will be updated when the cluster
- * comes back.  Thus while no tasks are technically restorable, all tasks once launched will run in isolation to the
- * extent possible without requiring the overlord consistently up during their lifetime.
  */
-
 public class KubernetesTaskRunner implements TaskLogStreamer, TaskRunner
 {
-
   private static final EmittingLogger log = new EmittingLogger(KubernetesTaskRunner.class);
   private final CopyOnWriteArrayList<Pair<TaskRunnerListener, Executor>> listeners = new CopyOnWriteArrayList<>();
 
   // to cleanup old jobs that might not have been deleted.
   private final ScheduledExecutorService cleanupExecutor;
 
-  protected final ConcurrentHashMap<String, K8sWorkItem> tasks = new ConcurrentHashMap<>();
+  protected final ConcurrentHashMap<String, KubernetesWorkItem> tasks = new ConcurrentHashMap<>();
   protected final TaskAdapter adapter;
-  protected final KubernetesPeonClient client;
 
-  private final ObjectMapper mapper;
-  private final KubernetesTaskRunnerConfig k8sConfig;
-  private final TaskQueueConfig taskQueueConfig;
-  private final TaskLogs taskLogs;
+  private final KubernetesPeonClient client;
+  private final KubernetesTaskRunnerConfig config;
   private final ListeningExecutorService exec;
   private final HttpClient httpClient;
+  private final PeonLifecycleFactory peonLifecycleFactory;
 
 
   public KubernetesTaskRunner(
-      ObjectMapper mapper,
       TaskAdapter adapter,
-      KubernetesTaskRunnerConfig k8sConfig,
-      TaskQueueConfig taskQueueConfig,
-      TaskLogs taskLogs,
+      KubernetesTaskRunnerConfig config,
       KubernetesPeonClient client,
-      HttpClient httpClient
+      HttpClient httpClient,
+      PeonLifecycleFactory peonLifecycleFactory
   )
   {
-    this.mapper = mapper;
     this.adapter = adapter;
-    this.k8sConfig = k8sConfig;
-    this.taskQueueConfig = taskQueueConfig;
-    this.taskLogs = taskLogs;
+    this.config = config;
     this.client = client;
     this.httpClient = httpClient;
+    this.peonLifecycleFactory = peonLifecycleFactory;
     this.cleanupExecutor = Executors.newScheduledThreadPool(1);
     this.exec = MoreExecutors.listeningDecorator(
-        Execs.multiThreaded(taskQueueConfig.getMaxSize(), "k8s-task-runner-%d")
-    );
-    Preconditions.checkArgument(
-        taskQueueConfig.getMaxSize() < Integer.MAX_VALUE,
-        "The task queue bounds how many concurrent k8s tasks you can have"
+        Execs.multiThreaded(config.getCapacity(), "k8s-task-runner-%d")
     );
   }
 
-
   @Override
   public Optional<InputStream> streamTaskLog(String taskid, long offset)
   {
-    return client.getPeonLogs(new K8sTaskId(taskid));
+    KubernetesWorkItem workItem = tasks.get(taskid);
+    if (workItem == null) {
+      return Optional.absent();
+    }
+    return workItem.streamTaskLogs();
   }
 
   @Override
   public ListenableFuture<TaskStatus> run(Task task)
   {
     synchronized (tasks) {
-      tasks.computeIfAbsent(
-          task.getId(), k -> new K8sWorkItem(
-              client,
-              task,
-              exec.submit(() -> {
-                K8sTaskId k8sTaskId = new K8sTaskId(task);
-                try {
-                  JobResponse completedPhase;
-                  Optional<Job> existingJob = client.jobExists(k8sTaskId);
-                  if (!existingJob.isPresent()) {
-                    Job job = adapter.fromTask(task);
-                    log.info("Job created %s and ready to launch", k8sTaskId);
-                    Pod peonPod = client.launchJobAndWaitForStart(
-                        job,
-                        KubernetesTaskRunnerConfig.toMilliseconds(k8sConfig.k8sjobLaunchTimeout),
-                        TimeUnit.MILLISECONDS
-                    );
-                    log.info("Job %s launched in k8s", k8sTaskId);
-                    completedPhase = monitorJob(peonPod, k8sTaskId);
-                  } else {
-                    Job job = existingJob.get();
-                    if (job.getStatus().getActive() == null) {
-                      if (job.getStatus().getSucceeded() != null) {
-                        completedPhase = new JobResponse(job, PeonPhase.SUCCEEDED);
-                      } else {
-                        completedPhase = new JobResponse(job, PeonPhase.FAILED);
-                      }
-                    } else {
-                      // the job is active lets monitor it
-                      completedPhase = monitorJob(k8sTaskId);
-                    }
-                  }
-                  TaskStatus status = getTaskStatus(k8sTaskId, completedPhase);
-                  if (completedPhase.getJobDuration().isPresent()) {
-                    status = status.withDuration(completedPhase.getJobDuration().get());
-                  }
-                  updateStatus(task, status);
-                  return status;
-                }
-                catch (Exception e) {
-                  log.error(e, "Error with task: %s", k8sTaskId);
-                  throw e;
-                }
-                finally {
-                  // publish task logs
-                  Path log = Files.createTempFile(task.getId(), "log");
-                  try {
-                    Optional<InputStream> logStream = client.getPeonLogs(new K8sTaskId(task.getId()));
-                    if (logStream.isPresent()) {
-                      FileUtils.copyInputStreamToFile(logStream.get(), log.toFile());
-                    }
-                    taskLogs.pushTaskLog(task.getId(), log.toFile());
-                  }
-                  finally {
-                    Files.deleteIfExists(log);
-                  }
-                  client.cleanUpJob(new K8sTaskId(task.getId()));
-                  synchronized (tasks) {
-                    tasks.remove(task.getId());
-                  }
-                }
-              })
-          ));
+      tasks.computeIfAbsent(task.getId(), k -> new KubernetesWorkItem(task, exec.submit(() -> runTask(task))));
+      return tasks.get(task.getId()).getResult();
+    }
+  }
+
+  protected ListenableFuture<TaskStatus> join(Task task)
+  {
+    synchronized (tasks) {
+      tasks.computeIfAbsent(task.getId(), k -> new KubernetesWorkItem(task, exec.submit(() -> joinTask(task))));
       return tasks.get(task.getId()).getResult();
     }
   }
 
-  JobResponse monitorJob(K8sTaskId k8sTaskId)
+  private TaskStatus runTask(Task task)
   {
-    return monitorJob(client.getMainJobPod(k8sTaskId), k8sTaskId);
+    return doTask(task, true);
   }
 
-  JobResponse monitorJob(Pod peonPod, K8sTaskId k8sTaskId)
+  private TaskStatus joinTask(Task task)
   {
-    if (peonPod == null) {
-      throw new ISE("Error in k8s launching peon pod for task %s", k8sTaskId);
-    }
-    return client.waitForJobCompletion(
-        k8sTaskId,
-        KubernetesTaskRunnerConfig.toMilliseconds(k8sConfig.maxTaskDuration),
-        TimeUnit.MILLISECONDS
-    );
+    return doTask(task, false);
   }
 
-  private TaskStatus getTaskStatus(K8sTaskId task, JobResponse jobResponse) throws IOException
+  @VisibleForTesting
+  protected TaskStatus doTask(Task task, boolean run)
   {
-    Optional<InputStream> maybeTaskStatusStream = taskLogs.streamTaskStatus(task.getOriginalTaskId());
-    if (maybeTaskStatusStream.isPresent()) {
-      String taskStatus = IOUtils.toString(maybeTaskStatusStream.get(), StandardCharsets.UTF_8);
-      return mapper.readValue(taskStatus, TaskStatus.class);
-    } else if (PeonPhase.SUCCEEDED.equals(jobResponse.getPhase())) {
-      // fallback to behavior before the introduction of task status streaming for backwards compatibility
-      return TaskStatus.success(task.getOriginalTaskId());
-    } else if (Objects.isNull(jobResponse.getJob())) {
-      return TaskStatus.failure(
-          task.getOriginalTaskId(),
-          StringUtils.format("Task [%s] failed kubernetes job disappeared before completion", task.getOriginalTaskId())
-      );
-    } else {
-      return TaskStatus.failure(
-          task.getOriginalTaskId(),
-          StringUtils.format("Task [%s] failed", task.getOriginalTaskId())
-      );
+    KubernetesPeonLifecycle peonLifecycle = peonLifecycleFactory.build(task);
+
+    synchronized (tasks) {
+      KubernetesWorkItem workItem = tasks.get(task.getId());
+
+      if (workItem == null) {
+        throw new ISE("Task [%s] disappeared", task.getId());
+      }
+
+      if (workItem.isShutdownRequested()) {
+        throw new ISE("Task [%s] has been shut down", task.getId());
+      }
+
+      workItem.setKubernetesPeonLifecycle(peonLifecycle);
+    }
+
+    try {
+      TaskStatus taskStatus;
+      if (run) {
+        taskStatus = peonLifecycle.run(
+            adapter.fromTask(task),
+            config.getTaskLaunchTimeout().toStandardDuration().getMillis(),
+            config.getTaskTimeout().toStandardDuration().getMillis()
+        );
+      } else {
+        taskStatus = peonLifecycle.join(
+            config.getTaskTimeout().toStandardDuration().getMillis()
+        );
+      }
+
+      updateStatus(task, taskStatus);
+
+      return taskStatus;
+    }
+
+    catch (Exception e) {
+      log.error(e, "Task [%s] execution caught an exception", task.getId());

Review Comment:
   do we cleanup the task when such an exception happens? 



##########
extensions-contrib/kubernetes-overlord-extensions/src/main/java/org/apache/druid/k8s/overlord/KubernetesTaskRunner.java:
##########
@@ -89,174 +69,128 @@
 
 /**
  * Runs tasks as k8s jobs using the "internal peon" verb.
- * One additional feature of this class is that kubernetes is the source of truth, so if you launch a task

Review Comment:
   lets use this PR itself if we can. 



-- 
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: commits-unsubscribe@druid.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org