source: gs2-extensions/parallel-building/trunk/src/src/java/org/nzdl/gsdl/HadoopGreenstoneIngest.java@ 27494

Last change on this file since 27494 was 27494, checked in by jmt12, 11 years ago

Fixing a truncated comment - or maybe I never wrote an end to it...

File size: 12.6 KB
Line 
1/** jmt12 **/
2package org.nzdl.gsdl;
3
4import java.io.BufferedOutputStream;
5import java.io.BufferedReader;
6import java.io.File;
7import java.io.FileOutputStream;
8import java.io.FileWriter;
9import java.io.InputStream;
10import java.io.InputStreamReader;
11import java.io.IOException;
12import java.io.PrintWriter;
13import java.lang.ProcessBuilder;
14import java.lang.ProcessBuilder.*;
15import java.lang.Thread;
16import java.net.InetAddress;
17import java.util.Map;
18
19import org.apache.hadoop.fs.Path;
20import org.apache.hadoop.conf.*;
21import org.apache.hadoop.io.*;
22import org.apache.hadoop.mapreduce.*;
23import org.apache.hadoop.mapreduce.Mapper.Context;
24import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
25import org.apache.hadoop.mapreduce.lib.input.FileSplit;
26import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
27import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
28import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
29import org.apache.hadoop.util.*;
30
31/** @class WordCount
32 */
33public class HadoopGreenstoneIngest
34{
35
36 /** @class GSFileRecordReader
37 */
38 public static class GSFileRecordReader
39 extends RecordReader<Text, IntWritable>
40 {
41 /** Uncompressed file name */
42 private Text current_key;
43
44 private IntWritable current_value = new IntWritable(1);
45
46 /** Used to indicate progress */
47 private boolean is_finished = false;
48
49 /**
50 */
51 @Override
52 public void initialize( InputSplit inputSplit, TaskAttemptContext taskAttemptContext )
53 throws IOException, InterruptedException
54 {
55 FileSplit split = (FileSplit) inputSplit;
56 current_key = new Text(split.getPath().toString());
57 }
58 /** initialize() **/
59
60 /**
61 * We only ever have a single key/value
62 */
63 @Override
64 public boolean nextKeyValue()
65 throws IOException, InterruptedException
66 {
67 if (!is_finished)
68 {
69 is_finished = true;
70 return true;
71 }
72 return false;
73 }
74 /** nextKeyValue() **/
75
76 /** @function getProgress
77 * Rather than calculating progress, we just keep it simple
78 */
79 @Override
80 public float getProgress()
81 throws IOException, InterruptedException
82 {
83 return is_finished ? 1 : 0;
84 }
85 /** getProgress() **/
86
87 /**
88 * Returns the current key (name of the zipped file)
89 */
90 @Override
91 public Text getCurrentKey()
92 throws IOException, InterruptedException
93 {
94 return current_key;
95 }
96 /** getCurrentKey() **/
97
98 /**
99 * Returns the current value (contents of the zipped file)
100 */
101 @Override
102 public IntWritable getCurrentValue()
103 throws IOException, InterruptedException
104 {
105 return current_value;
106 }
107 /** getCurrentValue() **/
108
109 /**
110 * Close quietly, ignoring any exceptions
111 */
112 @Override
113 public void close()
114 throws IOException
115 {
116 // nothing to do
117 }
118 /** close() **/
119
120 }
121 /** GSFileRecordReader **/
122
123 /** @class GSFileInputFormat
124 */
125 public static class GSFileInputFormat
126 extends FileInputFormat<Text, IntWritable>
127 {
128 /**
129 * Don't split the files
130 */
131 @Override
132 protected boolean isSplitable(JobContext context, Path filename)
133 {
134 return false;
135 }
136 /** isSplitable() **/
137
138 /**
139 */
140 @Override
141 public RecordReader<Text, IntWritable> createRecordReader(InputSplit split, TaskAttemptContext content)
142 throws IOException, InterruptedException
143 {
144 return new GSFileRecordReader();
145 }
146 /** createRecordReader() **/
147
148 }
149 /** class GSFileInputFormat **/
150
151 /** @class GSMap
152 */
153 public static class GSMap
154 extends Mapper<Text, IntWritable, Text, IntWritable>
155 {
156 /** @function map
157 * The key is the full path (HDFS) of the file to be processed.
158 */
159 public void map(Text key, IntWritable value, Context context)
160 throws IOException, InterruptedException
161 {
162 String file_path = key.toString();
163 // - configuration for the task
164 Configuration conf = context.getConfiguration();
165 String gsdlhome = conf.get("gsdlhome");
166 String hdfs_prefix = conf.get("hdfsprefix");
167 String hadoop_prefix = conf.get("hadoopprefix");
168 String collection = conf.get("collection");
169 String task_id = conf.get("mapred.task.id");
170 task_id = task_id.substring(8); // remove "attempt_" prefix
171 // - create a temporary directory
172 File greenstone_tmp_dir = new File("/tmp/greenstone");
173 if (!greenstone_tmp_dir.isDirectory())
174 {
175 greenstone_tmp_dir.mkdir();
176 }
177 // - open a unique log file
178 File import_process_log = new File("/tmp/greenstone/import-hadoop-" + task_id + ".log");
179 // - start the log by writing the time and the manifest line
180 FileWriter fw1 = new FileWriter(import_process_log, true);
181 long start_time = System.currentTimeMillis()/1000;
182 fw1.write("[Started:" + start_time + "]\n");
183 fw1.write("[Host:" + InetAddress.getLocalHost().getHostName() + "]\n");
184 fw1.write("[Task:" + task_id + "]\n");
185
186 // Programatically rewrite the protocol as appropriate for the given
187 // archives directory
188 file_path = file_path.replace("hdfs://", hdfs_prefix);
189 fw1.write("[Map:" + file_path + " => " + value + "]\n");
190
191 // - create a temporary manifest file to process this file. Overwrite any
192 // existing file
193 File manifest_path = new File("/tmp/greenstone/manifest" + task_id + ".xml");
194 FileWriter manifest_writer = new FileWriter(manifest_path);
195 manifest_writer.write("<Manifest version=\"2.0\">\n");
196 manifest_writer.write("\t<Index>\n");
197 manifest_writer.write("\t\t<Filename>" + file_path + "</Filename>\n");
198 manifest_writer.write("\t</Index>\n");
199 manifest_writer.write("</Manifest>\n");
200 manifest_writer.close();
201
202 // - call Greenstone passing in the path to the manifest
203 ProcessBuilder import_process_builder
204 = new ProcessBuilder("time", "-p", "import.pl", "-manifest", manifest_path.toString(), "-keepold", "-verbosity", "42", "-archivedir", hdfs_prefix + "/user/jmt12/gsdl/collect/" + collection + "/archives", collection);
205 fw1.write("[Command:" + import_process_builder.command() + "]\n");
206 // - alter environment
207 Map<String, String> import_process_env = import_process_builder.environment();
208 // - path
209 String path = import_process_env.get("PATH");
210 path = gsdlhome + "/ext/parallel-building/bin/script:" + path;
211 path = gsdlhome + "/ext/parallel-building/linux/bin:" + path;
212 path = hadoop_prefix + "/bin:" + path;
213 path = gsdlhome + "/ext/tdb-edit/linux/bin:" + path;
214 path = gsdlhome + "/ext/tdb-edit/bin/script:" + path;
215 path = gsdlhome + "/ext/video-and-audio/linux/bin:" + path;
216 path = gsdlhome + "/bin/script:" + path;
217 path = gsdlhome + "/bin/linux:" + path;
218 import_process_env.put("PATH", path);
219 fw1.write("[PATH: " + path + "]\n");
220 // - ld_library_path
221 import_process_env.put("LD_LIBRARY_PATH", gsdlhome + "/ext/parallel-building/linux/lib:" + gsdlhome + "/ext/hadoop/linux/lib:" + gsdlhome + "/ext/video-and-audio/linux/lib:" + gsdlhome + "/ext/tdb-edit/linux/lib");
222 // - dyld_library_path
223 import_process_env.put("DYLD_LIBRARY_PATH", gsdlhome + "/ext/video-and-audio/linux/lib");
224 // - misc
225 import_process_env.put("GSDLHOME", gsdlhome);
226 import_process_env.put("GSDLOS", "linux");
227 import_process_env.put("GSDLEXTS", "parallel-building:tdb-edit:video-and-audio");
228 // - installed extension paths
229 import_process_env.put("GEXTPARALLELBUILDING", gsdlhome + "/ext/parallel-building");
230 import_process_env.put("GEXTPARALLELBUILDING_INSTALLED", gsdlhome + "/ext/parallel-building/linux");
231 import_process_env.put("GEXTTDBEDIT_INSTALLED", gsdlhome + "/ext/tdb-edit/linux");
232 import_process_env.put("GEXTVIDEO_INSTALLED", gsdlhome + "/ext/video-and-audio/linux");
233 // - Hadoop specific
234 import_process_env.put("HADOOP_PREFIX", hadoop_prefix);
235 fw1.write("[HADOOP_PREFIX: " + hadoop_prefix + "]\n");
236
237 // - change working directory
238 import_process_builder.directory(new File(gsdlhome));
239 // - close our output to the log before opening in the process
240 fw1.close();
241
242 // - write output to log
243 import_process_builder.redirectErrorStream(true);
244 import_process_builder.redirectOutput(Redirect.appendTo(import_process_log));
245
246 // - create progress reporter (so Hadoop doesn't time us out)
247 Thread reporter = new HadoopProgressReporter(context, import_process_log);
248 reporter.start();
249
250 // - run process
251 Process import_process = import_process_builder.start();
252 try
253 {
254 int import_status = import_process.waitFor();
255 if (import_status != 0)
256 {
257 throw new Exception("exit status: " + import_status);
258 }
259 }
260 catch (Exception e)
261 {
262 System.err.println("Error! Import command failed (" + e.toString() + ")");
263 }
264
265 // - stop the progress reporter as, one way or another, there will be no
266 // more progress
267 reporter.interrupt();
268 reporter = null; // force gc
269
270 // - write end time to log
271 FileWriter fw2 = new FileWriter(import_process_log, true);
272 long end_time = System.currentTimeMillis()/1000;
273 fw2.write("[Completed:" + end_time + "]\n");
274 fw2.close();
275
276 // - for now return a dummy output. In the future I may want to parse the
277 // output from Greenstone as output and allow reducing to make me a
278 // pretty timebased log
279 context.write(key, value);
280 }
281 /** map(LongWritable,Text,Context) **/
282
283 }
284 /** class GSMap **/
285
286 /** @function main
287 */
288 public static void main(String[] args)
289 throws Exception
290 {
291 if (args.length < 6)
292 {
293 System.out.println("Usage: bin/hadoop jar hadoop-greenstone.jar org.nzdl.gsdl.HadoopGreenstoneIngest <gsdlhome> <hdfsprefix> <hadoop prefix> <collection> <hdfsin> <hdfsout>\n");
294 System.exit(0);
295 }
296
297 Configuration conf = new Configuration();
298 conf.set("gsdlhome", args[0]);
299 conf.set("hdfsprefix", args[1]); // HDThriftFS or HDFSShell
300 conf.set("hadoopprefix", args[2]);
301 conf.set("collection", args[3]);
302 // Set the number of retries to 1 - hopefully one of the following will work
303 conf.setInt("mapred.map.max.attempts", 1); // Old Hadoop
304 conf.setInt("mapreduce.map.maxattempts", 1); // Hadoop 2.0.3-alpha
305 conf.setInt("mapreduce.map.max.attempts", 1); // Solution on Web
306 // prevent timeouts
307 long milli_seconds = 60*60*1000; // 1 hour
308 conf.setLong("mapred.task.timeout", milli_seconds);
309 Job job = new Job(conf, "hadoopgreenstoneingest");
310 job.setJarByClass(HadoopGreenstoneIngest.class);
311
312 job.setOutputKeyClass(Text.class);
313 job.setOutputValueClass(IntWritable.class);
314
315 // Register the map, combiner, and reducer classes
316 job.setMapperClass(GSMap.class);
317 // - in theory, uses the IdentityReducer by default, which simply returns
318 // the input as the output (so no processing)
319 job.setNumReduceTasks(0);
320
321 // Sets the input and output handlers - may need to adjust input to provide me
322 // a series of filenames (TextInputFormat will instead read in a text file and
323 // return each line...)
324 job.setInputFormatClass(GSFileInputFormat.class);
325 job.setOutputFormatClass(NullOutputFormat.class);
326 //job.setOutputFormatClass(TextOutputFormat.class);
327
328 // Register the input and output paths
329 // - this input path should be to a file (in HDFS) that lists the paths to
330 // the manifest files
331 FileInputFormat.setInputPaths(job, new Path(args[4]));
332 // - for now the output isn't that important, but in the future I may use
333 // this mechanism to produce a time based log.
334 FileOutputFormat.setOutputPath(job, new Path(args[5]));
335
336 // Recommended notation despite my hatiness of ?: syntax
337 System.exit(job.waitForCompletion(true)?0:1);
338 }
339 /** main(String[]) **/
340}
341
342class HadoopProgressReporter
343extends Thread
344{
345
346 private Context hadoop_process;
347
348 private File log_file;
349
350 HadoopProgressReporter(Context hadoop_process, File log_file)
351 {
352 this.hadoop_process = hadoop_process;
353 this.log_file = log_file;
354 }
355
356 public void run()
357 {
358 try
359 {
360 while (!this.isInterrupted())
361 {
362 sleep(60000); // Wait a minute
363 //FileWriter fw1 = new FileWriter(this.log_file, true);
364 //long time = System.currentTimeMillis()/1000;
365 //fw1.write("[" + time + "] HadoopProgressReporter.progress()\n");
366 //fw1.close();
367 this.hadoop_process.progress(); // Inform Hadoop we are still processing
368 }
369 }
370 catch (InterruptedException iex)
371 {
372 // We've been interrupted: no more progress
373 }
374 catch (Exception ex)
375 {
376 ex.printStackTrace();
377 }
378 }
379}
Note: See TracBrowser for help on using the repository browser.