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.hadoop;
020
021import java.io.IOException;
022import java.io.StringReader;
023import java.net.URISyntaxException;
024import java.security.NoSuchAlgorithmException;
025import java.util.ArrayList;
026import java.util.Comparator;
027import java.util.List;
028import java.util.Map;
029import java.util.function.Predicate;
030
031import com.google.common.base.Charsets;
032import com.google.common.annotations.VisibleForTesting;
033import com.google.common.base.Function;
034import com.google.common.base.Preconditions;
035import com.google.common.base.Strings;
036import com.google.common.collect.Iterables;
037import com.google.common.collect.Ordering;
038import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
039import org.apache.hadoop.conf.Configuration;
040import org.apache.hadoop.fs.FileSystem;
041import org.apache.hadoop.fs.Path;
042import org.apache.hadoop.mapred.Counters;
043import org.apache.hadoop.mapred.JobClient;
044import org.apache.hadoop.mapred.JobConf;
045import org.apache.hadoop.mapred.JobID;
046import org.apache.hadoop.mapred.RunningJob;
047import org.apache.hadoop.mapreduce.TypeConverter;
048import org.apache.hadoop.yarn.api.protocolrecords.ApplicationsRequestScope;
049import org.apache.hadoop.yarn.api.records.ApplicationReport;
050import org.apache.oozie.WorkflowActionBean;
051import org.apache.oozie.action.ActionExecutorException;
052import org.apache.oozie.client.WorkflowAction;
053import org.apache.oozie.service.ConfigurationService;
054import org.apache.oozie.service.HadoopAccessorException;
055import org.apache.oozie.util.XConfiguration;
056import org.apache.oozie.util.XLog;
057import org.apache.oozie.util.XmlUtils;
058import org.jdom.Element;
059import org.jdom.JDOMException;
060import org.jdom.Namespace;
061
062import static org.apache.oozie.action.hadoop.LauncherMain.CHILD_MAPREDUCE_JOB_TAGS;
063
064public class MapReduceActionExecutor extends JavaActionExecutor {
065
066    public static final String OOZIE_ACTION_EXTERNAL_STATS_WRITE = "oozie.action.external.stats.write";
067    public static final String HADOOP_COUNTERS = "hadoop.counters";
068    public static final String OOZIE_MAPREDUCE_UBER_JAR_ENABLE = "oozie.action.mapreduce.uber.jar.enable";
069    private static final String STREAMING_MAIN_CLASS_NAME = "org.apache.oozie.action.hadoop.StreamingMain";
070    public static final String JOB_END_NOTIFICATION_URL = "job.end.notification.url";
071    private static final String MAPREDUCE_JOB_NAME = "mapreduce.job.name";
072    static final String YARN_APPLICATION_TYPE_MAPREDUCE = "MAPREDUCE";
073    private XLog log = XLog.getLog(getClass());
074
075    public MapReduceActionExecutor() {
076        super("map-reduce");
077    }
078
079    @Override
080    public List<Class<?>> getLauncherClasses() {
081        List<Class<?>> classes = new ArrayList<>();
082        try {
083            classes.add(Class.forName(STREAMING_MAIN_CLASS_NAME));
084        }
085        catch (ClassNotFoundException e) {
086            throw new RuntimeException("Class not found", e);
087        }
088        return classes;
089    }
090
091    @Override
092    protected String getActualExternalId(WorkflowAction action) {
093        String launcherJobId = action.getExternalId();
094        String childId = action.getExternalChildIDs();
095
096        if (childId != null && !childId.isEmpty()) {
097            return childId;
098        } else {
099            return launcherJobId;
100        }
101    }
102
103    @Override
104    protected String getLauncherMain(Configuration launcherConf, Element actionXml) {
105        String mainClass;
106        Namespace ns = actionXml.getNamespace();
107        if (actionXml.getChild("streaming", ns) != null) {
108            mainClass = launcherConf.get(LauncherAMUtils.CONF_OOZIE_ACTION_MAIN_CLASS, STREAMING_MAIN_CLASS_NAME);
109        }
110        else {
111            if (actionXml.getChild("pipes", ns) != null) {
112                mainClass = launcherConf.get(LauncherAMUtils.CONF_OOZIE_ACTION_MAIN_CLASS, PipesMain.class.getName());
113            }
114            else {
115                mainClass = launcherConf.get(LauncherAMUtils.CONF_OOZIE_ACTION_MAIN_CLASS, MapReduceMain.class.getName());
116            }
117        }
118        return mainClass;
119    }
120
121    @Override
122    Configuration setupLauncherConf(Configuration conf, Element actionXml, Path appPath, Context context)
123            throws ActionExecutorException {
124        super.setupLauncherConf(conf, actionXml, appPath, context);
125        conf.setBoolean("mapreduce.job.complete.cancel.delegation.tokens", false);
126
127        return conf;
128    }
129
130    private void injectConfigClass(Configuration conf, Element actionXml) {
131        // Inject config-class for launcher to use for action
132        Element e = actionXml.getChild("config-class", actionXml.getNamespace());
133        if (e != null) {
134            conf.set(LauncherAMUtils.OOZIE_ACTION_CONFIG_CLASS, e.getTextTrim());
135        }
136    }
137
138    @Override
139    protected Configuration createBaseHadoopConf(Context context, Element actionXml, boolean loadResources) {
140        return super.createBaseHadoopConf(context, actionXml, loadResources);
141    }
142
143    @Override
144    @SuppressWarnings("unchecked")
145    Configuration setupActionConf(Configuration actionConf, Context context, Element actionXml, Path appPath)
146            throws ActionExecutorException {
147        boolean regularMR = false;
148
149        injectConfigClass(actionConf, actionXml);
150        Namespace ns = actionXml.getNamespace();
151        if (actionXml.getChild("streaming", ns) != null) {
152            Element streamingXml = actionXml.getChild("streaming", ns);
153            String mapper = streamingXml.getChildTextTrim("mapper", ns);
154            String reducer = streamingXml.getChildTextTrim("reducer", ns);
155            String recordReader = streamingXml.getChildTextTrim("record-reader", ns);
156            List<Element> list = (List<Element>) streamingXml.getChildren("record-reader-mapping", ns);
157            String[] recordReaderMapping = new String[list.size()];
158            for (int i = 0; i < list.size(); i++) {
159                recordReaderMapping[i] = list.get(i).getTextTrim();
160            }
161            list = (List<Element>) streamingXml.getChildren("env", ns);
162            String[] env = new String[list.size()];
163            for (int i = 0; i < list.size(); i++) {
164                env[i] = list.get(i).getTextTrim();
165            }
166            setStreaming(actionConf, mapper, reducer, recordReader, recordReaderMapping, env);
167        }
168        else {
169            if (actionXml.getChild("pipes", ns) != null) {
170                Element pipesXml = actionXml.getChild("pipes", ns);
171                String map = pipesXml.getChildTextTrim("map", ns);
172                String reduce = pipesXml.getChildTextTrim("reduce", ns);
173                String inputFormat = pipesXml.getChildTextTrim("inputformat", ns);
174                String partitioner = pipesXml.getChildTextTrim("partitioner", ns);
175                String writer = pipesXml.getChildTextTrim("writer", ns);
176                String program = pipesXml.getChildTextTrim("program", ns);
177                PipesMain.setPipes(actionConf, map, reduce, inputFormat, partitioner, writer, program, appPath);
178            }
179            else {
180                regularMR = true;
181            }
182        }
183        actionConf = super.setupActionConf(actionConf, context, actionXml, appPath);
184        setJobName(actionConf, context);
185
186        // For "regular" (not streaming or pipes) MR jobs
187        if (regularMR) {
188            // Resolve uber jar path (has to be done after super because oozie.mapreduce.uber.jar is under <configuration>)
189            String uberJar = actionConf.get(MapReduceMain.OOZIE_MAPREDUCE_UBER_JAR);
190            if (uberJar != null) {
191                if (!ConfigurationService.getBoolean(OOZIE_MAPREDUCE_UBER_JAR_ENABLE)){
192                    throw new ActionExecutorException(ActionExecutorException.ErrorType.ERROR, "MR003",
193                            "{0} property is not allowed.  Set {1} to true in oozie-site to enable.",
194                            MapReduceMain.OOZIE_MAPREDUCE_UBER_JAR, OOZIE_MAPREDUCE_UBER_JAR_ENABLE);
195                }
196                String nameNode = actionXml.getChildTextTrim("name-node", ns);
197                if (nameNode != null) {
198                    Path uberJarPath = new Path(uberJar);
199                    if (uberJarPath.toUri().getScheme() == null || uberJarPath.toUri().getAuthority() == null) {
200                        if (uberJarPath.isAbsolute()) {     // absolute path without namenode --> prepend namenode
201                            Path nameNodePath = new Path(nameNode);
202                            String nameNodeSchemeAuthority = nameNodePath.toUri().getScheme()
203                                    + "://" + nameNodePath.toUri().getAuthority();
204                            actionConf.set(MapReduceMain.OOZIE_MAPREDUCE_UBER_JAR,
205                                    new Path(nameNodeSchemeAuthority + uberJarPath).toString());
206                        }
207                        else {                              // relative path --> prepend app path
208                            actionConf.set(MapReduceMain.OOZIE_MAPREDUCE_UBER_JAR, new Path(appPath, uberJarPath).toString());
209                        }
210                    }
211                }
212            }
213        }
214        else {
215            if (actionConf.get(MapReduceMain.OOZIE_MAPREDUCE_UBER_JAR) != null) {
216                log.warn("The " + MapReduceMain.OOZIE_MAPREDUCE_UBER_JAR + " property is only applicable for MapReduce (not"
217                        + "streaming nor pipes) workflows, ignoring");
218                actionConf.set(MapReduceMain.OOZIE_MAPREDUCE_UBER_JAR, "");
219            }
220        }
221
222        // child job cancel delegation token for mapred action
223        actionConf.setBoolean("mapreduce.job.complete.cancel.delegation.tokens", true);
224
225        return actionConf;
226    }
227
228    private void setJobName(Configuration actionConf, Context context) {
229        String jobName = getAppName(context);
230        if (jobName != null) {
231            actionConf.set(MAPREDUCE_JOB_NAME, jobName.replace("oozie:launcher", "oozie:action"));
232        }
233    }
234
235    @Override
236    public void end(Context context, WorkflowAction action) throws ActionExecutorException {
237        super.end(context, action);
238        JobClient jobClient = null;
239        boolean exception = false;
240        try {
241            if (action.getStatus() == WorkflowAction.Status.OK) {
242                Element actionXml = XmlUtils.parseXml(action.getConf());
243                Configuration jobConf = createBaseHadoopConf(context, actionXml);
244                jobClient = createJobClient(context, jobConf);
245                RunningJob runningJob = jobClient.getJob(JobID.forName(action.getExternalChildIDs()));
246                if (runningJob == null) {
247                    throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "MR002",
248                            "Unknown hadoop job [{0}] associated with action [{1}].  Failing this action!",
249                            action.getExternalChildIDs(), action.getId());
250                }
251
252                Counters counters = runningJob.getCounters();
253                if (counters != null) {
254                    ActionStats stats = new MRStats(counters);
255                    String statsJsonString = stats.toJSON();
256                    context.setVar(HADOOP_COUNTERS, statsJsonString);
257
258                    // If action stats write property is set to false by user or
259                    // size of stats is greater than the maximum allowed size,
260                    // do not store the action stats
261                    if (Boolean.parseBoolean(evaluateConfigurationProperty(actionXml,
262                            OOZIE_ACTION_EXTERNAL_STATS_WRITE, "false"))
263                            && (statsJsonString.getBytes(Charsets.UTF_8).length <= getMaxExternalStatsSize())) {
264                        context.setExecutionStats(statsJsonString);
265                        log.debug(
266                                "Printing stats for Map-Reduce action as a JSON string : [{0}]", statsJsonString);
267                    }
268                }
269                else {
270                    context.setVar(HADOOP_COUNTERS, "");
271                    XLog.getLog(getClass()).warn("Could not find Hadoop Counters for: [{0}]",
272                            action.getExternalChildIDs());
273                }
274            }
275        }
276        catch (Exception ex) {
277            exception = true;
278            throw convertException(ex);
279        }
280        finally {
281            if (jobClient != null) {
282                try {
283                    jobClient.close();
284                }
285                catch (Exception e) {
286                    if (exception) {
287                        log.error("JobClient error: ", e);
288                    }
289                    else {
290                        throw convertException(e);
291                    }
292                }
293            }
294        }
295    }
296
297    // Return the value of the specified configuration property
298    private String evaluateConfigurationProperty(Element actionConf, String key, String defaultValue)
299            throws ActionExecutorException {
300        try {
301            String ret = defaultValue;
302            if (actionConf != null) {
303                Namespace ns = actionConf.getNamespace();
304                Element e = actionConf.getChild("configuration", ns);
305                if(e != null) {
306                    String strConf = XmlUtils.prettyPrint(e).toString();
307                    XConfiguration inlineConf = new XConfiguration(new StringReader(strConf));
308                    ret = inlineConf.get(key, defaultValue);
309                }
310            }
311            return ret;
312        }
313        catch (IOException ex) {
314            throw convertException(ex);
315        }
316    }
317
318    /**
319     * Return the sharelib name for the action.
320     *
321     * @return returns <code>streaming</code> if mapreduce-streaming action, <code>NULL</code> otherwise.
322     * @param actionXml
323     */
324    @Override
325    protected String getDefaultShareLibName(Element actionXml) {
326        Namespace ns = actionXml.getNamespace();
327        return (actionXml.getChild("streaming", ns) != null) ? "mapreduce-streaming" : null;
328    }
329
330    public static void setStreaming(Configuration conf, String mapper, String reducer, String recordReader,
331                                    String[] recordReaderMapping, String[] env) {
332        if (mapper != null) {
333            conf.set("oozie.streaming.mapper", mapper);
334        }
335        if (reducer != null) {
336            conf.set("oozie.streaming.reducer", reducer);
337        }
338        if (recordReader != null) {
339            conf.set("oozie.streaming.record-reader", recordReader);
340        }
341        ActionUtils.setStrings(conf, "oozie.streaming.record-reader-mapping", recordReaderMapping);
342        ActionUtils.setStrings(conf, "oozie.streaming.env", env);
343    }
344
345    @Override
346    protected void injectCallback(Context context, Configuration conf) {
347        // add callback for the MapReduce job
348        String callback = context.getCallbackUrl("$jobStatus");
349        String originalCallbackURL = conf.get(JOB_END_NOTIFICATION_URL);
350        if (originalCallbackURL != null) {
351            LOG.warn("Overriding the action job end notification URI. Original value: {0}", originalCallbackURL);
352        }
353        conf.set(JOB_END_NOTIFICATION_URL, callback);
354
355        super.injectCallback(context, conf);
356    }
357
358    @Override
359    public void check(Context context, WorkflowAction action) throws ActionExecutorException {
360        Map<String, String> actionData;
361        Configuration jobConf;
362
363        // Need to emit jobConf and actionData for later usage
364        try {
365            final FileSystem actionFs = context.getAppFileSystem();
366            final Element actionXml = XmlUtils.parseXml(action.getConf());
367            jobConf = createBaseHadoopConf(context, actionXml);
368            final Path actionDir = context.getActionDir();
369            actionData = LauncherHelper.getActionData(actionFs, actionDir, jobConf);
370        } catch (final Exception e) {
371            LOG.warn("Exception in check(). Message[{0}]", e.getMessage(), e);
372            throw convertException(e);
373        }
374
375        final String newJobId = findNewHadoopJobId(context, action);
376
377        // check the Hadoop job if newID is defined (which should be the case here) - otherwise perform the normal check()
378        if (newJobId != null) {
379            boolean jobCompleted;
380            JobClient jobClient = null;
381            boolean exception = false;
382
383            try {
384                jobClient = createJobClient(context, new JobConf(jobConf));
385                final JobID jobid = JobID.forName(newJobId);
386                final RunningJob runningJob = jobClient.getJob(jobid);
387
388                if (runningJob == null) {
389                    context.setExternalStatus(FAILED);
390                    throw new ActionExecutorException(ActionExecutorException.ErrorType.FAILED, "JA017",
391                            "Unknown hadoop job [{0}] associated with action [{1}].  Failing this action!", newJobId,
392                            action.getId());
393                }
394
395                jobCompleted = runningJob.isComplete();
396            } catch (Exception e) {
397                LOG.warn("Unable to check the state of a running MapReduce job -"
398                        + " please check the health of the Job History Server!", e);
399                exception = true;
400                throw convertException(e);
401            } finally {
402                if (jobClient != null) {
403                    try {
404                        jobClient.close();
405                    } catch (Exception e) {
406                        if (exception) {
407                            LOG.error("JobClient error (not re-throwing due to a previous error): ", e);
408                        } else {
409                            throw convertException(e);
410                        }
411                    }
412                }
413            }
414
415            // run original check() if the MR action is completed or there are errors - otherwise mark it as RUNNING
416            if (jobCompleted || actionData.containsKey(LauncherAMUtils.ACTION_DATA_ERROR_PROPS)) {
417                super.check(context, action);
418            } else {
419                context.setExternalStatus(RUNNING);
420                final String externalAppId = TypeConverter.toYarn(JobID.forName(newJobId)).getAppId().toString();
421                context.setExternalChildIDs(externalAppId);
422            }
423        } else {
424            super.check(context, action);
425        }
426    }
427
428    @Override
429    void injectActionCallback(Context context, Configuration actionConf) {
430        injectCallback(context, actionConf);
431    }
432
433    private String findNewHadoopJobId(final Context context, final WorkflowAction action) throws ActionExecutorException {
434        try {
435            final Configuration jobConf = createJobConfFromActionConf(context, action);
436
437            return new HadoopJobIdFinder(jobConf, context).find();
438        } catch (final HadoopAccessorException | IOException | JDOMException | URISyntaxException | InterruptedException |
439                NoSuchAlgorithmException e) {
440            LOG.warn("Exception while trying to find new Hadoop job id(). Message[{0}]", e.getMessage(), e);
441            throw convertException(e);
442        }
443    }
444
445    private Configuration createJobConfFromActionConf(final Context context, final WorkflowAction action)
446            throws JDOMException, NoSuchAlgorithmException {
447        final Element actionXml = XmlUtils.parseXml(action.getConf());
448        final Configuration jobConf = createBaseHadoopConf(context, actionXml);
449
450        final String launcherTag = getActionYarnTag(context, action);
451        jobConf.set(CHILD_MAPREDUCE_JOB_TAGS, LauncherHelper.getTag(launcherTag));
452
453        return jobConf;
454    }
455
456    /**
457     * Find YARN application ID only for {@link MapReduceActionExecutor} delegating to {@link YarnApplicationIdFinder}.
458     * @param context the execution context
459     * @param action the workflow action
460     * @return the YARN application ID as a {@code String}
461     * @throws ActionExecutorException when the YARN application ID could not be found
462     */
463    @Override
464    protected String findYarnApplicationId(final Context context, final WorkflowAction action) throws ActionExecutorException {
465        try {
466            final Configuration jobConf = createJobConfFromActionConf(context, action);
467            final HadoopJobIdFinder hadoopJobIdFinder = new HadoopJobIdFinder(jobConf, context);
468
469            return new YarnApplicationIdFinder(hadoopJobIdFinder,
470                    new YarnApplicationReportReader(jobConf), (WorkflowActionBean) action).find();
471        }
472        catch (final  IOException | HadoopAccessorException | JDOMException | InterruptedException | URISyntaxException |
473                NoSuchAlgorithmException e) {
474            LOG.warn("Exception while finding YARN application id. Message[{0}]", e.getMessage(), e);
475            throw convertException(e);
476        }
477    }
478
479    /**
480     * Finds a Hadoop job ID based on {@code action-data.seq} file stored on HDFS by {@link MapReduceMain}.
481     */
482    @VisibleForTesting
483    static class HadoopJobIdFinder {
484        private final Configuration jobConf;
485        private final Context executorContext;
486
487        HadoopJobIdFinder(final Configuration jobConf, final Context executorContext) {
488            this.jobConf = jobConf;
489            this.executorContext = executorContext;
490        }
491
492        String find() throws HadoopAccessorException, IOException, URISyntaxException, InterruptedException {
493            final FileSystem actionFs = executorContext.getAppFileSystem();
494            final Path actionDir = executorContext.getActionDir();
495            final Map<String, String> actionData = LauncherHelper.getActionData(actionFs, actionDir, jobConf);
496
497            return actionData.get(LauncherAMUtils.ACTION_DATA_NEW_ID);
498        }
499    }
500
501    /**
502     * Find YARN application ID in three stages:
503     * <ul>
504     *     <li>based on {@code action-data.seq} written by {@link MapReduceMain}, if already present. If present and is not the
505     *     Oozie Launcher's application ID ({@link WorkflowAction#getExternalId()}), gets used. Else, fall back to following:</li>
506     *     <li>if not found, look up the appropriate YARN child ID</li>
507     *     <li>if an appropriate YARN application ID is not found, go with Oozie Launcher's application ID
508     *     ({@link WorkflowAction#getExternalId()})</li>
509     * </ul>
510     */
511    @VisibleForTesting
512    static class YarnApplicationIdFinder {
513        private static final XLog LOG = XLog.getLog(YarnApplicationIdFinder.class);
514
515        private final HadoopJobIdFinder hadoopJobIdFinder;
516        private final YarnApplicationReportReader reader;
517        private final WorkflowActionBean workflowActionBean;
518
519        YarnApplicationIdFinder(final HadoopJobIdFinder hadoopJobIdFinder,
520                                final YarnApplicationReportReader reader,
521                                final WorkflowActionBean workflowActionBean) {
522            this.hadoopJobIdFinder = hadoopJobIdFinder;
523            this.reader = reader;
524            this.workflowActionBean = workflowActionBean;
525        }
526
527        String find() throws IOException, HadoopAccessorException, URISyntaxException, InterruptedException {
528            final String newJobId = hadoopJobIdFinder.find();
529            if (Strings.isNullOrEmpty(newJobId) && !isHadoopJobId(newJobId)) {
530                LOG.trace("Is not a Hadoop Job Id, falling back.");
531                return fallbackToYarnChildOrExternalId();
532            }
533
534            final String effectiveApplicationId;
535            final String newApplicationId = TypeConverter.toYarn(JobID.forName(newJobId)).getAppId().toString();
536
537            if (workflowActionBean.getExternalId().equals(newApplicationId) || newApplicationId == null) {
538                LOG.trace("New YARN application ID {0} is empty or is the same as {1}, falling back.",
539                        newApplicationId, workflowActionBean.getExternalId());
540                effectiveApplicationId = fallbackToYarnChildOrExternalId();
541            }
542            else {
543                LOG.trace("New YARN application ID {0} is different, using it.", newApplicationId);
544                effectiveApplicationId = newApplicationId;
545            }
546
547            return effectiveApplicationId;
548        }
549
550        /**
551         * When a Hadoop could not be found, fall back finding the YARN child application ID, or the workflow's {@code externalId}:
552         * <ul>
553         *     <li>look for YARN children of the actual {@code WorkflowActionBean}</li>
554         *     <li>filter for type {@code MAPREDUCE}. Note that those will be the YARN application children of the original
555         *     {@code Oozie Launcher} type. Filter also for the ones not in YARN applications' terminal states. What remains is the
556         *     one we call YARN child ID</li>
557         *     <li>if not found, go with {@link WorkflowActionBean#externalId}</li>
558         *     <li>if the found one is not newer than the one already stored, go with {@link WorkflowActionBean#externalId}</li>
559         *     <li>if found and there is no {@link WorkflowActionBean#externalId}, go with the YARN child ID</li>
560         *     <li>else, go with the YARN child ID</li>
561         * </ul>
562         * @return the YARN child application's ID, or the workflow action's external ID
563         */
564        private String fallbackToYarnChildOrExternalId() {
565            final List<ApplicationReport> childYarnApplications = reader.read();
566            childYarnApplications.removeIf(new Predicate<ApplicationReport>() {
567                @Override
568                public boolean test(ApplicationReport applicationReport) {
569                    return !applicationReport.getApplicationType().equals(YARN_APPLICATION_TYPE_MAPREDUCE);
570                }
571            });
572
573            if (childYarnApplications.isEmpty()) {
574                LOG.trace("No child YARN applications present, returning {0} instead", workflowActionBean.getExternalId());
575                return workflowActionBean.getExternalId();
576            }
577
578            final String yarnChildId = getLastYarnId(childYarnApplications);
579
580            if (Strings.isNullOrEmpty(yarnChildId)) {
581                LOG.trace("yarnChildId is empty, returning {0} instead", workflowActionBean.getExternalId());
582                return workflowActionBean.getExternalId();
583            }
584
585            if (Strings.isNullOrEmpty(workflowActionBean.getExternalId())) {
586                LOG.trace("workflowActionBean.externalId is empty, returning {0} instead", yarnChildId);
587                return yarnChildId;
588            }
589
590            if (new YarnApplicationIdComparator().compare(yarnChildId, workflowActionBean.getExternalId()) > 0) {
591                LOG.trace("yarnChildId is newer, returning {0}", yarnChildId);
592                return yarnChildId;
593            }
594
595            LOG.trace("yarnChildId is not newer, returning {0}", workflowActionBean.getExternalId());
596            return workflowActionBean.getExternalId();
597        }
598
599        /**
600         * Get the biggest YARN application ID given {@link YarnApplicationIdComparator}.
601         * @param yarnApplications the YARN application reports
602         * @return the biggest {@link ApplicationReport#getApplicationId()#toString()}
603         */
604        @VisibleForTesting
605        protected String getLastYarnId(final List<ApplicationReport> yarnApplications) {
606            Preconditions.checkNotNull(yarnApplications, "YARN application list should be filled");
607            Preconditions.checkArgument(!yarnApplications.isEmpty(), "no YARN applications in the list");
608
609            final Iterable<String> unorderedApplicationIds =
610                    Iterables.transform(yarnApplications, new Function<ApplicationReport, String>() {
611                        @Override
612                        public String apply(final ApplicationReport input) {
613                            Preconditions.checkNotNull(input, "YARN application should be filled");
614                            return input.getApplicationId().toString();
615                        }
616                    });
617
618            return Ordering.from(new YarnApplicationIdComparator()).max(unorderedApplicationIds);
619        }
620
621        private boolean isHadoopJobId(final String jobIdCandidate) {
622            try {
623                return JobID.forName(jobIdCandidate) != null;
624            } catch (final IllegalArgumentException e) {
625                LOG.warn("Job ID candidate is not a Hadoop Job ID.", e);
626                return false;
627            }
628        }
629    }
630
631    /**
632     * Compares two YARN application IDs in the sense:
633     * <ul>
634     *     <li>originating from different cluster timestamps the one with the bigger timestamp is considered greater</li>
635     *     <li>originating from the same cluster timestamp the one with the higher sequence number is considered greater</li>
636     *     <li>originating from the same cluster timestamp and with the same sequence number both are considered equal</li>
637     * </ul>
638     */
639    @VisibleForTesting
640    @SuppressFBWarnings(value = "SE_COMPARATOR_SHOULD_BE_SERIALIZABLE", justification = "instances will never be serialized")
641    static class YarnApplicationIdComparator implements Comparator<String> {
642        private static final String PREFIX = "application_";
643        private static final String SEPARATOR = "_";
644
645        @Override
646        public int compare(final String left, final String right) {
647            // Let's say two application IDs with different cluster timestamps are equal
648            final int middleLongPartComparisonResult = Long.compare(getMiddleLongPart(left), getMiddleLongPart(right));
649            if (middleLongPartComparisonResult != 0) {
650                return middleLongPartComparisonResult;
651            }
652
653            // Else we compare the sequence number
654            return Integer.compare(getLastIntegerPart(left), getLastIntegerPart(right));
655        }
656
657        private long getMiddleLongPart(final String applicationId) {
658            return Long.parseLong(applicationId.substring(applicationId.indexOf(PREFIX) + PREFIX.length(),
659                    applicationId.lastIndexOf(SEPARATOR)));
660        }
661
662        private int getLastIntegerPart(final String applicationId) {
663            return Integer.parseInt(applicationId.substring(applicationId.lastIndexOf(SEPARATOR) + SEPARATOR.length()));
664        }
665    }
666
667    /**
668     * Encapsulates call to the static method
669     * {@link LauncherMain#getChildYarnApplications(Configuration, ApplicationsRequestScope, long)} for better testability.
670     */
671    @VisibleForTesting
672    static class YarnApplicationReportReader {
673        private final Configuration jobConf;
674
675        YarnApplicationReportReader(final Configuration jobConf) {
676            this.jobConf = jobConf;
677        }
678
679        List<ApplicationReport> read() {
680            return LauncherMain.getChildYarnApplications(jobConf, ApplicationsRequestScope.OWN, 0L);
681        }
682    }
683}