View Javadoc
1   /*
2    * Copyright 2012-2021 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.es.config.exentity.JobLog;
23  import org.codelibs.fess.es.config.exentity.ScheduledJob;
24  import org.codelibs.fess.exception.ScheduledJobException;
25  import org.codelibs.fess.helper.JobHelper;
26  import org.codelibs.fess.helper.SystemHelper;
27  import org.codelibs.fess.job.JobExecutor;
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  public class ScriptExecutorJob implements LaJob {
35      private static final Logger logger = LogManager.getLogger(ScriptExecutorJob.class);
36  
37      @Override
38      public void run(final LaJobRuntime runtime) {
39          final JobHelper jobHelper = ComponentUtil.getJobHelper();
40          try {
41              jobHelper.setJobRuntime(runtime);
42              process(runtime);
43          } finally {
44              jobHelper.setJobRuntime(null);
45          }
46      }
47  
48      protected void process(final LaJobRuntime runtime) {
49          if (!runtime.getParameterMap().containsKey(Constants.SCHEDULED_JOB)) {
50              logger.warn("{} is empty.", Constants.SCHEDULED_JOB);
51              return;
52          }
53          runtime.stopIfNeeds();
54  
55          final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
56          final JobManager jobManager = ComponentUtil.getJobManager();
57          final ScheduledJob scheduledJob = (ScheduledJob) runtime.getParameterMap().get(Constants.SCHEDULED_JOB);
58          final String id = scheduledJob.getId();
59          final String target = scheduledJob.getTarget();
60          if (!ComponentUtil.getFessConfig().isSchedulerTarget(target)) {
61              logger.info("Ignore Job {}:{} because of not target: {}", scheduledJob.getName(), id, scheduledJob.getTarget());
62              return;
63          }
64  
65          final JobHelper jobHelper = ComponentUtil.getJobHelper();
66          if (!jobHelper.isAvailable(id)) {
67              logger.info("Job {} is unavailable. Unregistering this job.", id);
68              jobHelper.unregister(scheduledJob);
69              return;
70          }
71  
72          final JobLog jobLog = new JobLog(scheduledJob);
73          final String scriptType = scheduledJob.getScriptType();
74          final String script = scheduledJob.getScriptData();
75  
76          final JobExecutor jobExecutor = ComponentUtil.getJobExecutor(scriptType);
77          if (jobExecutor == null) {
78              throw new ScheduledJobException("No jobExecutor: " + scriptType);
79          }
80  
81          if (!jobManager.findJobByUniqueOf(LaJobUnique.of(id)).isPresent()) {
82              if (logger.isDebugEnabled()) {
83                  logger.debug("Job {} is running.", id);
84              }
85              return;
86          }
87  
88          TimeoutTask task = null;
89          try {
90              if (scheduledJob.isLoggingEnabled()) {
91                  jobHelper.store(jobLog);
92                  task = jobHelper.startMonitorTask(jobLog);
93              }
94  
95              if (logger.isDebugEnabled()) {
96                  logger.debug("Starting Job {}. scriptType: {}, script: {}", id, scriptType, script);
97              } else if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) {
98                  logger.info("Starting Job {}.", id);
99              }
100 
101             final Object ret = jobExecutor.execute(Constants.DEFAULT_SCRIPT, script);
102             if (ret == null) {
103                 if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) {
104                     logger.info("Finished Job {}.", id);
105                 }
106             } else {
107                 if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) {
108                     logger.info("Finished Job {}. The return value is:\n{}", id, ret);
109                 }
110                 jobLog.setScriptResult(ret.toString());
111             }
112             jobLog.setJobStatus(Constants.OK);
113         } catch (final Throwable t) {
114             logger.warn("Failed to execute {}: {}", id, script, t);
115             jobLog.setJobStatus(Constants.FAIL);
116             jobLog.setScriptResult(systemHelper.abbreviateLongText(t.getLocalizedMessage()));
117         } finally {
118             if (task != null) {
119                 try {
120                     task.stop();
121                 } catch (final Exception e) {
122                     logger.warn("Failed to stop {}", jobLog, e);
123                 }
124             }
125             jobLog.setEndTime(ComponentUtil.getSystemHelper().getCurrentTimeAsLong());
126             if (logger.isDebugEnabled()) {
127                 logger.debug("jobLog: {}", jobLog);
128             }
129             if (scheduledJob.isLoggingEnabled()) {
130                 jobHelper.store(jobLog);
131             }
132         }
133     }
134 
135 }