morningman commented on code in PR #26845:
URL: https://github.com/apache/doris/pull/26845#discussion_r1391946138


##########
fe/fe-core/src/main/java/org/apache/doris/job/executor/DefaultTaskExecutorHandler.java:
##########
@@ -0,0 +1,75 @@
+// 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.doris.job.executor;
+
+import org.apache.doris.job.disruptor.ExecuteTaskEvent;
+import org.apache.doris.job.manager.TaskTokenManager;
+import org.apache.doris.job.task.AbstractTask;
+
+import com.lmax.disruptor.WorkHandler;
+import lombok.extern.slf4j.Slf4j;
+
+import java.util.concurrent.Semaphore;
+
+/**
+ * DefaultTaskExecutor is an implementation of the TaskExecutor interface.
+ * if you need to implement your own TaskExecutor, you could refer to this 
class. and need to register
+ * it in the TaskExecutorFactory
+ * It executes a given AbstractTask by acquiring a semaphore token from the 
TaskTokenManager
+ * and releasing it after the task execution.
+ */
+@Slf4j
+public class DefaultTaskExecutorHandler<T extends AbstractTask> implements 
WorkHandler<ExecuteTaskEvent<T>> {
+
+
+    @Override
+    public void onEvent(ExecuteTaskEvent<T> executeTaskEvent) {
+        T task = executeTaskEvent.getTask();
+        if (null == task) {
+            log.warn("task is null, ignore,maybe task has been canceled");
+            return;
+        }
+        if (task.isCancelled()) {
+            log.info("task is canceled, ignore");
+            return;
+        }
+        if (null == executeTaskEvent.getJobConfig().getMaxConcurrentTaskNum()
+                || executeTaskEvent.getJobConfig().getMaxConcurrentTaskNum() 
<= 0) {
+            try {
+                task.runTask();
+                return;
+            } catch (Exception e) {
+                log.warn("execute task error, task id is {}", 
task.getTaskId(), e);
+            }
+        }
+        Semaphore semaphore = null;

Review Comment:
   should be if..else here?
   will it be blocked here?



##########
fe/fe-core/src/main/java/org/apache/doris/job/scheduler/JobScheduler.java:
##########
@@ -0,0 +1,173 @@
+// 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.doris.job.scheduler;
+
+import org.apache.doris.common.CustomThreadFactory;
+import org.apache.doris.common.util.TimeUtils;
+import org.apache.doris.job.base.AbstractJob;
+import org.apache.doris.job.base.JobExecuteType;
+import org.apache.doris.job.common.JobStatus;
+import org.apache.doris.job.common.TaskType;
+import org.apache.doris.job.disruptor.TaskDisruptor;
+import org.apache.doris.job.executor.TimerJobSchedulerTask;
+import org.apache.doris.job.manager.TaskDisruptorGroupManager;
+import org.apache.doris.job.task.AbstractTask;
+
+import io.netty.util.HashedWheelTimer;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+@Slf4j
+public class JobScheduler<T extends AbstractJob<?>> implements Closeable {
+
+    /**
+     * scheduler tasks, it's used to scheduler job
+     */
+    private HashedWheelTimer timerTaskScheduler;
+
+    private TaskDisruptor timerJobDisruptor;
+
+    private TaskDisruptorGroupManager taskDisruptorGroupManager;
+
+    private long latestBatchSchedulerTimerTaskTimeMs = 0L;
+
+    private static final long BATCH_SCHEDULER_INTERVAL_SECONDS = 60;
+
+    private static final int HASHED_WHEEL_TIMER_TICKS_PER_WHEEL = 660;
+
+    private final Map<Long, T> jobMap;
+
+    public JobScheduler(Map<Long, T> jobMap) {
+        this.jobMap = jobMap;
+    }
+
+    /**
+     * batch scheduler interval ms time
+     */
+    private static final long BATCH_SCHEDULER_INTERVAL_MILLI_SECONDS = 
BATCH_SCHEDULER_INTERVAL_SECONDS * 1000L;
+
+    public void start() {
+        timerTaskScheduler = new HashedWheelTimer(new 
CustomThreadFactory("timer-task-scheduler"), 1,
+                TimeUnit.SECONDS, HASHED_WHEEL_TIMER_TICKS_PER_WHEEL);
+        timerTaskScheduler.start();
+        taskDisruptorGroupManager = new TaskDisruptorGroupManager();
+        taskDisruptorGroupManager.init();
+        this.timerJobDisruptor = 
taskDisruptorGroupManager.getDispatchDisruptor();
+        latestBatchSchedulerTimerTaskTimeMs = System.currentTimeMillis();
+        batchSchedulerTimerJob();
+        cycleSystemSchedulerTasks();
+    }
+
+    /**
+     * We will cycle system scheduler tasks every 10 minutes.
+     * Jobs will be re-registered after the task is completed
+     */
+    private void cycleSystemSchedulerTasks() {
+        log.info("re-register system scheduler timer tasks" + 
TimeUtils.longToTimeString(System.currentTimeMillis()));
+        timerTaskScheduler.newTimeout(timeout -> {
+            batchSchedulerTimerJob();
+            cycleSystemSchedulerTasks();
+        }, BATCH_SCHEDULER_INTERVAL_SECONDS, TimeUnit.SECONDS);
+
+    }
+
+    private void batchSchedulerTimerJob() {
+        executeTimerJobIdsWithinLastTenMinutesWindow();
+    }
+
+    public void scheduleOneJob(T job) {
+        if (!job.getJobStatus().equals(JobStatus.RUNNING)) {
+            return;
+        }
+        if (!job.getJobConfig().checkIsTimerJob()) {
+            //manual job will not scheduler
+            if 
(JobExecuteType.MANUAL.equals(job.getJobConfig().getExecuteType())) {
+                return;
+            }
+            //todo skip streaming job,improve in the future
+            if 
(JobExecuteType.INSTANT.equals(job.getJobConfig().getExecuteType()) && 
job.isReadyForScheduling()) {
+                schedulerImmediateJob(job);
+            }
+        }
+        //if it's timer job and trigger last window already start, we will 
scheduler it immediately
+        cycleTimerJobScheduler(job);
+    }
+
+    @Override
+    public void close() throws IOException {
+
+    }
+
+
+    private void cycleTimerJobScheduler(T job) {
+        List<Long> delaySeconds = 
job.getJobConfig().getTriggerDelayTimes(System.currentTimeMillis(),
+                System.currentTimeMillis(), 
latestBatchSchedulerTimerTaskTimeMs);
+        if (CollectionUtils.isNotEmpty(delaySeconds)) {
+            delaySeconds.forEach(delaySecond -> {
+                TimerJobSchedulerTask<T> timerJobSchedulerTask = new 
TimerJobSchedulerTask<>(timerJobDisruptor, job);
+                timerTaskScheduler.newTimeout(timerJobSchedulerTask, 
delaySecond, TimeUnit.SECONDS);
+            });
+        }
+    }
+
+
+    private void schedulerImmediateJob(T job) {
+        List<? extends AbstractTask> tasks = job.createTasks(TaskType.MANUAL);
+        if (CollectionUtils.isEmpty(tasks)) {
+            return;

Review Comment:
   Need to update the job's status?
   Or the job will be in RUNNING state forever 



##########
fe/fe-core/src/main/java/org/apache/doris/job/executor/TimerJobSchedulerTask.java:
##########
@@ -0,0 +1,48 @@
+// 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.doris.job.executor;
+
+import org.apache.doris.job.base.AbstractJob;
+import org.apache.doris.job.disruptor.TaskDisruptor;
+
+import io.netty.util.Timeout;
+import io.netty.util.TimerTask;
+import jline.internal.Log;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
+public class TimerJobSchedulerTask<T extends AbstractJob<?>> implements 
TimerTask {

Review Comment:
   What is the relation between TimerJobSchedulerTask and `Task`?



##########
fe/fe-core/src/main/java/org/apache/doris/analysis/CreateJobStmt.java:
##########
@@ -123,24 +112,43 @@ public void analyze(Analyzer analyzer) throws 
UserException {
         labelName.analyze(analyzer);
         String dbName = labelName.getDbName();
         Env.getCurrentInternalCatalog().getDbOrAnalysisException(dbName);
-        job.setDbName(labelName.getDbName());
-        job.setJobName(labelName.getLabelName());
-        if (StringUtils.isNotBlank(onceJobStartTimestamp)) {
-            analyzerOnceTimeJob();
-        } else {
-            analyzerCycleJob();
+        analyzerSqlStmt();
+        // check its insert stmt,currently only support insert stmt
+        InsertJob job = new InsertJob();
+        JobExecutionConfiguration jobExecutionConfiguration = new 
JobExecutionConfiguration();
+        jobExecutionConfiguration.setExecuteType(executeType);
+        job.setCreateTimeMs(System.currentTimeMillis());
+        TimerDefinition timerDefinition = new TimerDefinition();
+
+        if (null != onceJobStartTimestamp) {
+            
timerDefinition.setStartTimeMs(TimeUtils.timeStringToLong(onceJobStartTimestamp));
+        }
+        if (null != interval) {
+            timerDefinition.setInterval(interval);
+        }
+        if (null != intervalTimeUnit) {
+            
timerDefinition.setIntervalUnit(IntervalUnit.valueOf(intervalTimeUnit.toUpperCase()));
         }
-        if (ConnectContext.get() != null) {
-            timezone = ConnectContext.get().getSessionVariable().getTimeZone();
+        if (null != startsTimeStamp) {
+            
timerDefinition.setStartTimeMs(TimeUtils.timeStringToLong(startsTimeStamp));
         }
-        timezone = TimeUtils.checkTimeZoneValidAndStandardize(timezone);
-        job.setTimezone(timezone);
+        if (null != endsTimeStamp) {
+            
timerDefinition.setEndTimeMs(TimeUtils.timeStringToLong(endsTimeStamp));
+        }
+        jobExecutionConfiguration.setTimerDefinition(timerDefinition);
+        job.setJobConfig(jobExecutionConfiguration);
+
         job.setComment(comment);
-        //todo support user define
-        job.setUser(ConnectContext.get().getQualifiedUser());
+        job.setCurrentDbName(labelName.getDbName());
+        job.setJobName(labelName.getLabelName());
+        job.setComment(comment);

Review Comment:
   duplicate



##########
fe/fe-core/src/main/java/org/apache/doris/job/executor/DefaultTaskExecutorHandler.java:
##########
@@ -0,0 +1,75 @@
+// 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.doris.job.executor;
+
+import org.apache.doris.job.disruptor.ExecuteTaskEvent;
+import org.apache.doris.job.manager.TaskTokenManager;
+import org.apache.doris.job.task.AbstractTask;
+
+import com.lmax.disruptor.WorkHandler;
+import lombok.extern.slf4j.Slf4j;
+
+import java.util.concurrent.Semaphore;
+
+/**
+ * DefaultTaskExecutor is an implementation of the TaskExecutor interface.
+ * if you need to implement your own TaskExecutor, you could refer to this 
class. and need to register
+ * it in the TaskExecutorFactory
+ * It executes a given AbstractTask by acquiring a semaphore token from the 
TaskTokenManager
+ * and releasing it after the task execution.
+ */
+@Slf4j
+public class DefaultTaskExecutorHandler<T extends AbstractTask> implements 
WorkHandler<ExecuteTaskEvent<T>> {
+
+
+    @Override
+    public void onEvent(ExecuteTaskEvent<T> executeTaskEvent) {
+        T task = executeTaskEvent.getTask();
+        if (null == task) {
+            log.warn("task is null, ignore,maybe task has been canceled");
+            return;
+        }
+        if (task.isCancelled()) {
+            log.info("task is canceled, ignore");
+            return;
+        }
+        if (null == executeTaskEvent.getJobConfig().getMaxConcurrentTaskNum()
+                || executeTaskEvent.getJobConfig().getMaxConcurrentTaskNum() 
<= 0) {
+            try {
+                task.runTask();
+                return;
+            } catch (Exception e) {
+                log.warn("execute task error, task id is {}", 
task.getTaskId(), e);

Review Comment:
   How to handle this exception?
   I think the logic in `runTask()` can be moved to here?



##########
fe/fe-core/src/main/java/org/apache/doris/analysis/CreateJobStmt.java:
##########
@@ -123,24 +112,43 @@ public void analyze(Analyzer analyzer) throws 
UserException {
         labelName.analyze(analyzer);
         String dbName = labelName.getDbName();
         Env.getCurrentInternalCatalog().getDbOrAnalysisException(dbName);
-        job.setDbName(labelName.getDbName());
-        job.setJobName(labelName.getLabelName());
-        if (StringUtils.isNotBlank(onceJobStartTimestamp)) {
-            analyzerOnceTimeJob();
-        } else {
-            analyzerCycleJob();
+        analyzerSqlStmt();
+        // check its insert stmt,currently only support insert stmt
+        InsertJob job = new InsertJob();
+        JobExecutionConfiguration jobExecutionConfiguration = new 
JobExecutionConfiguration();
+        jobExecutionConfiguration.setExecuteType(executeType);
+        job.setCreateTimeMs(System.currentTimeMillis());
+        TimerDefinition timerDefinition = new TimerDefinition();
+
+        if (null != onceJobStartTimestamp) {
+            
timerDefinition.setStartTimeMs(TimeUtils.timeStringToLong(onceJobStartTimestamp));
+        }
+        if (null != interval) {
+            timerDefinition.setInterval(interval);
+        }
+        if (null != intervalTimeUnit) {
+            
timerDefinition.setIntervalUnit(IntervalUnit.valueOf(intervalTimeUnit.toUpperCase()));
         }
-        if (ConnectContext.get() != null) {
-            timezone = ConnectContext.get().getSessionVariable().getTimeZone();
+        if (null != startsTimeStamp) {
+            
timerDefinition.setStartTimeMs(TimeUtils.timeStringToLong(startsTimeStamp));
         }
-        timezone = TimeUtils.checkTimeZoneValidAndStandardize(timezone);
-        job.setTimezone(timezone);
+        if (null != endsTimeStamp) {
+            
timerDefinition.setEndTimeMs(TimeUtils.timeStringToLong(endsTimeStamp));
+        }
+        jobExecutionConfiguration.setTimerDefinition(timerDefinition);
+        job.setJobConfig(jobExecutionConfiguration);
+
         job.setComment(comment);
-        //todo support user define
-        job.setUser(ConnectContext.get().getQualifiedUser());
+        job.setCurrentDbName(labelName.getDbName());
+        job.setJobName(labelName.getLabelName());
+        job.setComment(comment);
+        job.setCreateUser(ConnectContext.get().getQualifiedUser());

Review Comment:
   ```suggestion
           job.setCreateUser(ConnectContext.get().getCurrentUserIdentity());
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/job/scheduler/JobScheduler.java:
##########
@@ -0,0 +1,171 @@
+// 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.doris.job.scheduler;
+
+import org.apache.doris.common.CustomThreadFactory;
+import org.apache.doris.common.util.TimeUtils;
+import org.apache.doris.job.base.AbstractJob;
+import org.apache.doris.job.base.JobExecuteType;
+import org.apache.doris.job.common.JobStatus;
+import org.apache.doris.job.common.TaskType;
+import org.apache.doris.job.disruptor.TaskDisruptor;
+import org.apache.doris.job.executor.TimerJobSchedulerTask;
+import org.apache.doris.job.manager.TaskDisruptorGroupManager;
+import org.apache.doris.job.task.AbstractTask;
+
+import io.netty.util.HashedWheelTimer;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+@Slf4j
+public class JobScheduler<T extends AbstractJob<?>> implements Closeable {

Review Comment:
   So you need a AbstractJobScheduler



##########
fe/fe-core/src/main/java/org/apache/doris/analysis/CreateJobStmt.java:
##########
@@ -81,16 +81,17 @@ public class CreateJobStmt extends DdlStmt {
     private final String endsTimeStamp;
 
     private final String comment;
+    private JobExecuteType executeType;
 
     private String timezone = TimeUtils.DEFAULT_TIME_ZONE;
 
     private static final ImmutableSet<Class<? extends DdlStmt>> 
supportStmtSuperClass
             = new ImmutableSet.Builder<Class<? extends 
DdlStmt>>().add(InsertStmt.class)

Review Comment:
   Use InsertIntoCommand 



-- 
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-unsubscr...@doris.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org
For additional commands, e-mail: commits-h...@doris.apache.org

Reply via email to