View Javadoc
1   /*
2    * Copyright 2012-2025 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.app.job;
17  
18  import org.apache.logging.log4j.LogManager;
19  import org.apache.logging.log4j.Logger;
20  import org.codelibs.core.timer.TimeoutTask;
21  import org.codelibs.fess.Constants;
22  import org.codelibs.fess.exception.ScheduledJobException;
23  import org.codelibs.fess.helper.JobHelper;
24  import org.codelibs.fess.helper.SystemHelper;
25  import org.codelibs.fess.job.JobExecutor;
26  import org.codelibs.fess.opensearch.config.exentity.JobLog;
27  import org.codelibs.fess.opensearch.config.exentity.ScheduledJob;
28  import org.codelibs.fess.util.ComponentUtil;
29  import org.lastaflute.job.JobManager;
30  import org.lastaflute.job.LaJob;
31  import org.lastaflute.job.LaJobRuntime;
32  import org.lastaflute.job.key.LaJobUnique;
33  
34  /**
35   * This job executes a script.
36   */
37  public class ScriptExecutorJob implements LaJob {
38      /**
39       * Constructor.
40       */
41      public ScriptExecutorJob() {
42          super();
43      }
44  
45      private static final Logger logger = LogManager.getLogger(ScriptExecutorJob.class);
46  
47      @Override
48      public void run(final LaJobRuntime runtime) {
49          final JobHelper jobHelper = ComponentUtil.getJobHelper();
50          try {
51              jobHelper.setJobRuntime(runtime);
52              process(runtime);
53          } finally {
54              jobHelper.setJobRuntime(null);
55          }
56      }
57  
58      /**
59       * Processes the job.
60       * @param runtime The job runtime.
61       */
62      protected void process(final LaJobRuntime runtime) {
63          if (!runtime.getParameterMap().containsKey(Constants.SCHEDULED_JOB)) {
64              logger.warn("Scheduled job is empty: key={}", Constants.SCHEDULED_JOB);
65              return;
66          }
67          runtime.stopIfNeeds();
68  
69          final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
70          final JobManager jobManager = ComponentUtil.getJobManager();
71          final ScheduledJob scheduledJob = (ScheduledJob) runtime.getParameterMap().get(Constants.SCHEDULED_JOB);
72          final String id = scheduledJob.getId();
73          final String target = scheduledJob.getTarget();
74          if (!ComponentUtil.getFessConfig().isSchedulerTarget(target)) {
75              logger.info("Ignoring job: name={}, id={}, target={}", scheduledJob.getName(), id, scheduledJob.getTarget());
76              return;
77          }
78  
79          final JobHelper jobHelper = ComponentUtil.getJobHelper();
80          if (!jobHelper.isAvailable(id)) {
81              logger.info("Job is unavailable, unregistering: id={}", id);
82              jobHelper.unregister(scheduledJob);
83              return;
84          }
85  
86          final JobLog jobLog = new JobLog(scheduledJob);
87          final String jobLogId = (String) runtime.getParameterMap().get(Constants.JOB_LOG_ID);
88          if (jobLogId != null) {
89              jobLog.setId(jobLogId);
90          }
91          final String scriptType = scheduledJob.getScriptType();
92          final String script = scheduledJob.getScriptData();
93  
94          final JobExecutor jobExecutor = ComponentUtil.getJobExecutor(scriptType);
95          if (jobExecutor == null) {
96              throw new ScheduledJobException("No jobExecutor: " + scriptType);
97          }
98  
99          if (!jobManager.findJobByUniqueOf(LaJobUnique.of(id)).isPresent()) {
100             if (logger.isDebugEnabled()) {
101                 logger.debug("Job is running: id={}", id);
102             }
103             return;
104         }
105 
106         TimeoutTask task = null;
107         try {
108             if (scheduledJob.isLoggingEnabled()) {
109                 jobHelper.store(jobLog);
110                 task = jobHelper.startMonitorTask(jobLog);
111             }
112 
113             if (logger.isDebugEnabled()) {
114                 logger.debug("Starting job: id={}, scriptType={}, script={}", id, scriptType, script);
115             } else if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) {
116                 logger.info("Starting job: id={}", id);
117             }
118 
119             final Object ret = jobExecutor.execute(Constants.DEFAULT_SCRIPT, script);
120             if (ret == null) {
121                 if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) {
122                     logger.info("Finished job: id={}", id);
123                 }
124             } else {
125                 if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) {
126                     logger.info("Finished job: id={}, returnValue:\n{}", id, ret);
127                 }
128                 jobLog.setScriptResult(ret.toString());
129             }
130             jobLog.setJobStatus(Constants.OK);
131         } catch (final Throwable t) {
132             logger.warn("Failed to execute job: id={}, script={}", id, script, t);
133             jobLog.setJobStatus(Constants.FAIL);
134             jobLog.setScriptResult(systemHelper.abbreviateLongText(t.getLocalizedMessage()));
135         } finally {
136             if (task != null) {
137                 try {
138                     task.stop();
139                 } catch (final Exception e) {
140                     logger.warn("Failed to stop job: {}", jobLog, e);
141                 }
142             }
143             jobLog.setEndTime(ComponentUtil.getSystemHelper().getCurrentTimeAsLong());
144             if (logger.isDebugEnabled()) {
145                 logger.debug("jobLog={}", jobLog);
146             }
147             if (scheduledJob.isLoggingEnabled()) {
148                 jobHelper.store(jobLog);
149             }
150         }
151     }
152 
153 }