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