View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.wal;
19  
20  import java.io.FileNotFoundException;
21  import java.io.IOException;
22  import java.io.PrintStream;
23  import java.util.ArrayList;
24  import java.util.Date;
25  import java.util.HashMap;
26  import java.util.Iterator;
27  import java.util.List;
28  import java.util.Map;
29  
30  import org.apache.commons.cli.CommandLine;
31  import org.apache.commons.cli.CommandLineParser;
32  import org.apache.commons.cli.HelpFormatter;
33  import org.apache.commons.cli.Options;
34  import org.apache.commons.cli.ParseException;
35  import org.apache.commons.cli.PosixParser;
36  import org.apache.hadoop.hbase.classification.InterfaceAudience;
37  import org.apache.hadoop.hbase.classification.InterfaceStability;
38  import org.apache.hadoop.hbase.util.GsonUtil;
39  import org.apache.hadoop.conf.Configuration;
40  import org.apache.hadoop.fs.FileSystem;
41  import org.apache.hadoop.fs.Path;
42  import org.apache.hadoop.hbase.Cell;
43  import org.apache.hadoop.hbase.CellUtil;
44  import org.apache.hadoop.hbase.HBaseConfiguration;
45  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
46  import org.apache.hadoop.hbase.Tag;
47  import org.apache.hadoop.hbase.util.Bytes;
48  import org.apache.hadoop.hbase.util.FSUtils;
49  
50  import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader;
51  // imports for things that haven't moved yet.
52  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
53  import org.apache.hbase.thirdparty.com.google.gson.Gson;
54  
55  
56  /**
57   * WALPrettyPrinter prints the contents of a given WAL with a variety of
58   * options affecting formatting and extent of content.
59   *
60   * It targets two usage cases: pretty printing for ease of debugging directly by
61   * humans, and JSON output for consumption by monitoring and/or maintenance
62   * scripts.
63   *
64   * It can filter by row, region, or sequence id.
65   *
66   * It can also toggle output of values.
67   *
68   */
69  @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
70  @InterfaceStability.Evolving
71  public class WALPrettyPrinter {
72    private boolean outputValues;
73    private boolean outputJSON;
74    // The following enable filtering by sequence, region, and row, respectively
75    private long sequence;
76    private String region;
77    private String row;
78    // enable in order to output a single list of transactions from several files
79    private boolean persistentOutput;
80    private boolean firstTxn;
81    // useful for programmatic capture of JSON output
82    private PrintStream out;
83    // for JSON encoding
84    private static final Gson GSON = GsonUtil.createGson().create();
85  
86    private long position;
87  
88    /**
89     * Basic constructor that simply initializes values to reasonable defaults.
90     */
91    public WALPrettyPrinter() {
92      outputValues = false;
93      outputJSON = false;
94      sequence = -1;
95      region = null;
96      row = null;
97      persistentOutput = false;
98      firstTxn = true;
99      out = System.out;
100   }
101 
102   /**
103    * Fully specified constructor.
104    *
105    * @param outputValues
106    *          when true, enables output of values along with other log
107    *          information
108    * @param outputJSON
109    *          when true, enables output in JSON format rather than a
110    *          "pretty string"
111    * @param sequence
112    *          when nonnegative, serves as a filter; only log entries with this
113    *          sequence id will be printed
114    * @param region
115    *          when not null, serves as a filter; only log entries from this
116    *          region will be printed
117    * @param row
118    *          when not null, serves as a filter; only log entries from this row
119    *          will be printed
120    * @param persistentOutput
121    *          keeps a single list running for multiple files. if enabled, the
122    *          endPersistentOutput() method must be used!
123    * @param out
124    *          Specifies an alternative to stdout for the destination of this
125    *          PrettyPrinter's output.
126    */
127   public WALPrettyPrinter(boolean outputValues, boolean outputJSON,
128       long sequence, String region, String row, boolean
129       persistentOutput,
130       PrintStream out) {
131     this.outputValues = outputValues;
132     this.outputJSON = outputJSON;
133     this.sequence = sequence;
134     this.region = region;
135     this.row = row;
136     this.persistentOutput = persistentOutput;
137     if (persistentOutput) {
138       beginPersistentOutput();
139     }
140     this.out = out;
141     this.firstTxn = true;
142   }
143 
144   /**
145    * turns value output on
146    */
147   public void enableValues() {
148     outputValues = true;
149   }
150 
151   /**
152    * turns value output off
153    */
154   public void disableValues() {
155     outputValues = false;
156   }
157 
158   /**
159    * turns JSON output on
160    */
161   public void enableJSON() {
162     outputJSON = true;
163   }
164 
165   /**
166    * turns JSON output off, and turns on "pretty strings" for human consumption
167    */
168   public void disableJSON() {
169     outputJSON = false;
170   }
171 
172   /**
173    * sets the region by which output will be filtered
174    *
175    * @param sequence
176    *          when nonnegative, serves as a filter; only log entries with this
177    *          sequence id will be printed
178    */
179   public void setSequenceFilter(long sequence) {
180     this.sequence = sequence;
181   }
182 
183   /**
184    * sets the region by which output will be filtered
185    *
186    * @param region
187    *          when not null, serves as a filter; only log entries from this
188    *          region will be printed
189    */
190   public void setRegionFilter(String region) {
191     this.region = region;
192   }
193 
194   /**
195    * sets the region by which output will be filtered
196    *
197    * @param row
198    *          when not null, serves as a filter; only log entries from this row
199    *          will be printed
200    */
201   public void setRowFilter(String row) {
202     this.row = row;
203   }
204 
205   /**
206    * enables output as a single, persistent list. at present, only relevant in
207    * the case of JSON output.
208    */
209   public void beginPersistentOutput() {
210     if (persistentOutput)
211       return;
212     persistentOutput = true;
213     firstTxn = true;
214     if (outputJSON)
215       out.print("[");
216   }
217 
218   /**
219    * ends output of a single, persistent list. at present, only relevant in the
220    * case of JSON output.
221    */
222   public void endPersistentOutput() {
223     if (!persistentOutput)
224       return;
225     persistentOutput = false;
226     if (outputJSON)
227       out.print("]");
228   }
229 
230   /**
231    * reads a log file and outputs its contents, one transaction at a time, as
232    * specified by the currently configured options
233    *
234    * @param conf
235    *          the HBase configuration relevant to this log file
236    * @param p
237    *          the path of the log file to be read
238    * @throws IOException
239    *           may be unable to access the configured filesystem or requested
240    *           file.
241    */
242   public void processFile(final Configuration conf, final Path p)
243       throws IOException {
244     FileSystem fs = p.getFileSystem(conf);
245     if (!fs.exists(p)) {
246       throw new FileNotFoundException(p.toString());
247     }
248     if (!fs.isFile(p)) {
249       throw new IOException(p + " is not a file");
250     }
251 
252     WAL.Reader log = WALFactory.createReader(fs, p, conf);
253     
254     if (log instanceof ProtobufLogReader) {
255       List<String> writerClsNames = ((ProtobufLogReader) log).getWriterClsNames();
256       if (writerClsNames != null && writerClsNames.size() > 0) {
257         out.print("Writer Classes: ");
258         for (int i = 0; i < writerClsNames.size(); i++) {
259           out.print(writerClsNames.get(i));
260           if (i != writerClsNames.size() - 1) {
261             out.print(" ");
262           }
263         }
264         out.println();
265       }
266       
267       String cellCodecClsName = ((ProtobufLogReader) log).getCodecClsName();
268       if (cellCodecClsName != null) {
269         out.println("Cell Codec Class: " + cellCodecClsName);
270       }
271     }
272     
273     if (outputJSON && !persistentOutput) {
274       out.print("[");
275       firstTxn = true;
276     }
277 
278     if (position > 0) {
279       log.seek(position);
280     }
281 
282     try {
283       WAL.Entry entry;
284       while ((entry = log.next()) != null) {
285         WALKey key = entry.getKey();
286         WALEdit edit = entry.getEdit();
287         // begin building a transaction structure
288         Map<String, Object> txn = key.toStringMap();
289         long writeTime = key.getWriteTime();
290         // check output filters
291         if (sequence >= 0 && ((Long) txn.get("sequence")) != sequence)
292           continue;
293         if (region != null && !((String) txn.get("region")).equals(region))
294           continue;
295         // initialize list into which we will store atomic actions
296         List<Map> actions = new ArrayList<Map>();
297         for (Cell cell : edit.getCells()) {
298           // add atomic operation to txn
299           Map<String, Object> op = new HashMap<String, Object>(toStringMap(cell));
300           if (outputValues) op.put("value", Bytes.toStringBinary(cell.getValue()));
301           // check row output filter
302           if (row == null || ((String) op.get("row")).equals(row)) {
303             actions.add(op);
304           }
305           op.put("total_size_sum", CellUtil.estimatedHeapSizeOf(cell));
306 
307         }
308         if (actions.size() == 0)
309           continue;
310         txn.put("actions", actions);
311         if (outputJSON) {
312           // JSON output is a straightforward "toString" on the txn object
313           if (firstTxn)
314             firstTxn = false;
315           else
316             out.print(",");
317           // encode and print JSON
318           out.print(GSON.toJson(txn));
319         } else {
320           // Pretty output, complete with indentation by atomic action
321           out.println("Sequence=" + txn.get("sequence") + " "
322               + ", region=" + txn.get("region") + " at write timestamp=" + new Date(writeTime));
323           for (int i = 0; i < actions.size(); i++) {
324             Map op = actions.get(i);
325             out.println("row=" + op.get("row") +
326                 ", column=" + op.get("family") + ":" + op.get("qualifier"));
327             if (op.get("tag") != null) {
328               out.println("    tag: " + op.get("tag"));
329             }
330             if (outputValues) out.println("    value: " + op.get("value"));
331             out.println("cell total size sum: " + op.get("total_size_sum"));
332           }
333         }
334         out.println("edit heap size: " + entry.getEdit().heapSize());
335         out.println("position: " + log.getPosition());
336       }
337     } finally {
338       log.close();
339     }
340     if (outputJSON && !persistentOutput) {
341       out.print("]");
342     }
343   }
344 
345   private static Map<String, Object> toStringMap(Cell cell) {
346     Map<String, Object> stringMap = new HashMap<String, Object>();
347     stringMap.put("row",
348         Bytes.toStringBinary(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()));
349     stringMap.put("family", Bytes.toStringBinary(cell.getFamilyArray(), cell.getFamilyOffset(),
350                 cell.getFamilyLength()));
351     stringMap.put("qualifier",
352         Bytes.toStringBinary(cell.getQualifierArray(), cell.getQualifierOffset(),
353             cell.getQualifierLength()));
354     stringMap.put("timestamp", cell.getTimestamp());
355     stringMap.put("vlen", cell.getValueLength());
356     if (cell.getTagsLength() > 0) {
357       List<String> tagsString = new ArrayList<String>();
358       Iterator<Tag> tagsIterator = CellUtil.tagsIterator(cell.getTagsArray(), cell.getTagsOffset(),
359           cell.getTagsLength());
360       while (tagsIterator.hasNext()) {
361         Tag tag = tagsIterator.next();
362         tagsString.add((tag.getType()) + ":"
363             + Bytes.toStringBinary(tag.getBuffer(), tag.getTagOffset(), tag.getTagLength()));
364       }
365       stringMap.put("tag", tagsString);
366     }
367     return stringMap;
368   }
369 
370   public static void main(String[] args) throws IOException {
371     run(args);
372   }
373 
374   /**
375    * Pass one or more log file names and formatting options and it will dump out
376    * a text version of the contents on <code>stdout</code>.
377    *
378    * @param args
379    *          Command line arguments
380    * @throws IOException
381    *           Thrown upon file system errors etc.
382    */
383   public static void run(String[] args) throws IOException {
384     // create options
385     Options options = new Options();
386     options.addOption("h", "help", false, "Output help message");
387     options.addOption("j", "json", false, "Output JSON");
388     options.addOption("p", "printvals", false, "Print values");
389     options.addOption("r", "region", true,
390         "Region to filter by. Pass encoded region name; e.g. '9192caead6a5a20acb4454ffbc79fa14'");
391     options.addOption("s", "sequence", true,
392         "Sequence to filter by. Pass sequence number.");
393     options.addOption("w", "row", true, "Row to filter by. Pass row name.");
394     options.addOption("g", "goto", true, "Position to seek to in the file");
395 
396     WALPrettyPrinter printer = new WALPrettyPrinter();
397     CommandLineParser parser = new PosixParser();
398     List<?> files = null;
399     try {
400       CommandLine cmd = parser.parse(options, args);
401       files = cmd.getArgList();
402       if (files.size() == 0 || cmd.hasOption("h")) {
403         HelpFormatter formatter = new HelpFormatter();
404         formatter.printHelp("WAL <filename...>", options, true);
405         System.exit(-1);
406       }
407       // configure the pretty printer using command line options
408       if (cmd.hasOption("p"))
409         printer.enableValues();
410       if (cmd.hasOption("j"))
411         printer.enableJSON();
412       if (cmd.hasOption("r"))
413         printer.setRegionFilter(cmd.getOptionValue("r"));
414       if (cmd.hasOption("s"))
415         printer.setSequenceFilter(Long.parseLong(cmd.getOptionValue("s")));
416       if (cmd.hasOption("w"))
417         printer.setRowFilter(cmd.getOptionValue("w"));
418       if (cmd.hasOption("g")) {
419         printer.setPosition(Long.parseLong(cmd.getOptionValue("g")));
420       }
421     } catch (ParseException e) {
422       e.printStackTrace();
423       HelpFormatter formatter = new HelpFormatter();
424       formatter.printHelp("HFile filename(s) ", options, true);
425       System.exit(-1);
426     }
427     // get configuration, file system, and process the given files
428     Configuration conf = HBaseConfiguration.create();
429     FSUtils.setFsDefault(conf, FSUtils.getRootDir(conf));
430 
431     // begin output
432     printer.beginPersistentOutput();
433     for (Object f : files) {
434       Path file = new Path((String) f);
435       FileSystem fs = file.getFileSystem(conf);
436       if (!fs.exists(file)) {
437         System.err.println("ERROR, file doesnt exist: " + file);
438         return;
439       }
440       printer.processFile(conf, file);
441     }
442     printer.endPersistentOutput();
443   }
444 
445   public void setPosition(long position) {
446     this.position = position;
447   }
448 }