View Javadoc

1   /**
2      This file is part of GoldenGate Project (named also GoldenGate or GG).
3   
4      Copyright 2009, Frederic Bregier, and individual contributors by the @author
5      tags. See the COPYRIGHT.txt in the distribution for a full listing of
6      individual contributors.
7   
8      All GoldenGate Project is free software: you can redistribute it and/or 
9      modify it under the terms of the GNU General Public License as published 
10     by the Free Software Foundation, either version 3 of the License, or
11     (at your option) any later version.
12  
13     GoldenGate is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17  
18     You should have received a copy of the GNU General Public License
19     along with GoldenGate .  If not, see <http://www.gnu.org/licenses/>.
20   */
21  package openr66.context.task;
22  
23  import goldengate.common.logging.GgInternalLogger;
24  import goldengate.common.logging.GgInternalLoggerFactory;
25  
26  import java.io.File;
27  import java.io.IOException;
28  
29  import openr66.context.ErrorCode;
30  import openr66.context.R66Result;
31  import openr66.context.R66Session;
32  import openr66.context.task.localexec.LocalExecClient;
33  import openr66.protocol.configuration.Configuration;
34  
35  import org.apache.commons.exec.CommandLine;
36  import org.apache.commons.exec.DefaultExecutor;
37  import org.apache.commons.exec.ExecuteException;
38  import org.apache.commons.exec.ExecuteWatchdog;
39  import org.apache.commons.exec.PumpStreamHandler;
40  
41  /**
42   * Execute an external command
43   *
44   *
45   * @author Frederic Bregier
46   *
47   */
48  public class ExecTask extends AbstractTask {
49  
50      /**
51       * Internal Logger
52       */
53      private static final GgInternalLogger logger = GgInternalLoggerFactory
54              .getLogger(ExecTask.class);
55  
56      /**
57       * @param argRule
58       * @param delay
59       * @param argTransfer
60       * @param session
61       */
62      public ExecTask(String argRule, int delay, String argTransfer,
63              R66Session session) {
64          super(TaskType.EXEC, delay, argRule, argTransfer, session);
65      }
66  
67      /*
68       * (non-Javadoc)
69       *
70       * @see openr66.context.task.AbstractTask#run()
71       */
72      @Override
73      public void run() {
74          /*
75           * First apply all replacements and format to argRule from context and
76           * argTransfer. Will call exec (from first element of resulting string)
77           * with arguments as the following value from the replacements. Return 0
78           * if OK, else 1 for a warning else as an error. No change should be done
79           * in the FILENAME
80           */
81          logger.debug("Exec with " + argRule + ":" + argTransfer + " and {}",
82                  session);
83          String finalname = argRule;
84          finalname = getReplacedValue(finalname, argTransfer.split(" "));
85          // Check if the execution will be done through LocalExec daemon
86          if (Configuration.configuration.useLocalExec && useLocalExec) {
87              LocalExecClient localExecClient = new LocalExecClient();
88              if (localExecClient.connect()) {
89                  localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion);
90                  localExecClient.disconnect();
91                  return;
92              }// else continue 
93          }
94          // Execution is done internally
95          String[] args = finalname.split(" ");
96          File exec = new File(args[0]);
97          if (exec.isAbsolute()) {
98              if (! exec.canExecute()) {
99                  logger.error("Exec command is not executable: " + finalname);
100                 R66Result result = new R66Result(session, false,
101                         ErrorCode.CommandNotFound, session.getRunner());
102                 futureCompletion.setResult(result);
103                 futureCompletion.cancel();
104                 return;
105             }
106         }
107         CommandLine commandLine = new CommandLine(args[0]);
108         for (int i = 1; i < args.length; i ++) {
109             commandLine.addArgument(args[i]);
110         }
111         DefaultExecutor defaultExecutor = new DefaultExecutor();
112         PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null);
113         defaultExecutor.setStreamHandler(pumpStreamHandler);
114         int[] correctValues = {
115                 0, 1 };
116         defaultExecutor.setExitValues(correctValues);
117         ExecuteWatchdog watchdog = null;
118         if (delay > 0 && waitForValidation) {
119             watchdog = new ExecuteWatchdog(delay);
120             defaultExecutor.setWatchdog(watchdog);
121         }
122         if (! waitForValidation) {
123             // Do not wait for validation
124             futureCompletion.setSuccess();
125             logger.info("Exec will start but no WAIT with {}", commandLine);
126         }
127         int status = -1;
128         try {
129             status = defaultExecutor.execute(commandLine);
130         } catch (ExecuteException e) {
131             if (e.getExitValue() == -559038737) {
132                 // Cannot run immediately so retry once
133                 try {
134                     Thread.sleep(Configuration.RETRYINMS);
135                 } catch (InterruptedException e1) {
136                 }
137                 try {
138                     status = defaultExecutor.execute(commandLine);
139                 } catch (ExecuteException e1) {
140                     pumpStreamHandler.stop();
141                     logger.error("Exception: " + e.getMessage() +
142                             " Exec in error with " + commandLine.toString());
143                     if (waitForValidation) {
144                         futureCompletion.setFailure(e);
145                     }
146                     return;
147                 } catch (IOException e1) {
148                     pumpStreamHandler.stop();
149                     logger.error("Exception: " + e.getMessage() +
150                             " Exec in error with " + commandLine.toString());
151                     if (waitForValidation) {
152                         futureCompletion.setFailure(e);
153                     }
154                     return;
155                 }
156             } else {
157                 pumpStreamHandler.stop();
158                 logger.error("Exception: " + e.getMessage() +
159                         " Exec in error with " + commandLine.toString());
160                 if (waitForValidation) {
161                     futureCompletion.setFailure(e);
162                 }
163                 return;
164             }
165         } catch (IOException e) {
166             pumpStreamHandler.stop();
167             logger.error("Exception: " + e.getMessage() +
168                     " Exec in error with " + commandLine.toString());
169             if (waitForValidation) {
170                 futureCompletion.setFailure(e);
171             }
172             return;
173         }
174         pumpStreamHandler.stop();
175         if (defaultExecutor.isFailure(status) && watchdog != null &&
176                 watchdog.killedProcess()) {
177             // kill by the watchdoc (time out)
178             logger.error("Exec is in Time Out");
179             status = -1;
180         }
181         if (status == 0) {
182             if (waitForValidation) {
183                 futureCompletion.setSuccess();
184             }
185             logger.info("Exec OK with {}", commandLine);
186         } else if (status == 1) {
187             logger.warn("Exec in warning with " + commandLine.toString());
188             if (waitForValidation) {
189                 futureCompletion.setSuccess();
190             }
191         } else {
192             logger.error("Status: " + status + " Exec in error with " +
193                     commandLine.toString());
194             if (waitForValidation) {
195                 futureCompletion.cancel();
196             }
197         }
198     }
199 
200 }