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.BufferedReader;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.InputStreamReader;
025import java.io.OutputStream;
026import java.math.BigInteger;
027import java.security.MessageDigest;
028import java.security.NoSuchAlgorithmException;
029import java.security.PrivilegedExceptionAction;
030import java.util.ArrayList;
031import java.util.Collection;
032import java.util.HashMap;
033import java.util.List;
034import java.util.Map;
035import java.util.Properties;
036
037import org.apache.hadoop.conf.Configuration;
038import org.apache.hadoop.fs.FileSystem;
039import org.apache.hadoop.fs.Path;
040import org.apache.hadoop.io.SequenceFile;
041import org.apache.hadoop.io.Text;
042import org.apache.hadoop.mapred.JobConf;
043import org.apache.hadoop.mapred.RunningJob;
044import org.apache.hadoop.mapred.Counters;
045import org.apache.hadoop.security.UserGroupInformation;
046import org.apache.oozie.client.OozieClient;
047import org.apache.oozie.client.WorkflowAction;
048import org.apache.oozie.service.HadoopAccessorException;
049import org.apache.oozie.service.HadoopAccessorService;
050import org.apache.oozie.service.Services;
051import org.apache.oozie.service.URIHandlerService;
052import org.apache.oozie.service.UserGroupInformationService;
053import org.apache.oozie.util.IOUtils;
054import org.apache.oozie.util.PropertiesUtils;
055
056public class LauncherMapperHelper {
057
058    public static String getRecoveryId(Configuration launcherConf, Path actionDir, String recoveryId)
059            throws HadoopAccessorException, IOException {
060        String jobId = null;
061        Path recoveryFile = new Path(actionDir, recoveryId);
062        FileSystem fs = Services.get().get(HadoopAccessorService.class)
063                .createFileSystem(launcherConf.get("user.name"),recoveryFile.toUri(), launcherConf);
064
065        if (fs.exists(recoveryFile)) {
066            InputStream is = fs.open(recoveryFile);
067            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
068            jobId = reader.readLine();
069            reader.close();
070        }
071        return jobId;
072
073    }
074
075    public static void setupMainClass(Configuration launcherConf, String javaMainClass) {
076        // Only set the javaMainClass if its not null or empty string, this way the user can override the action's main class via
077        // <configuration> property
078        if (javaMainClass != null && !javaMainClass.equals("")) {
079            launcherConf.set(LauncherMapper.CONF_OOZIE_ACTION_MAIN_CLASS, javaMainClass);
080        }
081    }
082
083    public static void setupLauncherURIHandlerConf(Configuration launcherConf) {
084        for(Map.Entry<String, String> entry : Services.get().get(URIHandlerService.class).getLauncherConfig()) {
085            launcherConf.set(entry.getKey(), entry.getValue());
086        }
087    }
088
089    public static void setupMainArguments(Configuration launcherConf, String[] args) {
090        launcherConf.setInt(LauncherMapper.CONF_OOZIE_ACTION_MAIN_ARG_COUNT, args.length);
091        for (int i = 0; i < args.length; i++) {
092            launcherConf.set(LauncherMapper.CONF_OOZIE_ACTION_MAIN_ARG_PREFIX + i, args[i]);
093        }
094    }
095
096    public static void setupMaxOutputData(Configuration launcherConf, int maxOutputData) {
097        launcherConf.setInt(LauncherMapper.CONF_OOZIE_ACTION_MAX_OUTPUT_DATA, maxOutputData);
098    }
099
100    /**
101     * Set the maximum value of stats data
102     *
103     * @param launcherConf the oozie launcher configuration
104     * @param maxStatsData the maximum allowed size of stats data
105     */
106    public static void setupMaxExternalStatsSize(Configuration launcherConf, int maxStatsData){
107        launcherConf.setInt(LauncherMapper.CONF_OOZIE_EXTERNAL_STATS_MAX_SIZE, maxStatsData);
108    }
109
110    /**
111     * Set the maximum number of globbed files/dirs
112     *
113     * @param launcherConf the oozie launcher configuration
114     * @param fsGlobMax the maximum number of files/dirs for FS operation
115     */
116    public static void setupMaxFSGlob(Configuration launcherConf, int fsGlobMax){
117        launcherConf.setInt(LauncherMapper.CONF_OOZIE_ACTION_FS_GLOB_MAX, fsGlobMax);
118    }
119
120    public static void setupLauncherInfo(JobConf launcherConf, String jobId, String actionId, Path actionDir,
121            String recoveryId, Configuration actionConf, String prepareXML) throws IOException, HadoopAccessorException {
122
123        launcherConf.setMapperClass(LauncherMapper.class);
124        launcherConf.setSpeculativeExecution(false);
125        launcherConf.setNumMapTasks(1);
126        launcherConf.setNumReduceTasks(0);
127
128        launcherConf.set(LauncherMapper.OOZIE_JOB_ID, jobId);
129        launcherConf.set(LauncherMapper.OOZIE_ACTION_ID, actionId);
130        launcherConf.set(LauncherMapper.OOZIE_ACTION_DIR_PATH, actionDir.toString());
131        launcherConf.set(LauncherMapper.OOZIE_ACTION_RECOVERY_ID, recoveryId);
132        launcherConf.set(LauncherMapper.ACTION_PREPARE_XML, prepareXML);
133
134        actionConf.set(LauncherMapper.OOZIE_JOB_ID, jobId);
135        actionConf.set(LauncherMapper.OOZIE_ACTION_ID, actionId);
136
137        if (Services.get().getConf().getBoolean("oozie.hadoop-2.0.2-alpha.workaround.for.distributed.cache", false)) {
138          List<String> purgedEntries = new ArrayList<String>();
139          Collection<String> entries = actionConf.getStringCollection("mapreduce.job.cache.files");
140          for (String entry : entries) {
141            if (entry.contains("#")) {
142              purgedEntries.add(entry);
143            }
144          }
145          actionConf.setStrings("mapreduce.job.cache.files", purgedEntries.toArray(new String[purgedEntries.size()]));
146          launcherConf.setBoolean("oozie.hadoop-2.0.2-alpha.workaround.for.distributed.cache", true);
147        }
148
149        FileSystem fs =
150          Services.get().get(HadoopAccessorService.class).createFileSystem(launcherConf.get("user.name"),
151                                                                           actionDir.toUri(), launcherConf);
152        fs.mkdirs(actionDir);
153
154        OutputStream os = fs.create(new Path(actionDir, LauncherMapper.ACTION_CONF_XML));
155        try {
156            actionConf.writeXml(os);
157        } finally {
158            IOUtils.closeSafely(os);
159        }
160
161        launcherConf.setInputFormat(OozieLauncherInputFormat.class);
162        launcherConf.setOutputFormat(OozieLauncherOutputFormat.class);
163        launcherConf.setOutputCommitter(OozieLauncherOutputCommitter.class);
164    }
165
166    public static void setupYarnRestartHandling(JobConf launcherJobConf, Configuration actionConf, String launcherTag,
167                                                long launcherTime)
168            throws NoSuchAlgorithmException {
169        launcherJobConf.setLong(LauncherMainHadoopUtils.OOZIE_JOB_LAUNCH_TIME, launcherTime);
170        // Tags are limited to 100 chars so we need to hash them to make sure (the actionId otherwise doesn't have a max length)
171        String tag = getTag(launcherTag);
172        // keeping the oozie.child.mapreduce.job.tags instead of mapreduce.job.tags to avoid killing launcher itself.
173        // mapreduce.job.tags should only go to child job launch by launcher.
174        actionConf.set(LauncherMainHadoopUtils.CHILD_MAPREDUCE_JOB_TAGS, tag);
175    }
176
177    private static String getTag(String launcherTag) throws NoSuchAlgorithmException {
178        MessageDigest digest = MessageDigest.getInstance("MD5");
179        digest.update(launcherTag.getBytes(), 0, launcherTag.length());
180        String md5 = "oozie-" + new BigInteger(1, digest.digest()).toString(16);
181        return md5;
182    }
183
184    public static boolean isMainDone(RunningJob runningJob) throws IOException {
185        return runningJob.isComplete();
186    }
187
188    public static boolean isMainSuccessful(RunningJob runningJob) throws IOException {
189        boolean succeeded = runningJob.isSuccessful();
190        if (succeeded) {
191            Counters counters = runningJob.getCounters();
192            if (counters != null) {
193                Counters.Group group = counters.getGroup(LauncherMapper.COUNTER_GROUP);
194                if (group != null) {
195                    succeeded = group.getCounter(LauncherMapper.COUNTER_LAUNCHER_ERROR) == 0;
196                }
197            }
198        }
199        return succeeded;
200    }
201
202    /**
203     * Determine whether action has external child jobs or not
204     * @param actionData
205     * @return true/false
206     * @throws IOException
207     */
208    public static boolean hasExternalChildJobs(Map<String, String> actionData) throws IOException {
209        return actionData.containsKey(LauncherMapper.ACTION_DATA_EXTERNAL_CHILD_IDS);
210    }
211
212    /**
213     * Determine whether action has output data or not
214     * @param actionData
215     * @return true/false
216     * @throws IOException
217     */
218    public static boolean hasOutputData(Map<String, String> actionData) throws IOException {
219        return actionData.containsKey(LauncherMapper.ACTION_DATA_OUTPUT_PROPS);
220    }
221
222    /**
223     * Determine whether action has external stats or not
224     * @param actionData
225     * @return true/false
226     * @throws IOException
227     */
228    public static boolean hasStatsData(Map<String, String> actionData) throws IOException{
229        return actionData.containsKey(LauncherMapper.ACTION_DATA_STATS);
230    }
231
232    /**
233     * Determine whether action has new id (id swap) or not
234     * @param actionData
235     * @return true/false
236     * @throws IOException
237     */
238    public static boolean hasIdSwap(Map<String, String> actionData) throws IOException {
239        return actionData.containsKey(LauncherMapper.ACTION_DATA_NEW_ID);
240    }
241
242    /**
243     * Get the sequence file path storing all action data
244     * @param actionDir
245     * @return
246     */
247    public static Path getActionDataSequenceFilePath(Path actionDir) {
248        return new Path(actionDir, LauncherMapper.ACTION_DATA_SEQUENCE_FILE);
249    }
250
251    /**
252     * Utility function to load the contents of action data sequence file into
253     * memory object
254     *
255     * @param fs Action Filesystem
256     * @param actionDir Path
257     * @param conf Configuration
258     * @return Map action data
259     * @throws IOException
260     * @throws InterruptedException
261     */
262    public static Map<String, String> getActionData(final FileSystem fs, final Path actionDir, final Configuration conf)
263            throws IOException, InterruptedException {
264        UserGroupInformationService ugiService = Services.get().get(UserGroupInformationService.class);
265        UserGroupInformation ugi = ugiService.getProxyUser(conf.get(OozieClient.USER_NAME));
266
267        return ugi.doAs(new PrivilegedExceptionAction<Map<String, String>>() {
268            @Override
269            public Map<String, String> run() throws IOException {
270                Map<String, String> ret = new HashMap<String, String>();
271                Path seqFilePath = getActionDataSequenceFilePath(actionDir);
272                if (fs.exists(seqFilePath)) {
273                    SequenceFile.Reader seqFile = new SequenceFile.Reader(fs, seqFilePath, conf);
274                    Text key = new Text(), value = new Text();
275                    while (seqFile.next(key, value)) {
276                        ret.put(key.toString(), value.toString());
277                    }
278                    seqFile.close();
279                }
280                else { // maintain backward-compatibility. to be deprecated
281                    org.apache.hadoop.fs.FileStatus[] files = fs.listStatus(actionDir);
282                    InputStream is;
283                    BufferedReader reader = null;
284                    Properties props;
285                    if (files != null && files.length > 0) {
286                        for (int x = 0; x < files.length; x++) {
287                            Path file = files[x].getPath();
288                            if (file.equals(new Path(actionDir, "externalChildIds.properties"))) {
289                                is = fs.open(file);
290                                reader = new BufferedReader(new InputStreamReader(is));
291                                ret.put(LauncherMapper.ACTION_DATA_EXTERNAL_CHILD_IDS,
292                                        IOUtils.getReaderAsString(reader, -1));
293                            }
294                            else if (file.equals(new Path(actionDir, "newId.properties"))) {
295                                is = fs.open(file);
296                                reader = new BufferedReader(new InputStreamReader(is));
297                                props = PropertiesUtils.readProperties(reader, -1);
298                                ret.put(LauncherMapper.ACTION_DATA_NEW_ID, props.getProperty("id"));
299                            }
300                            else if (file.equals(new Path(actionDir, LauncherMapper.ACTION_DATA_OUTPUT_PROPS))) {
301                                int maxOutputData = conf.getInt(LauncherMapper.CONF_OOZIE_ACTION_MAX_OUTPUT_DATA,
302                                        2 * 1024);
303                                is = fs.open(file);
304                                reader = new BufferedReader(new InputStreamReader(is));
305                                ret.put(LauncherMapper.ACTION_DATA_OUTPUT_PROPS, PropertiesUtils
306                                        .propertiesToString(PropertiesUtils.readProperties(reader, maxOutputData)));
307                            }
308                            else if (file.equals(new Path(actionDir, LauncherMapper.ACTION_DATA_STATS))) {
309                                int statsMaxOutputData = conf.getInt(LauncherMapper.CONF_OOZIE_EXTERNAL_STATS_MAX_SIZE,
310                                        Integer.MAX_VALUE);
311                                is = fs.open(file);
312                                reader = new BufferedReader(new InputStreamReader(is));
313                                ret.put(LauncherMapper.ACTION_DATA_STATS, PropertiesUtils
314                                        .propertiesToString(PropertiesUtils.readProperties(reader, statsMaxOutputData)));
315                            }
316                            else if (file.equals(new Path(actionDir, LauncherMapper.ACTION_DATA_ERROR_PROPS))) {
317                                is = fs.open(file);
318                                reader = new BufferedReader(new InputStreamReader(is));
319                                ret.put(LauncherMapper.ACTION_DATA_ERROR_PROPS, IOUtils.getReaderAsString(reader, -1));
320                            }
321                        }
322                    }
323                }
324                return ret;
325            }
326        });
327    }
328}