You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hbase.apache.org by se...@apache.org on 2013/04/30 20:34:59 UTC

svn commit: r1477762 [5/6] - in /hbase/branches/0.95: hbase-client/src/main/java/org/apache/hadoop/hbase/protobuf/ hbase-common/src/main/java/org/apache/hadoop/hbase/codec/ hbase-common/src/main/resources/ hbase-protocol/src/main/java/org/apache/hadoop...

Modified: hbase/branches/0.95/hbase-protocol/src/main/protobuf/Admin.proto
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-protocol/src/main/protobuf/Admin.proto?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-protocol/src/main/protobuf/Admin.proto (original)
+++ hbase/branches/0.95/hbase-protocol/src/main/protobuf/Admin.proto Tue Apr 30 18:34:58 2013
@@ -25,6 +25,7 @@ option java_generate_equals_and_hash = t
 option optimize_for = SPEED;
 
 import "hbase.proto";
+import "WAL.proto";
 
 message GetRegionInfoRequest {
   required RegionSpecifier region = 1;
@@ -155,39 +156,10 @@ message MergeRegionsRequest {
 message MergeRegionsResponse {
 }
 
-message UUID {
-  required uint64 leastSigBits = 1;
-  required uint64 mostSigBits = 2;
-}
-
-// Protocol buffer version of HLog
+// Protocol buffer version of WAL for replication
 message WALEntry {
   required WALKey key = 1;
-  required WALEdit edit = 2;
-
-  // Protocol buffer version of HLogKey
-  message WALKey {
-    required bytes encodedRegionName = 1;
-    required bytes tableName = 2;
-    required uint64 logSequenceNumber = 3;
-    required uint64 writeTime = 4;
-    optional UUID clusterId = 5;
-  }
-
-  message WALEdit {
-    repeated bytes keyValueBytes = 1;
-    repeated FamilyScope familyScope = 2;
-
-    enum ScopeType {
-      REPLICATION_SCOPE_LOCAL = 0;
-      REPLICATION_SCOPE_GLOBAL = 1;
-    }
-
-    message FamilyScope {
-      required bytes family = 1;
-      required ScopeType scopeType = 2;
-    }
-  }
+  repeated bytes keyValueBytes = 2;
 }
 
 /**

Modified: hbase/branches/0.95/hbase-protocol/src/main/protobuf/WAL.proto
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-protocol/src/main/protobuf/WAL.proto?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-protocol/src/main/protobuf/WAL.proto (original)
+++ hbase/branches/0.95/hbase-protocol/src/main/protobuf/WAL.proto Tue Apr 30 18:34:58 2013
@@ -16,14 +16,48 @@
  * limitations under the License.
  */
 option java_package = "org.apache.hadoop.hbase.protobuf.generated";
-option java_outer_classname = "WAL";
+option java_outer_classname = "WALProtos";
+option java_generic_services = false;
 option java_generate_equals_and_hash = true;
 option optimize_for = SPEED;
 
 import "hbase.proto";
 
+message WALHeader {
+  optional bool hasCompression = 1;
+}
+
+// Protocol buffer version of HLogKey; see HLogKey comment, not really a key but WALEdit header for some KVs
+message WALKey {
+  required bytes encodedRegionName = 1;
+  required bytes tableName = 2;
+  required uint64 logSequenceNumber = 3;
+  required uint64 writeTime = 4;
+  optional UUID clusterId = 5;
+  
+  repeated FamilyScope scopes = 6;
+  optional uint32 followingKvCount = 7;
+/*
+  optional CustomEntryType customEntryType = 8;
+
+  enum CustomEntryType {
+    COMPACTION = 0;
+  }
+*/
+}
+
+enum ScopeType {
+  REPLICATION_SCOPE_LOCAL = 0;
+  REPLICATION_SCOPE_GLOBAL = 1;
+}
+
+message FamilyScope {
+  required bytes family = 1;
+  required ScopeType scopeType = 2;
+}
+
 /**
- * WAL entries
+ * Custom WAL entries
  */
 
 /**
@@ -33,7 +67,7 @@ import "hbase.proto";
  * the * compaction should we fail the WAL write.
  */
 message CompactionDescriptor {
-  required bytes tableName = 1;
+  required bytes tableName = 1; // TODO: WALKey already stores these, might remove
   required bytes encodedRegionName = 2;
   required bytes familyName = 3;
   repeated string compactionInput = 4;

Modified: hbase/branches/0.95/hbase-protocol/src/main/protobuf/hbase.proto
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-protocol/src/main/protobuf/hbase.proto?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-protocol/src/main/protobuf/hbase.proto (original)
+++ hbase/branches/0.95/hbase-protocol/src/main/protobuf/hbase.proto Tue Apr 30 18:34:58 2013
@@ -301,3 +301,8 @@ message LongMsg {
 message BigDecimalMsg {
   required bytes bigdecimalMsg = 1;
 }
+
+message UUID {
+  required uint64 leastSigBits = 1;
+  required uint64 mostSigBits = 2;
+}

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/protobuf/ReplicationProtbufUtil.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/protobuf/ReplicationProtbufUtil.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/protobuf/ReplicationProtbufUtil.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/protobuf/ReplicationProtbufUtil.java Tue Apr 30 18:34:58 2013
@@ -26,6 +26,8 @@ import org.apache.hadoop.hbase.HConstant
 import org.apache.hadoop.hbase.KeyValue;
 import org.apache.hadoop.hbase.client.AdminProtocol;
 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos;
+import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos;
 import org.apache.hadoop.hbase.regionserver.wal.HLog;
 import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
@@ -47,32 +49,23 @@ public class ReplicationProtbufUtil {
    * @return an array of HLog entries
    */
   public static HLog.Entry[]
-      toHLogEntries(final List<AdminProtos.WALEntry> protoList) {
+      toHLogEntries(final List<AdminProtos.WALEntry> protoList) throws IOException {
     List<HLog.Entry> entries = new ArrayList<HLog.Entry>();
     for (AdminProtos.WALEntry entry: protoList) {
-      AdminProtos.WALEntry.WALKey walKey = entry.getKey();
-      java.util.UUID clusterId = HConstants.DEFAULT_CLUSTER_ID;
-      if (walKey.hasClusterId()) {
-        AdminProtos.UUID protoUuid = walKey.getClusterId();
-        clusterId = new java.util.UUID(
-          protoUuid.getMostSigBits(), protoUuid.getLeastSigBits());
-      }
-      HLogKey key = new HLogKey(walKey.getEncodedRegionName().toByteArray(),
-        walKey.getTableName().toByteArray(), walKey.getLogSequenceNumber(),
-        walKey.getWriteTime(), clusterId);
-      AdminProtos.WALEntry.WALEdit walEdit = entry.getEdit();
+      WALProtos.WALKey walKey = entry.getKey();
+      HLogKey key = new HLogKey(walKey);
       WALEdit edit = new WALEdit();
-      for (ByteString keyValue: walEdit.getKeyValueBytesList()) {
+      for (ByteString keyValue: entry.getKeyValueBytesList()) {
         edit.add(new KeyValue(keyValue.toByteArray()));
       }
-      if (walEdit.getFamilyScopeCount() > 0) {
+      if (walKey.getScopesCount() > 0) {
         TreeMap<byte[], Integer> scopes =
           new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR);
-        for (AdminProtos.WALEntry.WALEdit.FamilyScope scope: walEdit.getFamilyScopeList()) {
+        for (WALProtos.FamilyScope scope: walKey.getScopesList()) {
           scopes.put(scope.getFamily().toByteArray(),
             Integer.valueOf(scope.getScopeType().ordinal()));
         }
-        edit.setScopes(scopes);
+        key.setScopes(scopes);
       }
       entries.add(new HLog.Entry(key, edit));
     }
@@ -105,16 +98,13 @@ public class ReplicationProtbufUtil {
    */
   public static AdminProtos.ReplicateWALEntryRequest
       buildReplicateWALEntryRequest(final HLog.Entry[] entries) {
-    AdminProtos.WALEntry.WALEdit.FamilyScope.Builder scopeBuilder = AdminProtos.WALEntry
-        .WALEdit
-        .FamilyScope
-        .newBuilder();
+    WALProtos.FamilyScope.Builder scopeBuilder = WALProtos.FamilyScope.newBuilder();
     AdminProtos.WALEntry.Builder entryBuilder = AdminProtos.WALEntry.newBuilder();
     AdminProtos.ReplicateWALEntryRequest.Builder builder =
       AdminProtos.ReplicateWALEntryRequest.newBuilder();
     for (HLog.Entry entry: entries) {
       entryBuilder.clear();
-      AdminProtos.WALEntry.WALKey.Builder keyBuilder = entryBuilder.getKeyBuilder();
+      WALProtos.WALKey.Builder keyBuilder = entryBuilder.getKeyBuilder();
       HLogKey key = entry.getKey();
       keyBuilder.setEncodedRegionName(
         ByteString.copyFrom(key.getEncodedRegionName()));
@@ -123,28 +113,24 @@ public class ReplicationProtbufUtil {
       keyBuilder.setWriteTime(key.getWriteTime());
       UUID clusterId = key.getClusterId();
       if (clusterId != null) {
-        AdminProtos.UUID.Builder uuidBuilder = keyBuilder.getClusterIdBuilder();
+        HBaseProtos.UUID.Builder uuidBuilder = keyBuilder.getClusterIdBuilder();
         uuidBuilder.setLeastSigBits(clusterId.getLeastSignificantBits());
         uuidBuilder.setMostSigBits(clusterId.getMostSignificantBits());
       }
       WALEdit edit = entry.getEdit();
-      AdminProtos.WALEntry.WALEdit.Builder editBuilder = entryBuilder.getEditBuilder();
-      NavigableMap<byte[], Integer> scopes = edit.getScopes();
+      NavigableMap<byte[], Integer> scopes = key.getScopes();
       if (scopes != null && !scopes.isEmpty()) {
         for (Map.Entry<byte[], Integer> scope: scopes.entrySet()) {
           scopeBuilder.setFamily(ByteString.copyFrom(scope.getKey()));
-          AdminProtos.WALEntry.WALEdit.ScopeType
-              scopeType = AdminProtos.WALEntry
-              .WALEdit
-              .ScopeType
-              .valueOf(scope.getValue().intValue());
+          WALProtos.ScopeType scopeType =
+              WALProtos.ScopeType.valueOf(scope.getValue().intValue());
           scopeBuilder.setScopeType(scopeType);
-          editBuilder.addFamilyScope(scopeBuilder.build());
+          keyBuilder.addScopes(scopeBuilder.build());
         }
       }
       List<KeyValue> keyValues = edit.getKeyValues();
       for (KeyValue value: keyValues) {
-        editBuilder.addKeyValueBytes(ByteString.copyFrom(
+        entryBuilder.addKeyValueBytes(ByteString.copyFrom(
           value.getBuffer(), value.getOffset(), value.getLength()));
       }
       builder.addEntry(entryBuilder.build());

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java Tue Apr 30 18:34:58 2013
@@ -115,7 +115,7 @@ import org.apache.hadoop.hbase.monitorin
 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse.CompactionState;
 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceCall;
 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
-import org.apache.hadoop.hbase.protobuf.generated.WAL.CompactionDescriptor;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
 import org.apache.hadoop.hbase.regionserver.MultiVersionConsistencyControl.WriteEntry;
 import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext;
 import org.apache.hadoop.hbase.regionserver.wal.HLog;
@@ -2937,7 +2937,7 @@ public class HRegion implements HeapSize
 
               skippedEdits++;
               continue;
-                }
+            }
             // Figure which store the edit is meant for.
             if (store == null || !kv.matchingFamily(store.getFamily().getName())) {
               store = this.stores.get(kv.getFamily());
@@ -3019,7 +3019,8 @@ public class HRegion implements HeapSize
       throws IOException {
     Store store = this.getStore(compaction.getFamilyName().toByteArray());
     if (store == null) {
-      LOG.warn("Found Compaction WAL edit for deleted family:" + Bytes.toString(compaction.getFamilyName().toByteArray()));
+      LOG.warn("Found Compaction WAL edit for deleted family:" +
+          Bytes.toString(compaction.getFamilyName().toByteArray()));
       return;
     }
     store.completeCompactionMarker(compaction);

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HStore.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HStore.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HStore.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HStore.java Tue Apr 30 18:34:58 2013
@@ -63,7 +63,7 @@ import org.apache.hadoop.hbase.io.hfile.
 import org.apache.hadoop.hbase.io.hfile.NoOpDataBlockEncoder;
 import org.apache.hadoop.hbase.monitoring.MonitoredTask;
 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
-import org.apache.hadoop.hbase.protobuf.generated.WAL.CompactionDescriptor;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
 import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext;
 import org.apache.hadoop.hbase.regionserver.compactions.CompactionProgress;
 import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest;

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/Store.java Tue Apr 30 18:34:58 2013
@@ -35,7 +35,7 @@ import org.apache.hadoop.hbase.io.HeapSi
 import org.apache.hadoop.hbase.io.compress.Compression;
 import org.apache.hadoop.hbase.io.hfile.CacheConfig;
 import org.apache.hadoop.hbase.io.hfile.HFileDataBlockEncoder;
-import org.apache.hadoop.hbase.protobuf.generated.WAL.CompactionDescriptor;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
 import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext;
 import org.apache.hadoop.hbase.regionserver.compactions.CompactionProgress;
 import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest;

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/Compressor.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/Compressor.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/Compressor.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/Compressor.java Tue Apr 30 18:34:58 2013
@@ -25,6 +25,7 @@ import java.io.IOException;
 
 import org.apache.hadoop.hbase.HBaseConfiguration;
 import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
 import org.apache.hadoop.hbase.regionserver.wal.HLog;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.io.WritableUtils;
@@ -32,6 +33,7 @@ import org.apache.hadoop.conf.Configurat
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import com.google.common.base.Preconditions;
+import com.google.protobuf.ByteString;
 
 /**
  * A set of static functions for running our custom WAL compression/decompression.
@@ -63,26 +65,31 @@ public class Compressor {
 
   private static void transformFile(Path input, Path output)
       throws IOException {
-    SequenceFileLogReader in = new SequenceFileLogReader();
-    SequenceFileLogWriter out = new SequenceFileLogWriter();
+    Configuration conf = HBaseConfiguration.create();
 
-    try {
-      Configuration conf = HBaseConfiguration.create();
-
-      FileSystem inFS = input.getFileSystem(conf);
-      FileSystem outFS = output.getFileSystem(conf);
+    FileSystem inFS = input.getFileSystem(conf);
+    FileSystem outFS = output.getFileSystem(conf);
 
-      in.init(inFS, input, conf);
-      boolean compress = in.reader.isWALCompressionEnabled();
+    HLog.Reader in = HLogFactory.createReader(inFS, input, conf, null, false);
+    HLog.Writer out = null;
 
+    try {
+      if (!(in instanceof ReaderBase)) {
+        System.err.println("Cannot proceed, invalid reader type: " + in.getClass().getName());
+        return;
+      }
+      boolean compress = ((ReaderBase)in).hasCompression();
       conf.setBoolean(HConstants.ENABLE_WAL_COMPRESSION, !compress);
-      out.init(outFS, output, conf);
+      out = HLogFactory.createWriter(outFS, output, conf);
 
       HLog.Entry e = null;
       while ((e = in.next()) != null) out.append(e);
     } finally {
       in.close();
-      out.close();
+      if (out != null) {
+        out.close();
+        out = null;
+      }
     }
   }
 
@@ -93,6 +100,7 @@ public class Compressor {
    * @param dict the dictionary we use for our read.
    * @return the uncompressed array.
    */
+  @Deprecated
   static byte[] readCompressed(DataInput in, Dictionary dict)
       throws IOException {
     byte status = in.readByte();
@@ -129,6 +137,7 @@ public class Compressor {
    * 
    * @return the length of the uncompressed data
    */
+  @Deprecated
   static int uncompressIntoArray(byte[] to, int offset, DataInput in,
       Dictionary dict) throws IOException {
     byte status = in.readByte();
@@ -167,6 +176,7 @@ public class Compressor {
    * @param out the DataOutput to write into
    * @param dict the dictionary to use for compression
    */
+  @Deprecated
   static void writeCompressed(byte[] data, int offset, int length,
       DataOutput out, Dictionary dict)
       throws IOException {

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/FSHLog.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/FSHLog.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/FSHLog.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/FSHLog.java Tue Apr 30 18:34:58 2013
@@ -527,12 +527,10 @@ class FSHLog implements HLog, Syncable {
           }
         }
         FSHLog.Writer nextWriter = this.createWriterInstance(fs, newPath, conf);
-        // Can we get at the dfsclient outputstream?  If an instance of
-        // SFLW, it'll have done the necessary reflection to get at the
-        // protected field name.
+        // Can we get at the dfsclient outputstream?
         FSDataOutputStream nextHdfsOut = null;
-        if (nextWriter instanceof SequenceFileLogWriter) {
-          nextHdfsOut = ((SequenceFileLogWriter)nextWriter).getWriterFSDataOutputStream();
+        if (nextWriter instanceof ProtobufLogWriter) {
+          nextHdfsOut = ((ProtobufLogWriter)nextWriter).getStream();
         }
 
         Path oldFile = null;
@@ -854,43 +852,6 @@ class FSHLog implements HLog, Syncable {
   }
 
   @Override
-  public long append(HRegionInfo regionInfo, HLogKey logKey, WALEdit logEdit,
-                     HTableDescriptor htd, boolean doSync)
-  throws IOException {
-    if (this.closed) {
-      throw new IOException("Cannot append; log is closed");
-    }
-    long txid = 0;
-    synchronized (updateLock) {
-      long seqNum = obtainSeqNum();
-      logKey.setLogSeqNum(seqNum);
-      // The 'lastSeqWritten' map holds the sequence number of the oldest
-      // write for each region (i.e. the first edit added to the particular
-      // memstore). When the cache is flushed, the entry for the
-      // region being flushed is removed if the sequence number of the flush
-      // is greater than or equal to the value in lastSeqWritten.
-      this.oldestUnflushedSeqNums.putIfAbsent(regionInfo.getEncodedNameAsBytes(),
-        Long.valueOf(seqNum));
-      doWrite(regionInfo, logKey, logEdit, htd);
-      txid = this.unflushedEntries.incrementAndGet();
-      this.numEntries.incrementAndGet();
-      if (htd.isDeferredLogFlush()) {
-        lastDeferredTxid = txid;
-      }
-    }
-
-    // Sync if catalog region, and if not then check if that table supports
-    // deferred log flushing
-    if (doSync &&
-        (regionInfo.isMetaRegion() ||
-        !htd.isDeferredLogFlush())) {
-      // sync txn to file system
-      this.sync(txid);
-    }
-    return txid;
-  }
-
-  @Override
   public void append(HRegionInfo info, byte [] tableName, WALEdit edits,
     final long now, HTableDescriptor htd)
   throws IOException {
@@ -1456,4 +1417,4 @@ class FSHLog implements HLog, Syncable {
       System.exit(-1);
     }
   }
-}
\ No newline at end of file
+}

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLog.java Tue Apr 30 18:34:58 2013
@@ -29,6 +29,7 @@ import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.classification.InterfaceAudience;
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataInputStream;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hbase.HRegionInfo;
@@ -51,7 +52,14 @@ public interface HLog {
   public static final String RECOVERED_LOG_TMPFILE_SUFFIX = ".temp";
 
   public interface Reader {
-    void init(FileSystem fs, Path path, Configuration c) throws IOException;
+
+    /**
+     * @param fs File system.
+     * @param path Path.
+     * @param c Config.
+     * @param s Input stream that may have been pre-opened by the caller; may be null.
+     */
+    void init(FileSystem fs, Path path, Configuration c, FSDataInputStream s) throws IOException;
 
     void close() throws IOException;
 
@@ -235,20 +243,6 @@ public interface HLog {
   public void closeAndDelete() throws IOException;
 
   /**
-   * Append an entry to the log.
-   *
-   * @param regionInfo
-   * @param logEdit
-   * @param logKey
-   * @param doSync
-   *          shall we sync after writing the transaction
-   * @return The txid of this transaction
-   * @throws IOException
-   */
-  public long append(HRegionInfo regionInfo, HLogKey logKey, WALEdit logEdit,
-      HTableDescriptor htd, boolean doSync) throws IOException;
-
-  /**
    * Only used in tests.
    *
    * @param info

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogFactory.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogFactory.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogFactory.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogFactory.java Tue Apr 30 18:34:58 2013
@@ -21,23 +21,26 @@
 package org.apache.hadoop.hbase.regionserver.wal;
 
 import java.io.IOException;
+import java.util.Arrays;
 import java.io.InterruptedIOException;
 import java.util.List;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataInputStream;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hbase.HConstants;
 import org.apache.hadoop.hbase.regionserver.wal.HLog.Reader;
 import org.apache.hadoop.hbase.regionserver.wal.HLog.Writer;
+import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.hbase.util.CancelableProgressable;
 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
 
 public class HLogFactory {
     private static final Log LOG = LogFactory.getLog(HLogFactory.class);
-    
+
     public static HLog createHLog(final FileSystem fs, final Path root, final String logName,
         final Configuration conf) throws IOException {
       return new FSHLog(fs, root, logName, conf);
@@ -60,13 +63,12 @@ public class HLogFactory {
       return new FSHLog(fs, root, logName, HConstants.HREGION_OLDLOGDIR_NAME, 
             conf, listeners, false, prefix, true);
     }
-    
+
     /*
      * WAL Reader
      */
-    
     private static Class<? extends Reader> logReaderClass;
-    
+
     static void resetLogReaderClass() {
       logReaderClass = null;
     }
@@ -85,10 +87,17 @@ public class HLogFactory {
      */
     public static HLog.Reader createReader(final FileSystem fs, final Path path,
         Configuration conf, CancelableProgressable reporter) throws IOException {
-      if (logReaderClass == null) {
+      return createReader(fs, path, conf, reporter, true);
+    }
+
+    public static HLog.Reader createReader(final FileSystem fs, final Path path,
+      Configuration conf, CancelableProgressable reporter, boolean allowCustom)
+        throws IOException {
+      if (allowCustom && (logReaderClass == null)) {
         logReaderClass = conf.getClass("hbase.regionserver.hlog.reader.impl",
-          SequenceFileLogReader.class, Reader.class);
+          ProtobufLogReader.class, Reader.class);
       }
+      Class<? extends Reader> lrClass = allowCustom ? logReaderClass : ProtobufLogReader.class;
 
       try {
         // A hlog file could be under recovery, so it may take several
@@ -99,9 +108,25 @@ public class HLogFactory {
         int nbAttempt = 0;
         while (true) {
           try {
-            HLog.Reader reader = logReaderClass.newInstance();
-            reader.init(fs, path, conf);
-            return reader;
+            if (lrClass != ProtobufLogReader.class) {
+              // User is overriding the WAL reader, let them.
+              HLog.Reader reader = lrClass.newInstance();
+              reader.init(fs, path, conf, null);
+              return reader;
+            } else {
+              FSDataInputStream stream = fs.open(path);
+              // Note that zero-length file will fail to read PB magic, and attempt to create
+              // a non-PB reader and fail the same way existing code expects it to. If we get
+              // rid of the old reader entirely, we need to handle 0-size files differently from
+              // merely non-PB files.
+              byte[] magic = new byte[ProtobufLogReader.PB_WAL_MAGIC.length];
+              boolean isPbWal = (stream.read(magic) == magic.length)
+                  && Arrays.equals(magic, ProtobufLogReader.PB_WAL_MAGIC);
+              HLog.Reader reader =
+                  isPbWal ? new ProtobufLogReader() : new SequenceFileLogReader();
+              reader.init(fs, path, conf, stream);
+              return reader;
+            }
           } catch (IOException e) {
             String msg = e.getMessage();
             if (msg != null && msg.contains("Cannot obtain block length")) {
@@ -139,9 +164,8 @@ public class HLogFactory {
     /*
      * WAL writer
      */
-    
     private static Class<? extends Writer> logWriterClass;
-    
+
     /**
      * Create a writer for the WAL.
      * @return A WAL writer.  Close when done with it.
@@ -153,9 +177,9 @@ public class HLogFactory {
       try {
         if (logWriterClass == null) {
           logWriterClass = conf.getClass("hbase.regionserver.hlog.writer.impl",
-              SequenceFileLogWriter.class, Writer.class);
+              ProtobufLogWriter.class, Writer.class);
         }
-        HLog.Writer writer = (HLog.Writer) logWriterClass.newInstance();
+        HLog.Writer writer = (HLog.Writer)logWriterClass.newInstance();
         writer.init(fs, path, conf);
         return writer;
       } catch (Exception e) {

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogKey.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogKey.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogKey.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogKey.java Tue Apr 30 18:34:58 2013
@@ -22,16 +22,27 @@ import java.io.DataInput;
 import java.io.DataOutput;
 import java.io.EOFException;
 import java.io.IOException;
+import java.nio.ByteBuffer;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.NavigableMap;
+import java.util.TreeMap;
 import java.util.UUID;
 
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.classification.InterfaceAudience;
 import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos.FamilyScope;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos.ScopeType;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.io.WritableComparable;
 import org.apache.hadoop.io.WritableUtils;
 
+import com.google.protobuf.ByteString;
+
 /**
  * A Key for an entry in the change log.
  *
@@ -42,8 +53,12 @@ import org.apache.hadoop.io.WritableUtil
  * <p>Some Transactional edits (START, COMMIT, ABORT) will not have an
  * associated row.
  */
+// TODO: Key and WALEdit are never used separately, or in one-to-many relation, for practical
+//       purposes. They need to be merged into HLogEntry.
 @InterfaceAudience.Private
 public class HLogKey implements WritableComparable<HLogKey> {
+  public static final Log LOG = LogFactory.getLog(HLogKey.class);
+
   // should be < 0 (@see #readFields(DataInput))
   // version 2 supports HLog compression
   enum Version {
@@ -89,16 +104,17 @@ public class HLogKey implements Writable
 
   private UUID clusterId;
 
+  private NavigableMap<byte[], Integer> scopes;
+
   private CompressionContext compressionContext;
 
-  /** Writable Constructor -- Do not use. */
   public HLogKey() {
     this(null, null, 0L, HConstants.LATEST_TIMESTAMP,
         HConstants.DEFAULT_CLUSTER_ID);
   }
 
   /**
-   * Create the log key!
+   * Create the log key for writing to somewhere.
    * We maintain the tablename mainly for debugging purposes.
    * A regionName is always a sub-table object.
    *
@@ -111,11 +127,19 @@ public class HLogKey implements Writable
    */
   public HLogKey(final byte [] encodedRegionName, final byte [] tablename,
       long logSeqNum, final long now, UUID clusterId) {
-    this.encodedRegionName = encodedRegionName;
-    this.tablename = tablename;
     this.logSeqNum = logSeqNum;
     this.writeTime = now;
     this.clusterId = clusterId;
+    this.encodedRegionName = encodedRegionName;
+    this.tablename = tablename;
+  }
+
+  /**
+   * Create HLogKey wrapper around protobuf WAL key; takes care of compression.
+   * @throws IOException Never, as the compression is not enabled.
+   */
+  public HLogKey(WALKey walKey) throws IOException {
+    readFieldsFromPb(walKey, null);
   }
 
   /**
@@ -137,11 +161,7 @@ public class HLogKey implements Writable
 
   /** @return log sequence number */
   public long getLogSeqNum() {
-    return logSeqNum;
-  }
-
-  void setLogSeqNum(long logSeqNum) {
-    this.logSeqNum = logSeqNum;
+    return this.logSeqNum;
   }
 
   /**
@@ -159,8 +179,16 @@ public class HLogKey implements Writable
     return clusterId;
   }
 
+  public NavigableMap<byte[], Integer> getScopes() {
+    return scopes;
+  }
+
+  public void setScopes(NavigableMap<byte[], Integer> scopes) {
+    this.scopes = scopes;
+  }
+
   /**
-   * Set the cluster id of this key
+   * Set the cluster id of this key.
    * @param clusterId
    */
   public void setClusterId(UUID clusterId) {
@@ -213,7 +241,7 @@ public class HLogKey implements Writable
     if (result == 0) {
       if (this.logSeqNum < o.logSeqNum) {
         result = -1;
-      } else if (this.logSeqNum > o.logSeqNum) {
+      } else if (this.logSeqNum  > o.logSeqNum ) {
         result = 1;
       }
       if (result == 0) {
@@ -255,7 +283,9 @@ public class HLogKey implements Writable
   }
 
   @Override
+  @Deprecated
   public void write(DataOutput out) throws IOException {
+    LOG.warn("HLogKey is being serialized to writable - only expected in test code");
     WritableUtils.writeVInt(out, VERSION.code);
     if (compressionContext == null) {
       Bytes.writeByteArray(out, this.encodedRegionName);
@@ -290,6 +320,7 @@ public class HLogKey implements Writable
     // encodes the length of encodedRegionName.
     // If < 0 we just read the version and the next vint is the length.
     // @see Bytes#readByteArray(DataInput)
+    this.scopes = null; // writable HLogKey does not contain scopes
     int len = WritableUtils.readVInt(in);
     if (len < 0) {
       // what we just read was the version
@@ -308,7 +339,7 @@ public class HLogKey implements Writable
       this.encodedRegionName = Compressor.readCompressed(in, compressionContext.regionDict);
       this.tablename = Compressor.readCompressed(in, compressionContext.tableDict);
     }
-    
+
     this.logSeqNum = in.readLong();
     this.writeTime = in.readLong();
     this.clusterId = HConstants.DEFAULT_CLUSTER_ID;
@@ -325,4 +356,62 @@ public class HLogKey implements Writable
       }
     }
   }
+
+  public WALKey.Builder getBuilder(
+      WALCellCodec.ByteStringCompressor compressor) throws IOException {
+    WALKey.Builder builder = WALKey.newBuilder();
+    if (compressionContext == null) {
+      builder.setEncodedRegionName(ByteString.copyFrom(this.encodedRegionName));
+      builder.setTableName(ByteString.copyFrom(this.tablename));
+    } else {
+      builder.setEncodedRegionName(
+          compressor.compress(this.encodedRegionName, compressionContext.regionDict));
+      builder.setTableName(compressor.compress(this.tablename, compressionContext.tableDict));
+    }
+    builder.setLogSequenceNumber(this.logSeqNum);
+    builder.setWriteTime(writeTime);
+    if (this.clusterId != HConstants.DEFAULT_CLUSTER_ID) {
+      builder.setClusterId(HBaseProtos.UUID.newBuilder()
+          .setLeastSigBits(this.clusterId.getLeastSignificantBits())
+          .setMostSigBits(this.clusterId.getMostSignificantBits()));
+    }
+    if (scopes != null) {
+      for (Map.Entry<byte[], Integer> e : scopes.entrySet()) {
+        ByteString family = (compressionContext == null) ? ByteString.copyFrom(e.getKey())
+            : compressor.compress(e.getKey(), compressionContext.familyDict);
+        builder.addScopes(FamilyScope.newBuilder()
+            .setFamily(family).setScopeType(ScopeType.valueOf(e.getValue())));
+      }
+    }
+    return builder;
+  }
+
+  public void readFieldsFromPb(
+      WALKey walKey, WALCellCodec.ByteStringUncompressor uncompressor) throws IOException {
+    if (this.compressionContext != null) {
+      this.encodedRegionName = uncompressor.uncompress(
+          walKey.getEncodedRegionName(), compressionContext.regionDict);
+      this.tablename = uncompressor.uncompress(
+          walKey.getTableName(), compressionContext.tableDict);
+    } else {
+      this.encodedRegionName = walKey.getEncodedRegionName().toByteArray();
+      this.tablename = walKey.getTableName().toByteArray();
+    }
+    this.clusterId = HConstants.DEFAULT_CLUSTER_ID;
+    if (walKey.hasClusterId()) {
+      this.clusterId = new UUID(
+          walKey.getClusterId().getMostSigBits(), walKey.getClusterId().getLeastSigBits());
+    }
+    this.scopes = null;
+    if (walKey.getScopesCount() > 0) {
+      this.scopes = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR);
+      for (FamilyScope scope : walKey.getScopesList()) {
+        byte[] family = (compressionContext == null) ? scope.getFamily().toByteArray() :
+          uncompressor.uncompress(scope.getFamily(), compressionContext.familyDict);
+        this.scopes.put(family, scope.getScopeType().getNumber());
+      }
+    }
+    this.logSeqNum = walKey.getLogSequenceNumber();
+    this.writeTime = walKey.getWriteTime();
+  }
 }

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogUtil.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogUtil.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogUtil.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/HLogUtil.java Tue Apr 30 18:34:58 2013
@@ -36,30 +36,13 @@ import org.apache.hadoop.hbase.HConstant
 import org.apache.hadoop.hbase.HRegionInfo;
 import org.apache.hadoop.hbase.HTableDescriptor;
 import org.apache.hadoop.hbase.ServerName;
-import org.apache.hadoop.hbase.protobuf.generated.WAL.CompactionDescriptor;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
 import org.apache.hadoop.hbase.util.FSUtils;
 
 public class HLogUtil {
   static final Log LOG = LogFactory.getLog(HLogUtil.class);
 
-  @SuppressWarnings("unchecked")
-  public static Class<? extends HLogKey> getKeyClass(Configuration conf) {
-    return (Class<? extends HLogKey>) conf.getClass(
-        "hbase.regionserver.hlog.keyclass", HLogKey.class);
-  }
-
-  public static HLogKey newKey(Configuration conf) throws IOException {
-    Class<? extends HLogKey> keyClass = getKeyClass(conf);
-    try {
-      return keyClass.newInstance();
-    } catch (InstantiationException e) {
-      throw new IOException("cannot create hlog key");
-    } catch (IllegalAccessException e) {
-      throw new IOException("cannot create hlog key");
-    }
-  }
-
   /**
    * Pattern used to validate a HLog file name
    */
@@ -76,52 +59,6 @@ public class HLogUtil {
     return pattern.matcher(filename).matches();
   }
 
-  /*
-   * Get a reader for the WAL.
-   *
-   * @param fs
-   *
-   * @param path
-   *
-   * @param conf
-   *
-   * @return A WAL reader. Close when done with it.
-   *
-   * @throws IOException
-   *
-   * public static HLog.Reader getReader(final FileSystem fs, final Path path,
-   * Configuration conf) throws IOException { try {
-   *
-   * if (logReaderClass == null) {
-   *
-   * logReaderClass = conf.getClass("hbase.regionserver.hlog.reader.impl",
-   * SequenceFileLogReader.class, Reader.class); }
-   *
-   *
-   * HLog.Reader reader = logReaderClass.newInstance(); reader.init(fs, path,
-   * conf); return reader; } catch (IOException e) { throw e; } catch (Exception
-   * e) { throw new IOException("Cannot get log reader", e); } }
-   *
-   * * Get a writer for the WAL.
-   *
-   * @param path
-   *
-   * @param conf
-   *
-   * @return A WAL writer. Close when done with it.
-   *
-   * @throws IOException
-   *
-   * public static HLog.Writer createWriter(final FileSystem fs, final Path
-   * path, Configuration conf) throws IOException { try { if (logWriterClass ==
-   * null) { logWriterClass =
-   * conf.getClass("hbase.regionserver.hlog.writer.impl",
-   * SequenceFileLogWriter.class, Writer.class); } FSHLog.Writer writer =
-   * (FSHLog.Writer) logWriterClass.newInstance(); writer.init(fs, path, conf);
-   * return writer; } catch (Exception e) { throw new
-   * IOException("cannot get log writer", e); } }
-   */
-
   /**
    * Construct the HLog directory name
    *
@@ -285,11 +222,11 @@ public class HLogUtil {
   /**
    * Write the marker that a compaction has succeeded and is about to be committed.
    * This provides info to the HMaster to allow it to recover the compaction if
-   * this regionserver dies in the middle (This part is not yet implemented). It also prevents the compaction from
-   * finishing if this regionserver has already lost its lease on the log.
+   * this regionserver dies in the middle (This part is not yet implemented). It also prevents
+   * the compaction from finishing if this regionserver has already lost its lease on the log.
    */
-  public static void writeCompactionMarker(HLog log, HTableDescriptor htd, HRegionInfo info, final CompactionDescriptor c)
-  throws IOException {
+  public static void writeCompactionMarker(HLog log, HTableDescriptor htd, HRegionInfo info,
+      final CompactionDescriptor c) throws IOException {
     WALEdit e = WALEdit.createCompaction(c);
     log.append(info, c.getTableName().toByteArray(), e,
         EnvironmentEdgeManager.currentTimeMillis(), htd);

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/KeyValueCompression.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/KeyValueCompression.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/KeyValueCompression.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/KeyValueCompression.java Tue Apr 30 18:34:58 2013
@@ -27,12 +27,15 @@ import org.apache.hadoop.hbase.util.Byte
 import org.apache.hadoop.io.WritableUtils;
 
 /**
+ * DO NOT USE. This class is deprecated and should only be used in pre-PB WAL.
+ * 
  * Compression class for {@link KeyValue}s written to the WAL. This is not
  * synchronized, so synchronization should be handled outside.
  * 
  * Class only compresses and uncompresses row keys, family names, and the
  * qualifier. More may be added depending on use patterns.
  */
+@Deprecated
 class KeyValueCompression {
   /**
    * Uncompresses a KeyValue from a DataInput and returns it.

Added: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ProtobufLogReader.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ProtobufLogReader.java?rev=1477762&view=auto
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ProtobufLogReader.java (added)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ProtobufLogReader.java Tue Apr 30 18:34:58 2013
@@ -0,0 +1,173 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hbase.regionserver.wal;
+
+import java.io.EOFException;
+import java.io.IOException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.fs.FSDataInputStream;
+import org.apache.hadoop.hbase.Cell;
+import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.codec.Codec;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALKey;
+import org.apache.hadoop.hbase.util.Bytes;
+
+import com.google.protobuf.InvalidProtocolBufferException;
+
+/**
+ * Reader for protobuf-based WAL.
+ */
+@InterfaceAudience.Private
+public class ProtobufLogReader extends ReaderBase {
+  private static final Log LOG = LogFactory.getLog(ProtobufLogReader.class);
+  static final byte[] PB_WAL_MAGIC = Bytes.toBytes("PWAL");
+
+  private FSDataInputStream inputStream;
+  private Codec.Decoder cellDecoder;
+  private WALCellCodec.ByteStringUncompressor byteStringUncompressor;
+  private boolean hasCompression = false;
+
+  public ProtobufLogReader() {
+    super();
+  }
+
+  @Override
+  public void close() throws IOException {
+    if (this.inputStream != null) {
+      this.inputStream.close();
+      this.inputStream = null;
+    }
+  }
+
+  @Override
+  public long getPosition() throws IOException {
+    return inputStream.getPos();
+  }
+
+  @Override
+  public void reset() throws IOException {
+    initInternal(null, false);
+    initAfterCompression(); // We need a new decoder (at least).
+  }
+
+  @Override
+  protected void initReader(FSDataInputStream stream) throws IOException {
+    initInternal(stream, true);
+  }
+
+  private void initInternal(FSDataInputStream stream, boolean isFirst) throws IOException {
+    close();
+    long expectedPos = PB_WAL_MAGIC.length;
+    if (stream == null) {
+      stream = fs.open(path);
+      stream.seek(expectedPos);
+    }
+    if (stream.getPos() != expectedPos) {
+      throw new IOException("The stream is at invalid position: " + stream.getPos());
+    }
+    // Initialize metadata or, when we reset, just skip the header.
+    WALProtos.WALHeader.Builder builder = WALProtos.WALHeader.newBuilder();
+    boolean hasHeader = builder.mergeDelimitedFrom(stream);
+    if (!hasHeader) {
+      throw new EOFException("Couldn't read WAL PB header");
+    }
+    if (isFirst) {
+      WALProtos.WALHeader header = builder.build();
+      this.hasCompression = header.hasHasCompression() && header.getHasCompression();
+    }
+    this.inputStream = stream;
+
+  }
+
+  @Override
+  protected void initAfterCompression() throws IOException {
+    WALCellCodec codec = new WALCellCodec(this.compressionContext);
+    this.cellDecoder = codec.getDecoder(this.inputStream);
+    if (this.hasCompression) {
+      this.byteStringUncompressor = codec.getByteStringUncompressor();
+    }
+  }
+
+  @Override
+  protected boolean hasCompression() {
+    return this.hasCompression;
+  }
+
+  @Override
+  protected boolean readNext(HLog.Entry entry) throws IOException {
+    WALKey.Builder builder = WALKey.newBuilder();
+    boolean hasNext = false;
+    try {
+      hasNext = builder.mergeDelimitedFrom(inputStream);
+    } catch (InvalidProtocolBufferException ipbe) {
+      LOG.error("Invalid PB while reading WAL, probably an unexpected EOF, ignoring", ipbe);
+    }
+    if (!hasNext) return false;
+    if (!builder.isInitialized()) {
+      // TODO: not clear if we should try to recover from corrupt PB that looks semi-legit.
+      //       If we can get the KV count, we could, theoretically, try to get next record.
+      LOG.error("Partial PB while reading WAL, probably an unexpected EOF, ignoring");
+      return false;
+    }
+    WALKey walKey = builder.build();
+    entry.getKey().readFieldsFromPb(walKey, this.byteStringUncompressor);
+    try {
+      int expectedCells = walKey.getFollowingKvCount();
+      int actualCells = entry.getEdit().readFromCells(cellDecoder, expectedCells);
+      if (expectedCells != actualCells) {
+        throw new EOFException("Unable to read " + expectedCells + " cells, got " + actualCells);
+      }
+    } catch (EOFException ex) {
+      LOG.error("EOF while reading KVs, ignoring", ex);
+      return false;
+    } catch (Exception ex) {
+      IOException realEofEx = extractHiddenEofOrRethrow(ex);
+      LOG.error("EOF while reading KVs, ignoring", realEofEx);
+      return false;
+    }
+    return true;
+  }
+
+  private IOException extractHiddenEofOrRethrow(Exception ex) throws IOException {
+    // There are two problems we are dealing with here. Hadoop stream throws generic exception
+    // for EOF, not EOFException; and scanner further hides it inside RuntimeException.
+    IOException ioEx = null;
+    if (ex instanceof IOException) {
+      ioEx = (IOException)ex;
+    } else if (ex instanceof RuntimeException
+        && ex.getCause() != null && ex.getCause() instanceof IOException) {
+      ioEx = (IOException)ex.getCause();
+    }
+    if (ioEx != null) {
+      if (ioEx.getMessage().contains("EOF")) return ioEx;
+      throw ioEx;
+    }
+    throw new IOException(ex);
+  }
+
+  @Override
+  protected void seekOnFs(long pos) throws IOException {
+    this.inputStream.seek(pos);
+  }
+}

Added: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ProtobufLogWriter.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ProtobufLogWriter.java?rev=1477762&view=auto
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ProtobufLogWriter.java (added)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ProtobufLogWriter.java Tue Apr 30 18:34:58 2013
@@ -0,0 +1,130 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hbase.regionserver.wal;
+
+import java.io.IOException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hbase.HConstants;
+import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.codec.Codec;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos.WALHeader;
+
+/**
+ * Writer for protobuf-based WAL.
+ */
+@InterfaceAudience.Private
+public class ProtobufLogWriter implements HLog.Writer {
+  private final Log LOG = LogFactory.getLog(this.getClass());
+  private FSDataOutputStream output;
+  private Codec.Encoder cellEncoder;
+  private WALCellCodec.ByteStringCompressor compressor;
+
+
+  /** Context used by our wal dictionary compressor.
+   * Null if we're not to do our custom dictionary compression. */
+  private CompressionContext compressionContext;
+
+  public ProtobufLogWriter() {
+    super();
+  }
+
+  @Override
+  public void init(FileSystem fs, Path path, Configuration conf) throws IOException {
+    assert this.output == null;
+    boolean doCompress = conf.getBoolean(HConstants.ENABLE_WAL_COMPRESSION, false);
+    if (doCompress) {
+      try {
+        this.compressionContext = new CompressionContext(LRUDictionary.class);
+      } catch (Exception e) {
+        throw new IOException("Failed to initiate CompressionContext", e);
+      }
+    }
+    int bufferSize = fs.getConf().getInt("io.file.buffer.size", 4096);
+    short replication = (short)conf.getInt(
+        "hbase.regionserver.hlog.replication", fs.getDefaultReplication());
+    long blockSize = conf.getLong("hbase.regionserver.hlog.blocksize", fs.getDefaultBlockSize());
+    output = fs.create(path, true, bufferSize, replication, blockSize);
+    output.write(ProtobufLogReader.PB_WAL_MAGIC);
+    WALHeader.newBuilder().setHasCompression(doCompress).build().writeDelimitedTo(output);
+
+    WALCellCodec codec = new WALCellCodec(this.compressionContext);
+    this.cellEncoder = codec.getEncoder(this.output);
+    if (doCompress) {
+      this.compressor = codec.getByteStringCompressor();
+    }
+    LOG.debug("Writing protobuf WAL; path=" + path + ", compression=" + doCompress);
+  }
+
+  @Override
+  public void append(HLog.Entry entry) throws IOException {
+    entry.setCompressionContext(compressionContext);
+    entry.getKey().getBuilder(compressor).setFollowingKvCount(entry.getEdit().size())
+      .build().writeDelimitedTo(output);
+    for (KeyValue kv : entry.getEdit().getKeyValues()) {
+      // cellEncoder must assume little about the stream, since we write PB and cells in turn.
+      cellEncoder.write(kv);
+    }
+  }
+
+  @Override
+  public void close() throws IOException {
+    if (this.output != null) {
+      try {
+        this.output.close();
+      } catch (NullPointerException npe) {
+        // Can get a NPE coming up from down in DFSClient$DFSOutputStream#close
+        LOG.warn(npe);
+      }
+      this.output = null;
+    }
+  }
+
+  @Override
+  public void sync() throws IOException {
+    try {
+      this.output.flush();
+      this.output.sync();
+    } catch (NullPointerException npe) {
+      // Concurrent close...
+      throw new IOException(npe);
+    }
+  }
+
+  @Override
+  public long getLength() throws IOException {
+    try {
+      return this.output.getPos();
+    } catch (NullPointerException npe) {
+      // Concurrent close...
+      throw new IOException(npe);
+    }
+  }
+
+  public FSDataOutputStream getStream() {
+    return this.output;
+  }
+}

Added: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ReaderBase.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ReaderBase.java?rev=1477762&view=auto
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ReaderBase.java (added)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/ReaderBase.java Tue Apr 30 18:34:58 2013
@@ -0,0 +1,137 @@
+/**
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hbase.regionserver.wal;
+
+import java.io.IOException;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataInputStream;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+
+@InterfaceAudience.Private
+public abstract class ReaderBase implements HLog.Reader {
+  protected Configuration conf;
+  protected FileSystem fs;
+  protected Path path;
+  protected long edit = 0;
+  /**
+   * Compression context to use reading.  Can be null if no compression.
+   */
+  protected CompressionContext compressionContext = null;
+  protected boolean emptyCompressionContext = true;
+
+  /**
+   * Default constructor.
+   */
+  public ReaderBase() {
+  }
+
+  @Override
+  public void init(FileSystem fs, Path path, Configuration conf, FSDataInputStream stream)
+      throws IOException {
+    this.conf = conf;
+    this.path = path;
+    this.fs = fs;
+
+    initReader(stream);
+
+    boolean compression = hasCompression();
+    if (compression) {
+      // If compression is enabled, new dictionaries are created here.
+      try {
+        if (compressionContext == null) {
+          compressionContext = new CompressionContext(LRUDictionary.class);
+        } else {
+          compressionContext.clear();
+        }
+      } catch (Exception e) {
+        throw new IOException("Failed to initialize CompressionContext", e);
+      }
+    }
+    initAfterCompression();
+  }
+
+  @Override
+  public HLog.Entry next() throws IOException {
+    return next(null);
+  }
+
+  @Override
+  public HLog.Entry next(HLog.Entry reuse) throws IOException {
+    HLog.Entry e = reuse;
+    if (e == null) {
+      e = new HLog.Entry(new HLogKey(), new WALEdit());
+    }
+    if (compressionContext != null) {
+      e.setCompressionContext(compressionContext);
+    }
+
+    boolean hasEntry = readNext(e);
+    edit++;
+    if (compressionContext != null && emptyCompressionContext) {
+      emptyCompressionContext = false;
+    }
+    return hasEntry ? e : null;
+  }
+
+
+  @Override
+  public void seek(long pos) throws IOException {
+    if (compressionContext != null && emptyCompressionContext) {
+      while (next() != null) {
+        if (getPosition() == pos) {
+          emptyCompressionContext = false;
+          break;
+        }
+      }
+    }
+    seekOnFs(pos);
+  }
+
+  /**
+   * Initializes the log reader with a particular stream (may be null).
+   * Reader assumes ownership of the stream if not null and may use it. Called once.
+   */
+  protected abstract void initReader(FSDataInputStream stream) throws IOException;
+
+  /**
+   * Initializes the compression after the shared stuff has been initialized. Called once.
+   */
+  protected abstract void initAfterCompression() throws IOException;
+  /**
+   * @return Whether compression is enabled for this log.
+   */
+  protected abstract boolean hasCompression();
+
+  /**
+   * Read next entry.
+   * @param e The entry to read into.
+   * @return Whether there was anything to read.
+   */
+  protected abstract boolean readNext(HLog.Entry e) throws IOException;
+
+  /**
+   * Performs a filesystem-level seek to a certain position in an underlying file.
+   */
+  protected abstract void seekOnFs(long pos) throws IOException;
+
+}

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SequenceFileLogReader.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SequenceFileLogReader.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SequenceFileLogReader.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/SequenceFileLogReader.java Tue Apr 30 18:34:58 2013
@@ -23,6 +23,8 @@ import java.io.FilterInputStream;
 import java.io.IOException;
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
+import java.util.NavigableMap;
+
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
@@ -31,12 +33,24 @@ import org.apache.hadoop.conf.Configurat
 import org.apache.hadoop.fs.FSDataInputStream;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hbase.regionserver.wal.HLog.Entry;
 import org.apache.hadoop.io.SequenceFile;
+import org.apache.hadoop.io.Text;
+import org.apache.hadoop.io.SequenceFile.Metadata;
 
 @InterfaceAudience.Private
-public class SequenceFileLogReader implements HLog.Reader {
+public class SequenceFileLogReader extends ReaderBase {
   private static final Log LOG = LogFactory.getLog(SequenceFileLogReader.class);
 
+  // Legacy stuff from pre-PB WAL metadata.
+  private static final Text WAL_VERSION_KEY = new Text("version");
+  // Let the version be 1.  Let absence of a version meta tag be old, version 0.
+  // Set this version '1' to be the version that introduces compression,
+  // the COMPRESSION_VERSION.
+  private static final int COMPRESSION_VERSION = 1;
+  private static final Text WAL_COMPRESSION_TYPE_KEY = new Text("compression.type");
+  private static final Text DICTIONARY_COMPRESSION_TYPE = new Text("dictionary");
+
   /**
    * Hack just to set the correct file length up in SequenceFile.Reader.
    * See HADOOP-6307.  The below is all about setting the right length on the
@@ -49,7 +63,7 @@ public class SequenceFileLogReader imple
    *         this.end = in.getPos() + length;
    *
    */
-  static class WALReader extends SequenceFile.Reader {
+  private static class WALReader extends SequenceFile.Reader {
 
     WALReader(final FileSystem fs, final Path p, final Configuration c)
     throws IOException {
@@ -65,15 +79,6 @@ public class SequenceFileLogReader imple
     }
 
     /**
-     * Call this method after init() has been executed
-     * 
-     * @return whether WAL compression is enabled
-     */
-    public boolean isWALCompressionEnabled() {
-      return SequenceFileLogWriter.isWALCompressionEnabled(this.getMetadata());
-    }
-
-    /**
      * Override just so can intercept first call to getPos.
      */
     static class WALReaderFSDataInputStream extends FSDataInputStream {
@@ -138,59 +143,12 @@ public class SequenceFileLogReader imple
     }
   }
 
-  Configuration conf;
-  WALReader reader;
-  FileSystem fs;
-
-  // Needed logging exceptions
-  Path path;
-  int edit = 0;
-  long entryStart = 0;
-  boolean emptyCompressionContext = true;
-  /**
-   * Compression context to use reading.  Can be null if no compression.
-   */
-  protected CompressionContext compressionContext = null;
-
-  protected Class<? extends HLogKey> keyClass;
+  // Protected for tests.
+  protected SequenceFile.Reader reader;
+  long entryStart = 0; // needed for logging exceptions
 
-  /**
-   * Default constructor.
-   */
   public SequenceFileLogReader() {
-  }
-
-  /**
-   * This constructor allows a specific HLogKey implementation to override that
-   * which would otherwise be chosen via configuration property.
-   *
-   * @param keyClass
-   */
-  public SequenceFileLogReader(Class<? extends HLogKey> keyClass) {
-    this.keyClass = keyClass;
-  }
-
-  @Override
-  public void init(FileSystem fs, Path path, Configuration conf)
-      throws IOException {
-    this.conf = conf;
-    this.path = path;
-    reader = new WALReader(fs, path, conf);
-    this.fs = fs;
-
-    // If compression is enabled, new dictionaries are created here.
-    boolean compression = reader.isWALCompressionEnabled();
-    if (compression) {
-      try {
-        if (compressionContext == null) {
-          compressionContext = new CompressionContext(LRUDictionary.class);
-        } else {
-          compressionContext.clear();
-        }
-      } catch (Exception e) {
-        throw new IOException("Failed to initialize CompressionContext", e);
-      }
-    }
+    super();
   }
 
   @Override
@@ -206,57 +164,70 @@ public class SequenceFileLogReader imple
   }
 
   @Override
-  public HLog.Entry next() throws IOException {
-    return next(null);
+  public long getPosition() throws IOException {
+    return reader != null ? reader.getPosition() : 0;
   }
 
   @Override
-  public HLog.Entry next(HLog.Entry reuse) throws IOException {
-    this.entryStart = this.reader.getPosition();
-    HLog.Entry e = reuse;
-    if (e == null) {
-      HLogKey key;
-      if (keyClass == null) {
-        key = HLogUtil.newKey(conf);
-      } else {
-        try {
-          key = keyClass.newInstance();
-        } catch (InstantiationException ie) {
-          throw new IOException(ie);
-        } catch (IllegalAccessException iae) {
-          throw new IOException(iae);
-        }
-      }
+  public void reset() throws IOException {
+    // Resetting the reader lets us see newly added data if the file is being written to
+    // We also keep the same compressionContext which was previously populated for this file
+    reader = new WALReader(fs, path, conf);
+  }
+
+  @Override
+  protected void initReader(FSDataInputStream stream) throws IOException {
+    // We don't use the stream because we have to have the magic stream above.
+    if (stream != null) {
+      stream.close();
+    }
+    reset();
+  }
+  
+  @Override
+  protected void initAfterCompression() throws IOException {
+    // Nothing to do here
+  }
+
+  @Override
+  protected boolean hasCompression() {
+    return isWALCompressionEnabled(reader.getMetadata());
+  }
 
-      WALEdit val = new WALEdit();
-      e = new HLog.Entry(key, val);
+  /**
+   * Call this method after init() has been executed
+   * @return whether WAL compression is enabled
+   */
+  static boolean isWALCompressionEnabled(final Metadata metadata) {
+    // Check version is >= VERSION?
+    Text txt = metadata.get(WAL_VERSION_KEY);
+    if (txt == null || Integer.parseInt(txt.toString()) < COMPRESSION_VERSION) {
+      return false;
     }
-    boolean b = false;
+    // Now check that compression type is present.  Currently only one value.
+    txt = metadata.get(WAL_COMPRESSION_TYPE_KEY);
+    return txt != null && txt.equals(DICTIONARY_COMPRESSION_TYPE);
+  }
+
+
+  @Override
+  protected boolean readNext(Entry e) throws IOException {
     try {
-      if (compressionContext != null) {
-        e.setCompressionContext(compressionContext);
+      boolean hasNext = this.reader.next(e.getKey(), e.getEdit());
+      if (!hasNext) return false;
+      // Scopes are probably in WAL edit, move to key
+      NavigableMap<byte[], Integer> scopes = e.getEdit().getAndRemoveScopes();
+      if (scopes != null) {
+        e.getKey().setScopes(scopes);
       }
-      b = this.reader.next(e.getKey(), e.getEdit());
+      return true;
     } catch (IOException ioe) {
       throw addFileInfoToException(ioe);
     }
-    edit++;
-    if (compressionContext != null && emptyCompressionContext) {
-      emptyCompressionContext = false;
-    }
-    return b? e: null;
   }
 
   @Override
-  public void seek(long pos) throws IOException {
-    if (compressionContext != null && emptyCompressionContext) {
-      while (next() != null) {
-        if (getPosition() == pos) {
-          emptyCompressionContext = false;
-          break;
-        }
-      }
-    }
+  protected void seekOnFs(long pos) throws IOException {
     try {
       reader.seek(pos);
     } catch (IOException ioe) {
@@ -264,11 +235,6 @@ public class SequenceFileLogReader imple
     }
   }
 
-  @Override
-  public long getPosition() throws IOException {
-    return reader != null ? reader.getPosition() : 0;
-  }
-
   protected IOException addFileInfoToException(final IOException ioe)
   throws IOException {
     long pos = -1;
@@ -301,11 +267,4 @@ public class SequenceFileLogReader imple
 
     return ioe;
   }
-
-  @Override
-  public void reset() throws IOException {
-    // Resetting the reader lets us see newly added data if the file is being written to
-    // We also keep the same compressionContext which was previously populated for this file
-    reader = new WALReader(fs, path, conf);
-  }
 }

Added: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java?rev=1477762&view=auto
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java (added)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALCellCodec.java Tue Apr 30 18:34:58 2013
@@ -0,0 +1,335 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.hbase.regionserver.wal;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.hadoop.hbase.Cell;
+import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.codec.BaseDecoder;
+import org.apache.hadoop.hbase.codec.BaseEncoder;
+import org.apache.hadoop.hbase.codec.Codec;
+import org.apache.hadoop.hbase.codec.KeyValueCodec;
+import org.apache.hadoop.hbase.util.Bytes;
+
+import com.google.common.base.Preconditions;
+import com.google.protobuf.ByteString;
+
+
+/**
+ * Compression in this class is lifted off Compressor/KeyValueCompression.
+ * This is a pure coincidence... they are independent and don't have to be compatible.
+ */
+public class WALCellCodec implements Codec {
+  private final CompressionContext compression;
+  private final ByteStringUncompressor statelessUncompressor = new ByteStringUncompressor() {
+    @Override
+    public byte[] uncompress(ByteString data, Dictionary dict) throws IOException {
+      return WALCellCodec.uncompressByteString(data, dict);
+    }
+  };
+
+  public WALCellCodec(CompressionContext compression) {
+    this.compression = compression;
+  }
+
+  public interface ByteStringCompressor {
+    ByteString compress(byte[] data, Dictionary dict) throws IOException;
+  }
+
+  public interface ByteStringUncompressor {
+    byte[] uncompress(ByteString data, Dictionary dict) throws IOException;
+  }
+
+  // TODO: it sucks that compression context is in HLog.Entry. It'd be nice if it was here.
+  //       Dictionary could be gotten by enum; initially, based on enum, context would create
+  //       an array of dictionaries.
+  static class BaosAndCompressor extends ByteArrayOutputStream implements ByteStringCompressor {
+    public ByteString toByteString() {
+      return ByteString.copyFrom(this.buf, 0, this.count);
+    }
+
+    @Override
+    public ByteString compress(byte[] data, Dictionary dict) throws IOException {
+      writeCompressed(data, dict);
+      ByteString result = ByteString.copyFrom(this.buf, 0, this.count);
+      reset(); // Only resets the count - we reuse the byte array.
+      return result;
+    }
+
+    private void writeCompressed(byte[] data, Dictionary dict) throws IOException {
+      assert dict != null;
+      short dictIdx = dict.findEntry(data, 0, data.length);
+      if (dictIdx == Dictionary.NOT_IN_DICTIONARY) {
+        write(Dictionary.NOT_IN_DICTIONARY);
+        StreamUtils.writeRawVInt32(this, data.length);
+        write(data, 0, data.length);
+      } else {
+        StreamUtils.writeShort(this, dictIdx);
+      }
+    }
+  }
+
+  private static byte[] uncompressByteString(ByteString bs, Dictionary dict) throws IOException {
+    InputStream in = bs.newInput();
+    byte status = (byte)in.read();
+    if (status == Dictionary.NOT_IN_DICTIONARY) {
+      byte[] arr = new byte[StreamUtils.readRawVarint32(in)];
+      int bytesRead = in.read(arr);
+      if (bytesRead != arr.length) {
+        throw new IOException("Cannot read; wanted " + arr.length + ", but got " + bytesRead);
+      }
+      if (dict != null) dict.addEntry(arr, 0, arr.length);
+      return arr;
+    } else {
+      // Status here is the higher-order byte of index of the dictionary entry.
+      short dictIdx = StreamUtils.toShort(status, (byte)in.read());
+      byte[] entry = dict.getEntry(dictIdx);
+      if (entry == null) {
+        throw new IOException("Missing dictionary entry for index " + dictIdx);
+      }
+      return entry;
+    }
+  }
+
+  static class CompressedKvEncoder extends BaseEncoder {
+    private final CompressionContext compression;
+    public CompressedKvEncoder(OutputStream out, CompressionContext compression) {
+      super(out);
+      this.compression = compression;
+    }
+
+    @Override
+    public void write(Cell cell) throws IOException {
+      if (!(cell instanceof KeyValue)) throw new IOException("Cannot write non-KV cells to WAL");
+      KeyValue kv = (KeyValue)cell;
+      byte[] kvBuffer = kv.getBuffer();
+      int offset = kv.getOffset();
+
+      // We first write the KeyValue infrastructure as VInts.
+      StreamUtils.writeRawVInt32(out, kv.getKeyLength());
+      StreamUtils.writeRawVInt32(out, kv.getValueLength());
+
+      // Write row, qualifier, and family; use dictionary
+      // compression as they're likely to have duplicates.
+      write(kvBuffer, kv.getRowOffset(), kv.getRowLength(), compression.rowDict);
+      write(kvBuffer, kv.getFamilyOffset(), kv.getFamilyLength(), compression.familyDict);
+      write(kvBuffer, kv.getQualifierOffset(), kv.getQualifierLength(), compression.qualifierDict);
+
+      // Write the rest uncompressed.
+      int pos = kv.getTimestampOffset();
+      int remainingLength = kv.getLength() + offset - pos;
+      out.write(kvBuffer, pos, remainingLength);
+
+    }
+
+    private void write(byte[] data, int offset, int length, Dictionary dict) throws IOException {
+      short dictIdx = Dictionary.NOT_IN_DICTIONARY;
+      if (dict != null) {
+        dictIdx = dict.findEntry(data, offset, length);
+      }
+      if (dictIdx == Dictionary.NOT_IN_DICTIONARY) {
+        out.write(Dictionary.NOT_IN_DICTIONARY);
+        StreamUtils.writeRawVInt32(out, length);
+        out.write(data, offset, length);
+      } else {
+        StreamUtils.writeShort(out, dictIdx);
+      }
+    }
+  }
+
+  static class CompressedKvDecoder extends BaseDecoder {
+    private final CompressionContext compression;
+    public CompressedKvDecoder(InputStream in, CompressionContext compression) {
+      super(in);
+      this.compression = compression;
+    }
+
+    @Override
+    protected Cell parseCell() throws IOException {
+      int keylength = StreamUtils.readRawVarint32(in);
+      int vlength = StreamUtils.readRawVarint32(in);
+      int length = KeyValue.KEYVALUE_INFRASTRUCTURE_SIZE + keylength + vlength;
+
+      byte[] backingArray = new byte[length];
+      int pos = 0;
+      pos = Bytes.putInt(backingArray, pos, keylength);
+      pos = Bytes.putInt(backingArray, pos, vlength);
+
+      // the row
+      int elemLen = readIntoArray(backingArray, pos + Bytes.SIZEOF_SHORT, compression.rowDict);
+      checkLength(elemLen, Short.MAX_VALUE);
+      pos = Bytes.putShort(backingArray, pos, (short)elemLen);
+      pos += elemLen;
+
+      // family
+      elemLen = readIntoArray(backingArray, pos + Bytes.SIZEOF_BYTE, compression.familyDict);
+      checkLength(elemLen, Byte.MAX_VALUE);
+      pos = Bytes.putByte(backingArray, pos, (byte)elemLen);
+      pos += elemLen;
+
+      // qualifier
+      elemLen = readIntoArray(backingArray, pos, compression.qualifierDict);
+      pos += elemLen;
+
+      // the rest
+      in.read(backingArray, pos, length - pos);
+      return new KeyValue(backingArray);
+    }
+
+    private int readIntoArray(byte[] to, int offset, Dictionary dict) throws IOException {
+      byte status = (byte)in.read();
+      if (status == Dictionary.NOT_IN_DICTIONARY) {
+        // status byte indicating that data to be read is not in dictionary.
+        // if this isn't in the dictionary, we need to add to the dictionary.
+        int length = StreamUtils.readRawVarint32(in);
+        in.read(to, offset, length);
+        dict.addEntry(to, offset, length);
+        return length;
+      } else {
+        // the status byte also acts as the higher order byte of the dictionary entry.
+        short dictIdx = StreamUtils.toShort(status, (byte)in.read());
+        byte[] entry = dict.getEntry(dictIdx);
+        if (entry == null) {
+          throw new IOException("Missing dictionary entry for index " + dictIdx);
+        }
+        // now we write the uncompressed value.
+        Bytes.putBytes(to, offset, entry, 0, entry.length);
+        return entry.length;
+      }
+    }
+
+    private static void checkLength(int len, int max) throws IOException {
+      if (len < 0 || len > max) {
+        throw new IOException("Invalid length for compresesed portion of keyvalue: " + len);
+      }
+    }
+  }
+
+  public class EnsureKvEncoder extends KeyValueCodec.KeyValueEncoder {
+    public EnsureKvEncoder(OutputStream out) {
+      super(out);
+    }
+    @Override
+    public void write(Cell cell) throws IOException {
+      if (!(cell instanceof KeyValue)) throw new IOException("Cannot write non-KV cells to WAL");
+      super.write(cell);
+    }
+  }
+
+  @Override
+  public Decoder getDecoder(InputStream is) {
+    return (compression == null)
+        ? new KeyValueCodec.KeyValueDecoder(is) : new CompressedKvDecoder(is, compression);
+  }
+
+  @Override
+  public Encoder getEncoder(OutputStream os) {
+    return (compression == null)
+        ? new EnsureKvEncoder(os) : new CompressedKvEncoder(os, compression);
+  }
+
+  public ByteStringCompressor getByteStringCompressor() {
+    // TODO: ideally this should also encapsulate compressionContext
+    return new BaosAndCompressor();
+  }
+
+  public ByteStringUncompressor getByteStringUncompressor() {
+    // TODO: ideally this should also encapsulate compressionContext
+    return this.statelessUncompressor;
+  }
+
+  /**
+   * It seems like as soon as somebody sets himself to the task of creating VInt encoding,
+   * his mind blanks out for a split-second and he starts the work by wrapping it in the
+   * most convoluted interface he can come up with. Custom streams that allocate memory,
+   * DataOutput that is only used to write single bytes... We operate on simple streams.
+   * Thus, we are going to have a simple implementation copy-pasted from protobuf Coded*Stream.
+   */
+  private static class StreamUtils {
+    public static int computeRawVarint32Size(final int value) {
+      if ((value & (0xffffffff <<  7)) == 0) return 1;
+      if ((value & (0xffffffff << 14)) == 0) return 2;
+      if ((value & (0xffffffff << 21)) == 0) return 3;
+      if ((value & (0xffffffff << 28)) == 0) return 4;
+      return 5;
+    }
+
+    static void writeRawVInt32(OutputStream output, int value) throws IOException {
+      assert value >= 0;
+      while (true) {
+        if ((value & ~0x7F) == 0) {
+          output.write(value);
+          return;
+        } else {
+          output.write((value & 0x7F) | 0x80);
+          value >>>= 7;
+        }
+      }
+    }
+
+    static int readRawVarint32(InputStream input) throws IOException {
+      byte tmp = (byte)input.read();
+      if (tmp >= 0) {
+        return tmp;
+      }
+      int result = tmp & 0x7f;
+      if ((tmp = (byte)input.read()) >= 0) {
+        result |= tmp << 7;
+      } else {
+        result |= (tmp & 0x7f) << 7;
+        if ((tmp = (byte)input.read()) >= 0) {
+          result |= tmp << 14;
+        } else {
+          result |= (tmp & 0x7f) << 14;
+          if ((tmp = (byte)input.read()) >= 0) {
+            result |= tmp << 21;
+          } else {
+            result |= (tmp & 0x7f) << 21;
+            result |= (tmp = (byte)input.read()) << 28;
+            if (tmp < 0) {
+              // Discard upper 32 bits.
+              for (int i = 0; i < 5; i++) {
+                if (input.read() >= 0) {
+                  return result;
+                }
+              }
+              throw new IOException("Malformed varint");
+            }
+          }
+        }
+      }
+      return result;
+    }
+
+    static short toShort(byte hi, byte lo) {
+      short s = (short) (((hi & 0xFF) << 8) | (lo & 0xFF));
+      Preconditions.checkArgument(s >= 0);
+      return s;
+    }
+
+    static void writeShort(OutputStream out, short v) throws IOException {
+      Preconditions.checkArgument(v >= 0);
+      out.write((byte)(0xff & (v >> 8)));
+      out.write((byte)(0xff & v));
+    }
+  }
+}

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALEdit.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALEdit.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALEdit.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/WALEdit.java Tue Apr 30 18:34:58 2013
@@ -26,14 +26,19 @@ import java.util.List;
 import java.util.NavigableMap;
 import java.util.TreeMap;
 
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.classification.InterfaceAudience;
-import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.codec.Codec;
 import org.apache.hadoop.hbase.io.HeapSize;
-import org.apache.hadoop.hbase.protobuf.generated.WAL.CompactionDescriptor;
+import org.apache.hadoop.hbase.Cell;
+import org.apache.hadoop.hbase.KeyValue;
+import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
 import org.apache.hadoop.hbase.util.Bytes;
 import org.apache.hadoop.hbase.util.ClassSize;
 import org.apache.hadoop.io.Writable;
 
+
 /**
  * WALEdit: Used in HBase's transaction log (WAL) to represent
  * the collection of edits (KeyValue objects) corresponding to a
@@ -70,15 +75,19 @@ import org.apache.hadoop.io.Writable;
  */
 @InterfaceAudience.Private
 public class WALEdit implements Writable, HeapSize {
-  // TODO: Make it so user cannot make a cf w/ this name.  Make the illegal cf names.  Ditto for row.
+  public static final Log LOG = LogFactory.getLog(WALEdit.class);
+
+  // TODO: Get rid of this; see HBASE-8457
   public static final byte [] METAFAMILY = Bytes.toBytes("METAFAMILY");
   static final byte [] METAROW = Bytes.toBytes("METAROW");
   static final byte[] COMPLETE_CACHE_FLUSH = Bytes.toBytes("HBASE::CACHEFLUSH");
   static final byte[] COMPACTION = Bytes.toBytes("HBASE::COMPACTION");
-
   private final int VERSION_2 = -1;
 
   private final ArrayList<KeyValue> kvs = new ArrayList<KeyValue>();
+
+  // Only here for legacy writable deserialization
+  @Deprecated
   private NavigableMap<byte[], Integer> scopes;
 
   private CompressionContext compressionContext;
@@ -115,15 +124,10 @@ public class WALEdit implements Writable
     return kvs;
   }
 
-  public NavigableMap<byte[], Integer> getScopes() {
-    return scopes;
-  }
-
-
-  public void setScopes (NavigableMap<byte[], Integer> scopes) {
-    // We currently process the map outside of WALEdit,
-    // TODO revisit when replication is part of core
-    this.scopes = scopes;
+  public NavigableMap<byte[], Integer> getAndRemoveScopes() {
+    NavigableMap<byte[], Integer> result = scopes;
+    scopes = null;
+    return result;
   }
 
   public void readFields(DataInput in) throws IOException {
@@ -141,7 +145,7 @@ public class WALEdit implements Writable
           this.add(KeyValueCompression.readKV(in, compressionContext));
         } else {
           this.add(KeyValue.create(in));
-    	  }
+        }
       }
       int numFamilies = in.readInt();
       if (numFamilies > 0) {
@@ -159,10 +163,10 @@ public class WALEdit implements Writable
       // read is actually the length of a single KeyValue
       this.add(KeyValue.create(versionOrLength, in));
     }
-
   }
 
   public void write(DataOutput out) throws IOException {
+    LOG.warn("WALEdit is being serialized to writable - only expected in test code");
     out.writeInt(VERSION_2);
     out.writeInt(kvs.size());
     // We interleave the two lists for code simplicity
@@ -184,6 +188,24 @@ public class WALEdit implements Writable
     }
   }
 
+  /**
+   * Reads WALEdit from cells.
+   * @param cellDecoder Cell decoder.
+   * @param expectedCount Expected cell count.
+   * @return Number of KVs read.
+   */
+  public int readFromCells(Codec.Decoder cellDecoder, int expectedCount) throws IOException {
+    kvs.clear();
+    while (kvs.size() < expectedCount && cellDecoder.advance()) {
+      Cell cell = cellDecoder.current();
+      if (!(cell instanceof KeyValue)) {
+        throw new IOException("WAL edit only supports KVs as cells");
+      }
+      kvs.add((KeyValue)cell);
+    }
+    return kvs.size();
+  }
+
   public long heapSize() {
     long ret = 0;
     for (KeyValue kv : kvs) {
@@ -234,4 +256,5 @@ public class WALEdit implements Writable
     }
     return null;
   }
-}
\ No newline at end of file
+}
+

Modified: hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/replication/regionserver/Replication.java
URL: http://svn.apache.org/viewvc/hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/replication/regionserver/Replication.java?rev=1477762&r1=1477761&r2=1477762&view=diff
==============================================================================
--- hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/replication/regionserver/Replication.java (original)
+++ hbase/branches/0.95/hbase-server/src/main/java/org/apache/hadoop/hbase/replication/regionserver/Replication.java Tue Apr 30 18:34:58 2013
@@ -215,7 +215,7 @@ public class Replication implements WALA
       }
     }
     if (!scopes.isEmpty()) {
-      logEdit.setScopes(scopes);
+      logKey.setScopes(scopes);
     }
   }