github-advanced-security[bot] commented on code in PR #17353:
URL: https://github.com/apache/druid/pull/17353#discussion_r1804053065


##########
indexing-service/src/main/java/org/apache/druid/indexing/scheduledbatch/ScheduledBatchScheduler.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.indexing.scheduledbatch;
+
+import com.cronutils.model.time.ExecutionTime;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.inject.Inject;
+import org.apache.druid.indexer.TaskLocation;
+import org.apache.druid.indexer.TaskStatus;
+import org.apache.druid.indexing.overlord.TaskMaster;
+import org.apache.druid.indexing.overlord.TaskRunner;
+import org.apache.druid.indexing.overlord.TaskRunnerListener;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.concurrent.Execs;
+import org.apache.druid.java.util.common.concurrent.ScheduledExecutorFactory;
+import org.apache.druid.java.util.common.logger.Logger;
+import org.apache.druid.java.util.emitter.EmittingLogger;
+import org.apache.druid.java.util.emitter.service.ServiceEmitter;
+import org.apache.druid.sql.client.BrokerClient;
+import org.apache.druid.sql.http.SqlQuery;
+import org.apache.druid.sql.http.SqlTaskStatus;
+import org.joda.time.DateTime;
+import org.joda.time.Duration;
+
+import javax.annotation.Nullable;
+import java.time.Instant;
+import java.time.ZonedDateTime;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+public class ScheduledBatchScheduler
+{
+  private static final Logger log = new 
EmittingLogger(ScheduledBatchScheduler.class);
+
+  private final TaskRunnerListener taskRunnerListener;
+  private final TaskMaster taskMaster;
+  private final ScheduledBatchStatusTracker statusTracker;
+
+  private final ConcurrentHashMap<String, SchedulerManager> supervisorToManager
+      = new ConcurrentHashMap<>();
+
+  /**
+   * Single-threaded executor to process the cron jobs queue.
+   */
+  private final ScheduledExecutorService cronExecutor;
+
+  private final BrokerClient brokerClient;
+
+  @Inject
+  public ScheduledBatchScheduler(
+      final TaskMaster taskMaster,
+      final ScheduledExecutorFactory executorFactory,
+      final ServiceEmitter emitter,

Review Comment:
   ## Useless parameter
   
   The parameter 'emitter' is never used.
   
   [Show more 
details](https://github.com/apache/druid/security/code-scanning/8410)



##########
indexing-service/src/test/java/org/apache/druid/indexing/scheduledbatch/ScheduledBatchSupervisorSpecTest.java:
##########
@@ -0,0 +1,245 @@
+/*
+ * 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.indexing.scheduledbatch;
+
+import com.fasterxml.jackson.databind.InjectableValues;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.ImmutableList;
+import com.google.common.util.concurrent.Futures;
+import org.apache.druid.error.DruidException;
+import org.apache.druid.error.DruidExceptionMatcher;
+import org.apache.druid.guice.SupervisorModule;
+import org.apache.druid.indexing.overlord.supervisor.SupervisorSpec;
+import org.apache.druid.jackson.DefaultObjectMapper;
+import org.apache.druid.java.util.common.granularity.Granularities;
+import org.apache.druid.sql.calcite.planner.ExplainAttributes;
+import org.apache.druid.sql.client.BrokerClient;
+import org.apache.druid.sql.http.ExplainPlanInformation;
+import org.apache.druid.sql.http.SqlQuery;
+import org.hamcrest.MatcherAssert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.util.Collections;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+public class ScheduledBatchSupervisorSpecTest
+{
+  private static final ObjectMapper OBJECT_MAPPER = new DefaultObjectMapper();
+  private BrokerClient brokerClient;
+  private ScheduledBatchScheduler scheduler;
+  private SqlQuery query;
+
+  @Before
+  public void setUp()
+  {
+    brokerClient = Mockito.mock(BrokerClient.class);
+    scheduler = Mockito.mock(ScheduledBatchScheduler.class);
+
+    OBJECT_MAPPER.setInjectableValues(
+        new InjectableValues.Std()
+            .addValue(BrokerClient.class, brokerClient)
+            .addValue(ObjectMapper.class, OBJECT_MAPPER)
+            .addValue(ScheduledBatchScheduler.class, scheduler)
+    );
+    OBJECT_MAPPER.registerModules(
+        new SupervisorModule().getJacksonModules()
+    );
+
+    query = new SqlQuery(
+        "REPLACE INTO foo OVERWRITE ALL SELECT TIME_PARSE(ts) AS __time, c1 
FROM (VALUES('2023-01-01', 'insert_1'), ('2023-01-01', 'insert_2'), 
('2023-02-01', 'insert3')) AS t(ts, c1) PARTITIONED BY ALL ",
+        null,
+        false,
+        false,
+        false,
+        null,
+        null
+    );
+
+    final ExplainPlanInformation explainPlanInfo = new ExplainPlanInformation(
+        "",
+        "",
+        new ExplainAttributes("REPLACE", "foo", Granularities.ALL, null, null)
+    );
+    Mockito.when(brokerClient.explainPlanFor(query))
+           
.thenReturn(Futures.immediateFuture(ImmutableList.of(explainPlanInfo)));
+  }
+
+  @Test
+  public void testSerdeOfActiveSpec()
+  {
+    testSerde(
+        new ScheduledBatchSupervisorSpec(
+            query,
+            new UnixCronSchedulerConfig("* * * * *"),
+            false,
+            null,
+            null,
+            OBJECT_MAPPER,
+            scheduler,
+            brokerClient
+        )
+    );
+  }
+
+  @Test
+  public void testSerdeOfSuspendedSpec()
+  {
+    testSerde(
+        new ScheduledBatchSupervisorSpec(
+            query,
+            new UnixCronSchedulerConfig("@daily"),
+            true,
+            "foo",
+            "boo",
+            OBJECT_MAPPER,
+            scheduler,
+            brokerClient
+        )
+    );
+  }
+
+  @Test
+  public void testGetIdAndDataSources()
+  {
+    final ScheduledBatchSupervisorSpec activeSpec = new 
ScheduledBatchSupervisorSpec(
+        query,
+        new UnixCronSchedulerConfig("* * * * *"),
+        false,
+        null,
+        null,
+        OBJECT_MAPPER,
+        scheduler,
+        brokerClient
+    );
+    
assertTrue(activeSpec.getId().startsWith(ScheduledBatchSupervisorSpec.TYPE));
+    assertEquals(Collections.singletonList("foo"), 
activeSpec.getDataSources());
+    assertFalse(activeSpec.isSuspended());
+  }
+
+  @Test
+  public void testCreateSuspendedSpec()
+  {
+    final ScheduledBatchSupervisorSpec activeSpec = new 
ScheduledBatchSupervisorSpec(
+        query,
+        new UnixCronSchedulerConfig("* * * * *"),
+        false,
+        null,
+        null,
+        OBJECT_MAPPER,
+        scheduler,
+        brokerClient
+    );
+    assertFalse(activeSpec.isSuspended());
+
+    final ScheduledBatchSupervisorSpec suspendedSpec = 
activeSpec.createSuspendedSpec();
+    assertTrue(suspendedSpec.isSuspended());
+    assertEquals(activeSpec.getId(), suspendedSpec.getId());
+    assertEquals(activeSpec.getSpec(), suspendedSpec.getSpec());
+    assertEquals(activeSpec.getDataSources(), suspendedSpec.getDataSources());
+  }
+
+  @Test
+  public void testCreateRunningSpec()
+  {
+    final ScheduledBatchSupervisorSpec suspendedSpec = new 
ScheduledBatchSupervisorSpec(
+        query,
+        new UnixCronSchedulerConfig("* * * * *"),
+        true,
+        null,
+        null,
+        OBJECT_MAPPER,
+        scheduler,
+        brokerClient
+    );
+    assertTrue(suspendedSpec.isSuspended());
+
+    final ScheduledBatchSupervisorSpec activeSpec = 
suspendedSpec.createRunningSpec();
+    assertFalse(activeSpec.isSuspended());
+    assertEquals(activeSpec.getId(), suspendedSpec.getId());
+    assertEquals(activeSpec.getSpec(), suspendedSpec.getSpec());
+    assertEquals(activeSpec.getDataSources(), suspendedSpec.getDataSources());
+  }
+
+  @Test
+  public void testCreateSupervisorWithSelectQuery()
+  {
+    query = new SqlQuery(
+        "SELECT TIME_PARSE(ts) AS __time, c1 FROM (VALUES('2023-01-01', 
'insert_1'), ('2023-01-01', 'insert_2'), ('2023-02-01', 'insert3')) AS t(ts, 
c1) PARTITIONED BY ALL ",
+        null,
+        false,
+        false,
+        false,
+        null,
+        null
+    );
+
+    Mockito.when(brokerClient.explainPlanFor(query))
+           .thenReturn(Futures.immediateFuture(ImmutableList.of(
+               new ExplainPlanInformation(
+                   "",
+                   "",
+                   new ExplainAttributes("SELECT", null, null, null, null)
+               ))
+           ));
+
+    MatcherAssert.assertThat(
+        assertThrows(
+            DruidException.class,
+            () -> new ScheduledBatchSupervisorSpec(
+              query,
+              new UnixCronSchedulerConfig("* * * * *"),
+              true,
+              null,
+              null,
+              OBJECT_MAPPER,
+              scheduler,
+              brokerClient
+            )
+        ),
+        DruidExceptionMatcher.invalidInput().expectMessageIs(
+            "SELECT queries are not supported by the [scheduled_batch] 
supervisor. Only INSERT or REPLACE ingest queries are allowed."
+        )
+    );
+  }
+
+  private void testSerde(final ScheduledBatchSupervisorSpec spec)
+  {
+    try {
+      final String json = OBJECT_MAPPER.writeValueAsString(spec);
+      final SupervisorSpec deserialized = OBJECT_MAPPER.readValue(json, 
SupervisorSpec.class);
+      assertTrue(deserialized instanceof ScheduledBatchSupervisorSpec);
+
+      final ScheduledBatchSupervisorSpec observedSpec = 
(ScheduledBatchSupervisorSpec) deserialized;
+      assertEquals(spec.isSuspended(), observedSpec.isSuspended());
+      assertEquals(spec.getSpec(), observedSpec.getSpec());
+      assertEquals(spec.getId(), observedSpec.getId());
+      assertEquals(spec.getDataSources(), observedSpec.getDataSources());
+    }
+    catch (Exception e) {
+      throw DruidException.defensive(e, "Error while performing serde of 
spec[%s].", spec);

Review Comment:
   ## Use of default toString()
   
   Default toString(): ScheduledBatchSupervisorSpec inherits toString() from 
Object, and so is not suitable for printing.
   
   [Show more 
details](https://github.com/apache/druid/security/code-scanning/8409)



##########
indexing-service/src/main/java/org/apache/druid/indexing/scheduledbatch/ScheduledBatchSupervisor.java:
##########
@@ -0,0 +1,121 @@
+/*
+ * 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.indexing.scheduledbatch;
+
+import org.apache.druid.indexing.overlord.DataSourceMetadata;
+import org.apache.druid.indexing.overlord.supervisor.Supervisor;
+import org.apache.druid.indexing.overlord.supervisor.SupervisorReport;
+import org.apache.druid.indexing.overlord.supervisor.SupervisorStateManager;
+import org.apache.druid.java.util.common.DateTimes;
+import org.apache.druid.java.util.common.logger.Logger;
+
+import javax.annotation.Nullable;
+
+public class ScheduledBatchSupervisor implements Supervisor
+{
+  private static final Logger log = new Logger(ScheduledBatchSupervisor.class);
+  private final ScheduledBatchSupervisorSpec supervisorSpec;
+  private final ScheduledBatchScheduler scheduler;
+
+  public ScheduledBatchSupervisor(
+      final ScheduledBatchSupervisorSpec supervisorSpec,
+      final ScheduledBatchScheduler scheduler
+  )
+  {
+    this.supervisorSpec = supervisorSpec;
+    this.scheduler = scheduler;
+  }
+
+  @Override
+  public void start()
+  {
+    if (supervisorSpec.isSuspended()) {
+      log.info("Suspending the scheduled batch supervisor[%s].", 
supervisorSpec.getId());
+      scheduler.stopScheduledIngestion(supervisorSpec.getId());
+    } else {
+      scheduler.startScheduledIngestion(
+          supervisorSpec.getId(),
+          supervisorSpec.getSchedulerConfig(),
+          supervisorSpec.getSpec()
+      );
+      log.info("Starting the scheduled batch supervisor[%s].", 
supervisorSpec.getId());
+    }
+  }
+
+  @Override
+  public void stop(boolean stopGracefully)
+  {
+    log.info("Stopping the scheduled batch supervisor[%s]", 
supervisorSpec.getId());
+    scheduler.stopScheduledIngestion(supervisorSpec.getId());
+  }
+
+  @Override
+  public SupervisorReport<ScheduledBatchSupervisorSnapshot> getStatus()
+  {
+    return new SupervisorReport<>(
+        supervisorSpec.getId(),
+        DateTimes.nowUtc(),
+        scheduler.getSchedulerSnapshot(supervisorSpec.getId())
+    );
+  }
+
+  @Override
+  public SupervisorStateManager.State getState()
+  {
+    if (supervisorSpec.isSuspended()) {
+      return State.SUSPENDED;
+    } else {
+      return State.RUNNING;
+    }
+  }
+
+  @Override
+  public void reset(@Nullable DataSourceMetadata dataSourceMetadata)
+  {
+    // do nothing
+  }
+
+  public enum State implements SupervisorStateManager.State

Review Comment:
   ## Class has same name as super class
   
   State has the same name as its supertype 
[org.apache.druid.indexing.overlord.supervisor.SupervisorStateManager$State](1).
   
   [Show more 
details](https://github.com/apache/druid/security/code-scanning/8408)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to