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