001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.wal;
019
020import java.io.IOException;
021import java.util.ArrayList;
022import java.util.List;
023import java.util.Map;
024import java.util.Set;
025import java.util.TreeSet;
026import org.apache.hadoop.hbase.Cell;
027import org.apache.hadoop.hbase.CellUtil;
028import org.apache.hadoop.hbase.HBaseInterfaceAudience;
029import org.apache.hadoop.hbase.KeyValue;
030import org.apache.hadoop.hbase.PrivateCellUtil;
031import org.apache.hadoop.hbase.client.RegionInfo;
032import org.apache.hadoop.hbase.codec.Codec;
033import org.apache.hadoop.hbase.io.HeapSize;
034import org.apache.hadoop.hbase.util.Bytes;
035import org.apache.hadoop.hbase.util.ClassSize;
036import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
037import org.apache.yetus.audience.InterfaceAudience;
038
039import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos;
040import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.CompactionDescriptor;
041import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.FlushDescriptor;
042import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.RegionEventDescriptor;
043
044/**
045 * Used in HBase's transaction log (WAL) to represent a collection of edits (Cell/KeyValue objects)
046 * that came in as a single transaction. All the edits for a given transaction are written out as a
047 * single record, in PB format, followed (optionally) by Cells written via the WALCellEncoder.
048 * <p>
049 * This class is LimitedPrivate for CPs to read-only. The {@link #add} methods are classified as
050 * private methods, not for use by CPs.
051 * </p>
052 * <p>
053 * A particular WALEdit 'type' is the 'meta' type used to mark key operational events in the WAL
054 * such as compaction, flush, or region open. These meta types do not traverse hbase memstores. They
055 * are edits made by the hbase system rather than edit data submitted by clients. They only show in
056 * the WAL. These 'Meta' types have not been formally specified (or made into an explicit class
057 * type). They evolved organically. HBASE-8457 suggests codifying a WALEdit 'type' by adding a type
058 * field to WALEdit that gets serialized into the WAL. TODO. Would have to work on the
059 * consumption-side. Reading WALs on replay we seem to consume a Cell-at-a-time rather than by
060 * WALEdit. We are already in the below going out of our way to figure particular types -- e.g. if a
061 * compaction, replay, or close meta Marker -- during normal processing so would make sense to do
062 * this. Current system is an awkward marking of Cell columnfamily as {@link #METAFAMILY} and then
063 * setting qualifier based off meta edit type. For replay-time where we read Cell-at-a-time, there
064 * are utility methods below for figuring meta type. See also
065 * {@link #createBulkLoadEvent(RegionInfo, WALProtos.BulkLoadDescriptor)}, etc., for where we create
066 * meta WALEdit instances.
067 * </p>
068 * <p>
069 * WALEdit will accumulate a Set of all column family names referenced by the Cells
070 * {@link #add(Cell)}'d. This is an optimization. Usually when loading a WALEdit, we have the column
071 * family name to-hand.. just shove it into the WALEdit if available. Doing this, we can save on a
072 * parse of each Cell to figure column family down the line when we go to add the WALEdit to the WAL
073 * file. See the hand-off in FSWALEntry Constructor.
074 * @see WALKey
075 */
076// TODO: Do not expose this class to Coprocessors. It has set methods. A CP might meddle.
077@InterfaceAudience.LimitedPrivate({ HBaseInterfaceAudience.REPLICATION,
078  HBaseInterfaceAudience.COPROC })
079public class WALEdit implements HeapSize {
080  // Below defines are for writing WALEdit 'meta' Cells..
081  // TODO: Get rid of this system of special 'meta' Cells. See HBASE-8457. It suggests
082  // adding a type to WALEdit itself for use denoting meta Edits and their types.
083  public static final byte[] METAFAMILY = Bytes.toBytes("METAFAMILY");
084
085  /**
086   * @deprecated Since 2.3.0. Not used.
087   */
088  @Deprecated
089  public static final byte[] METAROW = Bytes.toBytes("METAROW");
090
091  /**
092   * @deprecated Since 2.3.0. Make it protected, internal-use only. Use
093   *             {@link #isCompactionMarker(Cell)}
094   */
095  @Deprecated
096  @InterfaceAudience.Private
097  public static final byte[] COMPACTION = Bytes.toBytes("HBASE::COMPACTION");
098
099  /**
100   * @deprecated Since 2.3.0. Make it protected, internal-use only.
101   */
102  @Deprecated
103  @InterfaceAudience.Private
104  public static final byte[] FLUSH = Bytes.toBytes("HBASE::FLUSH");
105
106  /**
107   * Qualifier for region event meta 'Marker' WALEdits start with the {@link #REGION_EVENT_PREFIX}
108   * prefix ('HBASE::REGION_EVENT::'). After the prefix, we note the type of the event which we get
109   * from the RegionEventDescriptor protobuf instance type (A RegionEventDescriptor protobuf
110   * instance is written as the meta Marker Cell value). Adding a type suffix means we do not have
111   * to deserialize the protobuf to figure out what type of event this is.. .just read the qualifier
112   * suffix. For example, a close region event descriptor will have a qualifier of
113   * HBASE::REGION_EVENT::REGION_CLOSE. See WAL.proto and the EventType in RegionEventDescriptor
114   * protos for all possible event types.
115   */
116  private static final String REGION_EVENT_STR = "HBASE::REGION_EVENT";
117  private static final String REGION_EVENT_PREFIX_STR = REGION_EVENT_STR + "::";
118  private static final byte[] REGION_EVENT_PREFIX = Bytes.toBytes(REGION_EVENT_PREFIX_STR);
119
120  /**
121   * @deprecated Since 2.3.0. Remove. Not for external use. Not used.
122   */
123  @Deprecated
124  public static final byte[] REGION_EVENT = Bytes.toBytes(REGION_EVENT_STR);
125
126  /**
127   * We use this define figuring if we are carrying a close event.
128   */
129  private static final byte[] REGION_EVENT_CLOSE =
130    createRegionEventDescriptorQualifier(RegionEventDescriptor.EventType.REGION_CLOSE);
131
132  @InterfaceAudience.Private
133  public static final byte[] BULK_LOAD = Bytes.toBytes("HBASE::BULK_LOAD");
134
135  /**
136   * Periodically {@link org.apache.hadoop.hbase.replication.regionserver.ReplicationMarkerChore}
137   * will create marker edits with family as {@link WALEdit#METAFAMILY} and
138   * {@link WALEdit#REPLICATION_MARKER} as qualifier and an empty value.
139   * org.apache.hadoop.hbase.replication.regionserver.ReplicationSourceWALReader will populate the
140   * Replication Marker edit with region_server_name, wal_name and wal_offset encoded in
141   * {@link org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.ReplicationMarkerDescriptor}
142   * object. {@link org.apache.hadoop.hbase.replication.regionserver.Replication} will change the
143   * REPLICATION_SCOPE for this edit to GLOBAL so that it can replicate. On the sink cluster,
144   * {@link org.apache.hadoop.hbase.replication.regionserver.ReplicationSink} will convert the
145   * ReplicationMarkerDescriptor into a Put mutation to REPLICATION_SINK_TRACKER_TABLE_NAME_STR
146   * table.
147   */
148  @InterfaceAudience.Private
149  public static final byte[] REPLICATION_MARKER = Bytes.toBytes("HBASE::REPLICATION_MARKER");
150
151  private final transient boolean replay;
152
153  private ArrayList<Cell> cells;
154
155  /**
156   * All the Cell families in <code>cells</code>. Updated by {@link #add(Cell)} and
157   * {@link #add(Map)}. This Set is passed to the FSWALEntry so it does not have to recalculate the
158   * Set of families in a transaction; makes for a bunch of CPU savings.
159   */
160  private Set<byte[]> families = null;
161
162  public WALEdit() {
163    this(1, false);
164  }
165
166  /**
167   * @deprecated since 2.0.1 and will be removed in 4.0.0. Use {@link #WALEdit(int, boolean)}
168   *             instead.
169   * @see #WALEdit(int, boolean)
170   * @see <a href="https://issues.apache.org/jira/browse/HBASE-20781">HBASE-20781</a>
171   */
172  @Deprecated
173  public WALEdit(boolean replay) {
174    this(1, replay);
175  }
176
177  /**
178   * @deprecated since 2.0.1 and will be removed in 4.0.0. Use {@link #WALEdit(int, boolean)}
179   *             instead.
180   * @see #WALEdit(int, boolean)
181   * @see <a href="https://issues.apache.org/jira/browse/HBASE-20781">HBASE-20781</a>
182   */
183  @Deprecated
184  public WALEdit(int cellCount) {
185    this(cellCount, false);
186  }
187
188  /**
189   * @param cellCount Pass so can pre-size the WALEdit. Optimization.
190   */
191  public WALEdit(int cellCount, boolean isReplay) {
192    this.replay = isReplay;
193    cells = new ArrayList<>(cellCount);
194  }
195
196  private Set<byte[]> getOrCreateFamilies() {
197    if (this.families == null) {
198      this.families = new TreeSet<>(Bytes.BYTES_COMPARATOR);
199    }
200    return this.families;
201  }
202
203  /**
204   * For use by FSWALEntry ONLY. An optimization.
205   * @return All families in {@link #getCells()}; may be null.
206   */
207  public Set<byte[]> getFamilies() {
208    return this.families;
209  }
210
211  /**
212   * @return True is <code>f</code> is {@link #METAFAMILY}
213   * @deprecated Since 2.3.0. Do not expose. Make protected.
214   */
215  @Deprecated
216  public static boolean isMetaEditFamily(final byte[] f) {
217    return Bytes.equals(METAFAMILY, f);
218  }
219
220  /**
221   * Replaying WALs can read Cell-at-a-time so need this method in those cases.
222   */
223  public static boolean isMetaEditFamily(Cell cell) {
224    return CellUtil.matchingFamily(cell, METAFAMILY);
225  }
226
227  /**
228   * @return True if this is a meta edit; has one edit only and its columnfamily is
229   *         {@link #METAFAMILY}.
230   */
231  public boolean isMetaEdit() {
232    return this.families != null && this.families.size() == 1 && this.families.contains(METAFAMILY);
233  }
234
235  /**
236   * @return True when current WALEdit is created by log replay. Replication skips WALEdits from
237   *         replay.
238   */
239  public boolean isReplay() {
240    return this.replay;
241  }
242
243  @InterfaceAudience.Private
244  public WALEdit add(Cell cell, byte[] family) {
245    getOrCreateFamilies().add(family);
246    return addCell(cell);
247  }
248
249  @InterfaceAudience.Private
250  public WALEdit add(Cell cell) {
251    // We clone Family each time we add a Cell. Expensive but safe. For CPU savings, use
252    // add(Map) or add(Cell, family).
253    return add(cell, CellUtil.cloneFamily(cell));
254  }
255
256  public boolean isEmpty() {
257    return cells.isEmpty();
258  }
259
260  public int size() {
261    return cells.size();
262  }
263
264  public ArrayList<Cell> getCells() {
265    return cells;
266  }
267
268  /**
269   * This is not thread safe. This will change the WALEdit and shouldn't be used unless you are sure
270   * that nothing else depends on the contents being immutable.
271   * @param cells the list of cells that this WALEdit now contains.
272   */
273  @InterfaceAudience.Private
274  // Used by replay.
275  public void setCells(ArrayList<Cell> cells) {
276    this.cells = cells;
277    this.families = null;
278  }
279
280  /**
281   * Reads WALEdit from cells.
282   * @param cellDecoder   Cell decoder.
283   * @param expectedCount Expected cell count.
284   * @return Number of KVs read.
285   */
286  public int readFromCells(Codec.Decoder cellDecoder, int expectedCount) throws IOException {
287    cells.clear();
288    cells.ensureCapacity(expectedCount);
289    while (cells.size() < expectedCount && cellDecoder.advance()) {
290      add(cellDecoder.current());
291    }
292    return cells.size();
293  }
294
295  @Override
296  public long heapSize() {
297    long ret = ClassSize.ARRAYLIST;
298    for (Cell cell : cells) {
299      ret += cell.heapSize();
300    }
301    return ret;
302  }
303
304  public long estimatedSerializedSizeOf() {
305    long ret = 0;
306    for (Cell cell : cells) {
307      ret += PrivateCellUtil.estimatedSerializedSizeOf(cell);
308    }
309    return ret;
310  }
311
312  @Override
313  public String toString() {
314    StringBuilder sb = new StringBuilder();
315
316    sb.append("[#edits: ").append(cells.size()).append(" = <");
317    for (Cell cell : cells) {
318      sb.append(cell);
319      sb.append("; ");
320    }
321    sb.append(">]");
322    return sb.toString();
323  }
324
325  public static WALEdit createFlushWALEdit(RegionInfo hri, FlushDescriptor f) {
326    KeyValue kv = new KeyValue(getRowForRegion(hri), METAFAMILY, FLUSH,
327      EnvironmentEdgeManager.currentTime(), f.toByteArray());
328    return new WALEdit().add(kv, METAFAMILY);
329  }
330
331  public static FlushDescriptor getFlushDescriptor(Cell cell) throws IOException {
332    return CellUtil.matchingColumn(cell, METAFAMILY, FLUSH)
333      ? FlushDescriptor.parseFrom(CellUtil.cloneValue(cell))
334      : null;
335  }
336
337  /**
338   * @return A meta Marker WALEdit that has a single Cell whose value is the passed in
339   *         <code>regionEventDesc</code> serialized and whose row is this region, columnfamily is
340   *         {@link #METAFAMILY} and qualifier is {@link #REGION_EVENT_PREFIX} +
341   *         {@link RegionEventDescriptor#getEventType()}; for example
342   *         HBASE::REGION_EVENT::REGION_CLOSE.
343   */
344  public static WALEdit createRegionEventWALEdit(RegionInfo hri,
345    RegionEventDescriptor regionEventDesc) {
346    return createRegionEventWALEdit(getRowForRegion(hri), regionEventDesc);
347  }
348
349  @InterfaceAudience.Private
350  public static WALEdit createRegionEventWALEdit(byte[] rowForRegion,
351    RegionEventDescriptor regionEventDesc) {
352    KeyValue kv = new KeyValue(rowForRegion, METAFAMILY,
353      createRegionEventDescriptorQualifier(regionEventDesc.getEventType()),
354      EnvironmentEdgeManager.currentTime(), regionEventDesc.toByteArray());
355    return new WALEdit().add(kv, METAFAMILY);
356  }
357
358  /**
359   * @return Cell qualifier for the passed in RegionEventDescriptor Type; e.g. we'll return
360   *         something like a byte array with HBASE::REGION_EVENT::REGION_OPEN in it.
361   */
362  @InterfaceAudience.Private
363  public static byte[] createRegionEventDescriptorQualifier(RegionEventDescriptor.EventType t) {
364    return Bytes.toBytes(REGION_EVENT_PREFIX_STR + t.toString());
365  }
366
367  /**
368   * Public so can be accessed from regionserver.wal package.
369   * @return True if this is a Marker Edit and it is a RegionClose type.
370   */
371  public boolean isRegionCloseMarker() {
372    return isMetaEdit() && PrivateCellUtil.matchingQualifier(this.cells.get(0), REGION_EVENT_CLOSE,
373      0, REGION_EVENT_CLOSE.length);
374  }
375
376  /**
377   * @return Returns a RegionEventDescriptor made by deserializing the content of the passed in
378   *         <code>cell</code>, IFF the <code>cell</code> is a RegionEventDescriptor type WALEdit.
379   */
380  public static RegionEventDescriptor getRegionEventDescriptor(Cell cell) throws IOException {
381    return CellUtil.matchingColumnFamilyAndQualifierPrefix(cell, METAFAMILY, REGION_EVENT_PREFIX)
382      ? RegionEventDescriptor.parseFrom(CellUtil.cloneValue(cell))
383      : null;
384  }
385
386  /** Returns A Marker WALEdit that has <code>c</code> serialized as its value */
387  public static WALEdit createCompaction(final RegionInfo hri, final CompactionDescriptor c) {
388    byte[] pbbytes = c.toByteArray();
389    KeyValue kv = new KeyValue(getRowForRegion(hri), METAFAMILY, COMPACTION,
390      EnvironmentEdgeManager.currentTime(), pbbytes);
391    return new WALEdit().add(kv, METAFAMILY); // replication scope null so this won't be replicated
392  }
393
394  public static byte[] getRowForRegion(RegionInfo hri) {
395    byte[] startKey = hri.getStartKey();
396    if (startKey.length == 0) {
397      // empty row key is not allowed in mutations because it is both the start key and the end key
398      // we return the smallest byte[] that is bigger (in lex comparison) than byte[0].
399      return new byte[] { 0 };
400    }
401    return startKey;
402  }
403
404  /**
405   * Deserialized and returns a CompactionDescriptor is the KeyValue contains one.
406   * @param kv the key value
407   * @return deserialized CompactionDescriptor or null.
408   */
409  public static CompactionDescriptor getCompaction(Cell kv) throws IOException {
410    return isCompactionMarker(kv) ? CompactionDescriptor.parseFrom(CellUtil.cloneValue(kv)) : null;
411  }
412
413  /**
414   * Returns true if the given cell is a serialized {@link CompactionDescriptor}
415   * @see #getCompaction(Cell)
416   */
417  public static boolean isCompactionMarker(Cell cell) {
418    return CellUtil.matchingColumn(cell, METAFAMILY, COMPACTION);
419  }
420
421  /**
422   * Create a bulk loader WALEdit
423   * @param hri                The RegionInfo for the region in which we are bulk loading
424   * @param bulkLoadDescriptor The descriptor for the Bulk Loader
425   * @return The WALEdit for the BulkLoad
426   */
427  public static WALEdit createBulkLoadEvent(RegionInfo hri,
428    WALProtos.BulkLoadDescriptor bulkLoadDescriptor) {
429    KeyValue kv = new KeyValue(getRowForRegion(hri), METAFAMILY, BULK_LOAD,
430      EnvironmentEdgeManager.currentTime(), bulkLoadDescriptor.toByteArray());
431    return new WALEdit().add(kv, METAFAMILY);
432  }
433
434  /**
435   * Deserialized and returns a BulkLoadDescriptor from the passed in Cell
436   * @param cell the key value
437   * @return deserialized BulkLoadDescriptor or null.
438   */
439  public static WALProtos.BulkLoadDescriptor getBulkLoadDescriptor(Cell cell) throws IOException {
440    return CellUtil.matchingColumn(cell, METAFAMILY, BULK_LOAD)
441      ? WALProtos.BulkLoadDescriptor.parseFrom(CellUtil.cloneValue(cell))
442      : null;
443  }
444
445  /**
446   * Append the given map of family->edits to a WALEdit data structure. This does not write to the
447   * WAL itself. Note that as an optimization, we will stamp the Set of column families into the
448   * WALEdit to save on our having to calculate column families subsequently down in the actual WAL
449   * writing.
450   * @param familyMap map of family->edits
451   */
452  public void add(Map<byte[], List<Cell>> familyMap) {
453    for (Map.Entry<byte[], List<Cell>> e : familyMap.entrySet()) {
454      // 'foreach' loop NOT used. See HBASE-12023 "...creates too many iterator objects."
455      int listSize = e.getValue().size();
456      // Add all Cells first and then at end, add the family rather than call {@link #add(Cell)}
457      // and have it clone family each time. Optimization!
458      for (int i = 0; i < listSize; i++) {
459        addCell(e.getValue().get(i));
460      }
461      addFamily(e.getKey());
462    }
463  }
464
465  private void addFamily(byte[] family) {
466    getOrCreateFamilies().add(family);
467  }
468
469  private WALEdit addCell(Cell cell) {
470    this.cells.add(cell);
471    return this;
472  }
473
474  /**
475   * Creates a replication tracker edit with {@link #METAFAMILY} family and
476   * {@link #REPLICATION_MARKER} qualifier and has null value.
477   * @param rowKey    rowkey
478   * @param timestamp timestamp
479   */
480  public static WALEdit createReplicationMarkerEdit(byte[] rowKey, long timestamp) {
481    KeyValue kv =
482      new KeyValue(rowKey, METAFAMILY, REPLICATION_MARKER, timestamp, KeyValue.Type.Put);
483    return new WALEdit().add(kv);
484  }
485
486  /**
487   * Checks whether this edit is a replication marker edit.
488   * @param edit edit
489   * @return true if the cell within an edit has column = METAFAMILY and qualifier =
490   *         REPLICATION_MARKER, false otherwise
491   */
492  public static boolean isReplicationMarkerEdit(WALEdit edit) {
493    // Check just the first cell from the edit. ReplicationMarker edit will have only 1 cell.
494    return edit.getCells().size() == 1
495      && CellUtil.matchingColumn(edit.getCells().get(0), METAFAMILY, REPLICATION_MARKER);
496  }
497}