001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *      http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.oozie.action.ssh;
020
021import java.io.BufferedReader;
022import java.io.File;
023import java.io.FileWriter;
024import java.io.IOException;
025import java.io.InputStreamReader;
026import java.util.Arrays;
027import java.util.List;
028import java.util.concurrent.Callable;
029import com.google.common.base.Charsets;
030import org.apache.hadoop.util.StringUtils;
031
032import org.apache.oozie.client.WorkflowAction;
033import org.apache.oozie.client.OozieClient;
034import org.apache.oozie.client.WorkflowAction.Status;
035import org.apache.oozie.action.ActionExecutor;
036import org.apache.oozie.action.ActionExecutorException;
037import org.apache.oozie.service.CallbackService;
038import org.apache.oozie.service.ConfigurationService;
039import org.apache.oozie.servlet.CallbackServlet;
040import org.apache.oozie.service.Services;
041import org.apache.oozie.util.IOUtils;
042import org.apache.oozie.util.PropertiesUtils;
043import org.apache.oozie.util.XLog;
044import org.apache.oozie.util.XmlUtils;
045import org.jdom.Element;
046import org.jdom.JDOMException;
047import org.jdom.Namespace;
048
049/**
050 * Ssh action executor. <p> <ul> <li>Execute the shell commands on the remote host</li> <li>Copies the base and wrapper
051 * scripts on to the remote location</li> <li>Base script is used to run the command on the remote host</li> <li>Wrapper
052 * script is used to check the status of the submitted command</li> <li>handles the submission failures</li> </ul>
053 */
054public class SshActionExecutor extends ActionExecutor {
055    public static final String ACTION_TYPE = "ssh";
056
057    /**
058     * Configuration parameter which specifies whether the specified ssh user is allowed, or has to be the job user.
059     */
060    public static final String CONF_SSH_ALLOW_USER_AT_HOST = CONF_PREFIX + "ssh.allow.user.at.host";
061
062    protected static final String SSH_COMMAND_OPTIONS =
063            "-o PasswordAuthentication=no -o KbdInteractiveDevices=no -o StrictHostKeyChecking=no -o ConnectTimeout=20 ";
064
065    protected static final String SSH_COMMAND_BASE = "ssh " + SSH_COMMAND_OPTIONS;
066    protected static final String SCP_COMMAND_BASE = "scp " + SSH_COMMAND_OPTIONS;
067
068    public static final String ERR_SETUP_FAILED = "SETUP_FAILED";
069    public static final String ERR_EXECUTION_FAILED = "EXECUTION_FAILED";
070    public static final String ERR_UNKNOWN_ERROR = "UNKNOWN_ERROR";
071    public static final String ERR_COULD_NOT_CONNECT = "COULD_NOT_CONNECT";
072    public static final String ERR_HOST_RESOLUTION = "COULD_NOT_RESOLVE_HOST";
073    public static final String ERR_FNF = "FNF";
074    public static final String ERR_AUTH_FAILED = "AUTH_FAILED";
075    public static final String ERR_NO_EXEC_PERM = "NO_EXEC_PERM";
076    public static final String ERR_USER_MISMATCH = "ERR_USER_MISMATCH";
077    public static final String ERR_EXCEDE_LEN = "ERR_OUTPUT_EXCEED_MAX_LEN";
078
079    public static final String DELETE_TMP_DIR = "oozie.action.ssh.delete.remote.tmp.dir";
080
081    public static final String HTTP_COMMAND = "oozie.action.ssh.http.command";
082
083    public static final String HTTP_COMMAND_OPTIONS = "oozie.action.ssh.http.command.post.options";
084
085    private static final String EXT_STATUS_VAR = "#status";
086
087    private static int maxLen;
088    private static boolean allowSshUserAtHost;
089
090    private final XLog LOG = XLog.getLog(getClass())
091;
092    protected SshActionExecutor() {
093        super(ACTION_TYPE);
094    }
095
096    /**
097     * Initialize Action.
098     */
099    @Override
100    public void initActionType() {
101        super.initActionType();
102        maxLen = getOozieConf().getInt(CallbackServlet.CONF_MAX_DATA_LEN, 2 * 1024);
103        allowSshUserAtHost = ConfigurationService.getBoolean(CONF_SSH_ALLOW_USER_AT_HOST);
104        registerError(InterruptedException.class.getName(), ActionExecutorException.ErrorType.ERROR, "SH001");
105        registerError(JDOMException.class.getName(), ActionExecutorException.ErrorType.ERROR, "SH002");
106        initSshScripts();
107    }
108
109    /**
110     * Check ssh action status.
111     *
112     * @param context action execution context.
113     * @param action action object.
114     * @throws org.apache.oozie.action.ActionExecutorException
115     */
116    @Override
117    public void check(Context context, WorkflowAction action) throws ActionExecutorException {
118        LOG.trace("check() start for action={0}", action.getId());
119        Status status = getActionStatus(context, action);
120        boolean captureOutput = false;
121        try {
122            Element eConf = XmlUtils.parseXml(action.getConf());
123            Namespace ns = eConf.getNamespace();
124            captureOutput = eConf.getChild("capture-output", ns) != null;
125        }
126        catch (JDOMException ex) {
127            throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, "ERR_XML_PARSE_FAILED",
128                                              "unknown error", ex);
129        }
130        LOG.debug("Capture Output: {0}", captureOutput);
131        if (status == Status.OK) {
132            if (captureOutput) {
133                String outFile = getRemoteFileName(context, action, "stdout", false, true);
134                String dataCommand = SSH_COMMAND_BASE + action.getTrackerUri() + " cat " + outFile;
135                LOG.debug("Ssh command [{0}]", dataCommand);
136                try {
137                    final Process process = Runtime.getRuntime().exec(dataCommand.split("\\s"));
138
139                    final StringBuffer outBuffer = new StringBuffer();
140                    final StringBuffer errBuffer = new StringBuffer();
141                    boolean overflow = false;
142                    drainBuffers(process, outBuffer, errBuffer, maxLen);
143                    LOG.trace("outBuffer={0}", outBuffer);
144                    LOG.trace("errBuffer={0}", errBuffer);
145                    if (outBuffer.length() > maxLen) {
146                        overflow = true;
147                    }
148                    if (overflow) {
149                        throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR,
150                                                          "ERR_OUTPUT_EXCEED_MAX_LEN", "unknown error");
151                    }
152                    context.setExecutionData(status.toString(), PropertiesUtils.stringToProperties(outBuffer.toString()));
153                    LOG.trace("Execution data set. status={0}, properties={1}", status,
154                            PropertiesUtils.stringToProperties(outBuffer.toString()));
155                }
156                catch (Exception ex) {
157                    throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, "ERR_UNKNOWN_ERROR",
158                                                      "unknown error", ex);
159                }
160            }
161            else {
162                LOG.trace("Execution data set to null. status={0}", status);
163                context.setExecutionData(status.toString(), null);
164            }
165        }
166        else {
167            if (status == Status.ERROR) {
168                LOG.warn("Execution data set to null in ERROR");
169                context.setExecutionData(status.toString(), null);
170            }
171            else {
172                LOG.warn("Execution data not set");
173                context.setExternalStatus(status.toString());
174            }
175        }
176        LOG.trace("check() end for action={0}", action);
177    }
178
179    /**
180     * Kill ssh action.
181     *
182     * @param context action execution context.
183     * @param action object.
184     * @throws org.apache.oozie.action.ActionExecutorException
185     */
186    @Override
187    public void kill(Context context, WorkflowAction action) throws ActionExecutorException {
188        LOG.info("Killing action");
189        String command = "ssh " + action.getTrackerUri() + " kill  -KILL " + action.getExternalId();
190        int returnValue = getReturnValue(command);
191        if (returnValue != 0) {
192            throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, "FAILED_TO_KILL", XLog.format(
193                    "Unable to kill process {0} on {1}", action.getExternalId(), action.getTrackerUri()));
194        }
195        context.setEndData(WorkflowAction.Status.KILLED, "ERROR");
196    }
197
198    /**
199     * Start the ssh action execution.
200     *
201     * @param context action execution context.
202     * @param action action object.
203     * @throws org.apache.oozie.action.ActionExecutorException
204     */
205    @SuppressWarnings("unchecked")
206    @Override
207    public void start(final Context context, final WorkflowAction action) throws ActionExecutorException {
208        LOG.info("Starting action");
209        String confStr = action.getConf();
210        Element conf;
211        try {
212            conf = XmlUtils.parseXml(confStr);
213        }
214        catch (Exception ex) {
215            throw convertException(ex);
216        }
217        Namespace nameSpace = conf.getNamespace();
218        Element hostElement = conf.getChild("host", nameSpace);
219        String hostString = hostElement.getValue().trim();
220        hostString = prepareUserHost(hostString, context);
221        final String host = hostString;
222        final String dirLocation = execute(new Callable<String>() {
223            public String call() throws Exception {
224                return setupRemote(host, context, action);
225            }
226
227        });
228
229        String runningPid = execute(new Callable<String>() {
230            public String call() throws Exception {
231                return checkIfRunning(host, context, action);
232            }
233        });
234        String pid = "";
235
236        LOG.trace("runningPid={0}", runningPid);
237
238        if (runningPid == null) {
239            final Element commandElement = conf.getChild("command", nameSpace);
240            final boolean ignoreOutput = conf.getChild("capture-output", nameSpace) == null;
241
242            boolean preserve = false;
243            if (commandElement != null) {
244                String[] args = null;
245                // Will either have <args>, <arg>, or neither (but not both)
246                List<Element> argsList = conf.getChildren("args", nameSpace);
247                // Arguments in an <args> are "flattened" (spaces are delimiters)
248                if (argsList != null && argsList.size() > 0) {
249                    StringBuilder argsString = new StringBuilder("");
250                    for (Element argsElement : argsList) {
251                        argsString = argsString.append(argsElement.getValue()).append(" ");
252                    }
253                    args = new String[]{argsString.toString()};
254                }
255                else {
256                    // Arguments in an <arg> are preserved, even with spaces
257                    argsList = conf.getChildren("arg", nameSpace);
258                    if (argsList != null && argsList.size() > 0) {
259                        preserve = true;
260                        args = new String[argsList.size()];
261                        for (int i = 0; i < argsList.size(); i++) {
262                            Element argsElement = argsList.get(i);
263                            args[i] = argsElement.getValue();
264                            // Even though we're keeping the args as an array, if they contain a space we still have to either quote
265                            // them or escape their space (because the scripts will split them up otherwise)
266                            if (args[i].contains(" ") &&
267                                    !(args[i].startsWith("\"") && args[i].endsWith("\"") ||
268                                      args[i].startsWith("'") && args[i].endsWith("'"))) {
269                                args[i] = StringUtils.escapeString(args[i], '\\', ' ');
270                            }
271                        }
272                    }
273                }
274                final String[] argsF = args;
275                final String recoveryId = context.getRecoveryId();
276                final boolean preserveF = preserve;
277                pid = execute(new Callable<String>() {
278
279                    @Override
280                    public String call() throws Exception {
281                        return doExecute(host, dirLocation, commandElement.getValue(), argsF, ignoreOutput, action, recoveryId,
282                                preserveF);
283                    }
284
285                });
286            }
287            context.setStartData(pid, host, host);
288        }
289        else {
290            pid = runningPid;
291            context.setStartData(pid, host, host);
292            check(context, action);
293        }
294    }
295
296    private String checkIfRunning(String host, final Context context, final WorkflowAction action) {
297        String pid = null;
298        String outFile = getRemoteFileName(context, action, "pid", false, false);
299        String getOutputCmd = SSH_COMMAND_BASE + host + " cat " + outFile;
300        try {
301            Process process = Runtime.getRuntime().exec(getOutputCmd.split("\\s"));
302            StringBuffer buffer = new StringBuffer();
303            drainBuffers(process, buffer, null, maxLen);
304            pid = getFirstLine(buffer);
305
306            if (Long.valueOf(pid) > 0) {
307                return pid;
308            }
309            else {
310                return null;
311            }
312        }
313        catch (Exception e) {
314            return null;
315        }
316    }
317
318    /**
319     * Get remote host working location.
320     *
321     * @param context action execution context
322     * @param action Action
323     * @param fileExtension Extension to be added to file name
324     * @param dirOnly Get the Directory only
325     * @param useExtId Flag to use external ID in the path
326     * @return remote host file name/Directory.
327     */
328    public String getRemoteFileName(Context context, WorkflowAction action, String fileExtension, boolean dirOnly,
329                                    boolean useExtId) {
330        String path = getActionDirPath(context.getWorkflow().getId(), action, ACTION_TYPE, false) + "/";
331        if (dirOnly) {
332            return path;
333        }
334        if (useExtId) {
335            path = path + action.getExternalId() + ".";
336        }
337        path = path + context.getRecoveryId() + "." + fileExtension;
338        return path;
339    }
340
341    /**
342     * Utility method to execute command.
343     *
344     * @param command Command to execute as String.
345     * @return exit status of the execution.
346     * @throws IOException if processSettings exits with status nonzero.
347     * @throws InterruptedException if processSettings does not run properly.
348     */
349    public int executeCommand(String command) throws IOException, InterruptedException {
350        Runtime runtime = Runtime.getRuntime();
351        Process p = runtime.exec(command.split("\\s"));
352
353        StringBuffer errorBuffer = new StringBuffer();
354        int exitValue = drainBuffers(p, null, errorBuffer, maxLen);
355
356        String error = null;
357        if (exitValue != 0) {
358            error = getTruncatedString(errorBuffer);
359            throw new IOException(XLog.format("Not able to perform operation [{0}]", command) + " | " + "ErrorStream: "
360                    + error);
361        }
362        return exitValue;
363    }
364
365    /**
366     * Do ssh action execution setup on remote host.
367     *
368     * @param host host name.
369     * @param context action execution context.
370     * @param action action object.
371     * @return remote host working directory.
372     * @throws IOException thrown if failed to setup.
373     * @throws InterruptedException thrown if any interruption happens.
374     */
375    protected String setupRemote(String host, Context context, WorkflowAction action) throws IOException, InterruptedException {
376        LOG.info("Attempting to copy ssh base scripts to remote host [{0}]", host);
377        String localDirLocation = Services.get().getRuntimeDir() + "/ssh";
378        if (localDirLocation.endsWith("/")) {
379            localDirLocation = localDirLocation.substring(0, localDirLocation.length() - 1);
380        }
381        File file = new File(localDirLocation + "/ssh-base.sh");
382        if (!file.exists()) {
383            throw new IOException("Required Local file " + file.getAbsolutePath() + " not present.");
384        }
385        file = new File(localDirLocation + "/ssh-wrapper.sh");
386        if (!file.exists()) {
387            throw new IOException("Required Local file " + file.getAbsolutePath() + " not present.");
388        }
389        String remoteDirLocation = getRemoteFileName(context, action, null, true, true);
390        String command = XLog.format("{0}{1}  mkdir -p {2} ", SSH_COMMAND_BASE, host, remoteDirLocation).toString();
391        executeCommand(command);
392        command = XLog.format("{0}{1}/ssh-base.sh {2}/ssh-wrapper.sh {3}:{4}", SCP_COMMAND_BASE, localDirLocation,
393                              localDirLocation, host, remoteDirLocation);
394        executeCommand(command);
395        command = XLog.format("{0}{1}  chmod +x {2}ssh-base.sh {3}ssh-wrapper.sh ", SSH_COMMAND_BASE, host,
396                              remoteDirLocation, remoteDirLocation);
397        executeCommand(command);
398        return remoteDirLocation;
399    }
400
401    /**
402     * Execute the ssh command.
403     *
404     * @param host hostname.
405     * @param dirLocation location of the base and wrapper scripts.
406     * @param cmnd command to be executed.
407     * @param args command arguments.
408     * @param ignoreOutput ignore output option.
409     * @param action action object.
410     * @param recoveryId action id + run number to enable recovery in rerun
411     * @param preserveArgs tell the ssh scripts to preserve or flatten the arguments
412     * @return processSettings id of the running command.
413     * @throws IOException thrown if failed to run the command.
414     * @throws InterruptedException thrown if any interruption happens.
415     */
416    protected String doExecute(String host, String dirLocation, String cmnd, String[] args, boolean ignoreOutput,
417                               WorkflowAction action, String recoveryId, boolean preserveArgs)
418                               throws IOException, InterruptedException {
419        XLog log = XLog.getLog(getClass());
420        Runtime runtime = Runtime.getRuntime();
421        String callbackPost = ignoreOutput ? "_" : ConfigurationService.get(HTTP_COMMAND_OPTIONS).replace(" ", "%%%");
422        String preserveArgsS = preserveArgs ? "PRESERVE_ARGS" : "FLATTEN_ARGS";
423        // TODO check
424        String callBackUrl = Services.get().get(CallbackService.class)
425                .createCallBackUrl(action.getId(), EXT_STATUS_VAR);
426        String command = XLog.format("{0}{1} {2}ssh-base.sh {3} {4} \"{5}\" \"{6}\" {7} {8} ", SSH_COMMAND_BASE, host, dirLocation,
427                preserveArgsS, ConfigurationService.get(HTTP_COMMAND), callBackUrl, callbackPost, recoveryId, cmnd)
428                .toString();
429        String[] commandArray = command.split("\\s");
430        String[] finalCommand;
431        if (args == null) {
432            finalCommand = commandArray;
433        }
434        else {
435            finalCommand = new String[commandArray.length + args.length];
436            System.arraycopy(commandArray, 0, finalCommand, 0, commandArray.length);
437            System.arraycopy(args, 0, finalCommand, commandArray.length, args.length);
438        }
439
440        LOG.trace("Executing SSH command [finalCommand={0}]", Arrays.toString(finalCommand));
441        final Process p = runtime.exec(finalCommand);
442        final String pid;
443
444        final StringBuffer inputBuffer = new StringBuffer();
445        final StringBuffer errorBuffer = new StringBuffer();
446        final int exitValue = drainBuffers(p, inputBuffer, errorBuffer, maxLen);
447
448        pid = getFirstLine(inputBuffer);
449
450        String error = null;
451        if (exitValue != 0) {
452            error = getTruncatedString(errorBuffer);
453            throw new IOException(XLog.format("Not able to execute ssh-base.sh on {0}", host) + " | " + "ErrorStream: "
454                    + error);
455        }
456
457        LOG.trace("After execution pid={0}", pid);
458
459        return pid;
460    }
461
462    /**
463     * End action execution.
464     *
465     * @param context action execution context.
466     * @param action action object.
467     * @throws ActionExecutorException thrown if action end execution fails.
468     */
469    public void end(final Context context, final WorkflowAction action) throws ActionExecutorException {
470        if (action.getExternalStatus().equals("OK")) {
471            context.setEndData(WorkflowAction.Status.OK, WorkflowAction.Status.OK.toString());
472        }
473        else {
474            context.setEndData(WorkflowAction.Status.ERROR, WorkflowAction.Status.ERROR.toString());
475        }
476        boolean deleteTmpDir = ConfigurationService.getBoolean(DELETE_TMP_DIR);
477        if (deleteTmpDir) {
478            String tmpDir = getRemoteFileName(context, action, null, true, false);
479            String removeTmpDirCmd = SSH_COMMAND_BASE + action.getTrackerUri() + " rm -rf " + tmpDir;
480            int retVal = getReturnValue(removeTmpDirCmd);
481            if (retVal != 0) {
482                XLog.getLog(getClass()).warn("Cannot delete temp dir {0}", tmpDir);
483            }
484        }
485        LOG.info("Action ended with external status [{0}]", action.getExternalStatus());
486    }
487
488    /**
489     * Get the return value of a processSettings.
490     *
491     * @param command command to be executed.
492     * @return zero if execution is successful and any non zero value for failure.
493     * @throws ActionExecutorException
494     */
495    private int getReturnValue(String command) throws ActionExecutorException {
496        LOG.trace("Getting return value for command={0}", command);
497
498        int returnValue;
499        Process ps = null;
500        try {
501            ps = Runtime.getRuntime().exec(command.split("\\s"));
502            returnValue = drainBuffers(ps, null, null, 0);
503        }
504        catch (IOException e) {
505            throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, "FAILED_OPERATION", XLog.format(
506                    "Not able to perform operation {0}", command), e);
507        }
508        finally {
509            ps.destroy();
510        }
511
512        LOG.trace("returnValue={0}", returnValue);
513
514        return returnValue;
515    }
516
517    /**
518     * Copy the ssh base and wrapper scripts to the local directory.
519     */
520    private void initSshScripts() {
521        String dirLocation = Services.get().getRuntimeDir() + "/ssh";
522        File path = new File(dirLocation);
523        path.mkdirs();
524        if (!path.exists()) {
525            throw new RuntimeException(XLog.format("Not able to create required directory {0}", dirLocation));
526        }
527        try {
528            IOUtils.copyCharStream(IOUtils.getResourceAsReader("ssh-base.sh", -1), new FileWriter(dirLocation
529                    + "/ssh-base.sh"));
530            IOUtils.copyCharStream(IOUtils.getResourceAsReader("ssh-wrapper.sh", -1), new FileWriter(dirLocation
531                    + "/ssh-wrapper.sh"));
532        }
533        catch (IOException ie) {
534            throw new RuntimeException(XLog.format("Not able to copy required scripts file to {0} "
535                    + "for SshActionHandler", dirLocation));
536        }
537    }
538
539    /**
540     * Get action status.
541     *
542     * @param context
543     * @param action action object.
544     * @return status of the action(RUNNING/OK/ERROR).
545     * @throws ActionExecutorException thrown if there is any error in getting status.
546     */
547    protected Status getActionStatus(Context context, WorkflowAction action) throws ActionExecutorException {
548        String command = SSH_COMMAND_BASE + action.getTrackerUri() + " ps -p " + action.getExternalId();
549        Status aStatus;
550        int returnValue = getReturnValue(command);
551        if (returnValue == 0) {
552            aStatus = Status.RUNNING;
553        }
554        else {
555            String outFile = getRemoteFileName(context, action, "error", false, true);
556            String checkErrorCmd = SSH_COMMAND_BASE + action.getTrackerUri() + " ls " + outFile;
557            int retVal = getReturnValue(checkErrorCmd);
558            if (retVal == 0) {
559                aStatus = Status.ERROR;
560            }
561            else {
562                aStatus = Status.OK;
563            }
564        }
565        return aStatus;
566    }
567
568    /**
569     * Execute the callable.
570     *
571     * @param callable required callable.
572     * @throws ActionExecutorException thrown if there is any error in command execution.
573     */
574    private <T> T execute(Callable<T> callable) throws ActionExecutorException {
575        XLog log = XLog.getLog(getClass());
576        try {
577            return callable.call();
578        }
579        catch (IOException ex) {
580            log.warn("Error while executing ssh EXECUTION");
581            String errorMessage = ex.getMessage();
582            if (null == errorMessage) { // Unknown IOException
583                throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, ERR_UNKNOWN_ERROR, ex
584                        .getMessage(), ex);
585            } // Host Resolution Issues
586            else {
587                if (errorMessage.contains("Could not resolve hostname") ||
588                        errorMessage.contains("service not known")) {
589                    throw new ActionExecutorException(ActionExecutorException.ErrorType.TRANSIENT, ERR_HOST_RESOLUTION, ex
590                            .getMessage(), ex);
591                } // Connection Timeout. Host temporarily down.
592                else {
593                    if (errorMessage.contains("timed out")) {
594                        throw new ActionExecutorException(ActionExecutorException.ErrorType.TRANSIENT, ERR_COULD_NOT_CONNECT,
595                                                          ex.getMessage(), ex);
596                    }// Local ssh-base or ssh-wrapper missing
597                    else {
598                        if (errorMessage.contains("Required Local file")) {
599                            throw new ActionExecutorException(ActionExecutorException.ErrorType.TRANSIENT, ERR_FNF,
600                                                              ex.getMessage(), ex); // local_FNF
601                        }// Required oozie bash scripts missing, after the copy was
602                        // successful
603                        else {
604                            if (errorMessage.contains("No such file or directory")
605                                    && (errorMessage.contains("ssh-base") || errorMessage.contains("ssh-wrapper"))) {
606                                throw new ActionExecutorException(ActionExecutorException.ErrorType.TRANSIENT, ERR_FNF,
607                                                                  ex.getMessage(), ex); // remote
608                                // FNF
609                            } // Required application execution binary missing (either
610                            // caught by ssh-wrapper
611                            else {
612                                if (errorMessage.contains("command not found")) {
613                                    throw new ActionExecutorException(ActionExecutorException.ErrorType.NON_TRANSIENT, ERR_FNF, ex
614                                            .getMessage(), ex); // remote
615                                    // FNF
616                                } // Permission denied while connecting
617                                else {
618                                    if (errorMessage.contains("Permission denied")) {
619                                        throw new ActionExecutorException(ActionExecutorException.ErrorType.NON_TRANSIENT,
620                                                ERR_AUTH_FAILED, ex.getMessage(), ex);
621                                    } // Permission denied while executing
622                                    else {
623                                        if (errorMessage.contains(": Permission denied")) {
624                                            throw new ActionExecutorException(ActionExecutorException.ErrorType.NON_TRANSIENT,
625                                                    ERR_NO_EXEC_PERM, ex.getMessage(), ex);
626                                        }
627                                        else {
628                                            throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR,
629                                                    ERR_UNKNOWN_ERROR, ex.getMessage(), ex);
630                                        }
631                                    }
632                                }
633                            }
634                        }
635                    }
636                }
637            }
638        } // Any other type of exception
639        catch (Exception ex) {
640            throw convertException(ex);
641        }
642    }
643
644    /**
645     * Checks whether the system is configured to always use the oozie user for ssh, and injects the user if required.
646     *
647     * @param host the host string.
648     * @param context the execution context.
649     * @return the modified host string with a user parameter added on if required.
650     * @throws ActionExecutorException in case the flag to use the oozie user is turned on and there is a mismatch
651     * between the user specified in the host and the oozie user.
652     */
653    private String prepareUserHost(String host, Context context) throws ActionExecutorException {
654        String oozieUser = context.getProtoActionConf().get(OozieClient.USER_NAME);
655        if (allowSshUserAtHost) {
656            if (!host.contains("@")) {
657                host = oozieUser + "@" + host;
658            }
659        }
660        else {
661            if (host.contains("@")) {
662                if (!host.toLowerCase().startsWith(oozieUser + "@")) {
663                    throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, ERR_USER_MISMATCH,
664                                                      XLog.format("user mismatch between oozie user [{0}] and ssh host [{1}]",
665                                                              oozieUser, host));
666                }
667            }
668            else {
669                host = oozieUser + "@" + host;
670            }
671        }
672
673        LOG.trace("User host is {0}", host);
674
675        return host;
676    }
677
678    @Override
679    public boolean isCompleted(String externalStatus) {
680        return true;
681    }
682
683    /**
684     * Truncate the string to max length.
685     *
686     * @param strBuffer
687     * @return truncated string string
688     */
689    private String getTruncatedString(StringBuffer strBuffer) {
690
691        if (strBuffer.length() <= maxLen) {
692            return strBuffer.toString();
693        }
694        else {
695            return strBuffer.substring(0, maxLen);
696        }
697    }
698
699    /**
700     * Drains the inputStream and errorStream of the Process being executed. The contents of the streams are stored if a
701     * buffer is provided for the stream.
702     *
703     * @param p The Process instance.
704     * @param inputBuffer The buffer into which STDOUT is to be read. Can be null if only draining is required.
705     * @param errorBuffer The buffer into which STDERR is to be read. Can be null if only draining is required.
706     * @param maxLength The maximum data length to be stored in these buffers. This is an indicative value, and the
707     * store content may exceed this length.
708     * @return the exit value of the processSettings.
709     * @throws IOException
710     */
711    private int drainBuffers(final Process p, final StringBuffer inputBuffer, final StringBuffer errorBuffer, final int maxLength)
712            throws IOException {
713        LOG.trace("drainBuffers() start");
714
715        int exitValue = -1;
716
717        int inBytesRead = 0;
718        int errBytesRead = 0;
719
720        boolean processEnded = false;
721
722        try (final BufferedReader ir = new BufferedReader(new InputStreamReader(p.getInputStream(), Charsets.UTF_8));
723             final BufferedReader er = new BufferedReader(new InputStreamReader(p.getErrorStream(), Charsets.UTF_8))) {
724            // Here we do some kind of busy waiting, checking whether the process has finished by calling Process#exitValue().
725            // If not yet finished, an IllegalThreadStateException is thrown and ignored, the progress on stdout and stderr read,
726            // and retried until the process has ended.
727            // Note that Process#waitFor() may block sometimes, that's why we do a polling mechanism using Process#exitValue()
728            // instead. Until we extend unit and integration test coverage for SSH action, and we can introduce a more sophisticated
729            // error handling based on the extended coverage, this solution should stay in place.
730            while (!processEnded) {
731                try {
732                    // Doesn't block but throws IllegalThreadStateException if the process hasn't finished yet
733                    exitValue = p.exitValue();
734                    processEnded = true;
735                }
736                catch (final IllegalThreadStateException itse) {
737                    // Continue to drain
738                }
739
740                // Drain input and error streams
741                inBytesRead += drainBuffer(ir, inputBuffer, maxLength, inBytesRead, processEnded);
742                errBytesRead += drainBuffer(er, errorBuffer, maxLength, errBytesRead, processEnded);
743
744                // Necessary evil: sleep and retry
745                if (!processEnded) {
746                    try {
747                        Thread.sleep(500);
748                    }
749                    catch (final InterruptedException ie) {
750                        // Sleep a little, then check again
751                    }
752                }
753            }
754        }
755
756        LOG.trace("drainBuffers() end [exitValue={0}]", exitValue);
757
758        return exitValue;
759    }
760
761    /**
762     * Reads the contents of a stream and stores them into the provided buffer.
763     *
764     * @param br The stream to be read.
765     * @param storageBuf The buffer into which the contents of the stream are to be stored.
766     * @param maxLength The maximum number of bytes to be stored in the buffer. An indicative value and may be
767     * exceeded.
768     * @param bytesRead The number of bytes read from this stream to date.
769     * @param readAll If true, the stream is drained while their is data available in it. Otherwise, only a single chunk
770     * of data is read, irrespective of how much is available.
771     * @return bReadSession returns drainBuffer for stream of contents
772     * @throws IOException
773     */
774    private int drainBuffer(BufferedReader br, StringBuffer storageBuf, int maxLength, int bytesRead, boolean readAll)
775            throws IOException {
776        int bReadSession = 0;
777        if (br.ready()) {
778            char[] buf = new char[1024];
779            do {
780                int bReadCurrent = br.read(buf, 0, 1024);
781                if (storageBuf != null && bytesRead < maxLength) {
782                    storageBuf.append(buf, 0, bReadCurrent);
783                }
784                bReadSession += bReadCurrent;
785            } while (br.ready() && readAll);
786        }
787        return bReadSession;
788    }
789
790    /**
791     * Returns the first line from a StringBuffer, recognized by the new line character \n.
792     *
793     * @param buffer The StringBuffer from which the first line is required.
794     * @return The first line of the buffer.
795     */
796    private String getFirstLine(StringBuffer buffer) {
797        int newLineIndex = 0;
798        newLineIndex = buffer.indexOf("\n");
799        if (newLineIndex == -1) {
800            return buffer.toString();
801        }
802        else {
803            return buffer.substring(0, newLineIndex);
804        }
805    }
806}