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.backup;
019
020import static org.junit.jupiter.api.Assertions.assertAll;
021import static org.junit.jupiter.api.Assertions.assertEquals;
022import static org.junit.jupiter.api.Assertions.assertFalse;
023import static org.junit.jupiter.api.Assertions.assertNotNull;
024import static org.junit.jupiter.api.Assertions.assertNull;
025import static org.junit.jupiter.api.Assertions.assertTrue;
026
027import java.io.IOException;
028import java.util.ArrayList;
029import java.util.List;
030import java.util.Map;
031import org.apache.hadoop.fs.Path;
032import org.apache.hadoop.hbase.HBaseTestingUtil;
033import org.apache.hadoop.hbase.ServerName;
034import org.apache.hadoop.hbase.SingleProcessHBaseCluster;
035import org.apache.hadoop.hbase.TableName;
036import org.apache.hadoop.hbase.backup.impl.BackupAdminImpl;
037import org.apache.hadoop.hbase.backup.impl.BackupSystemTable;
038import org.apache.hadoop.hbase.backup.impl.FullTableBackupClient;
039import org.apache.hadoop.hbase.backup.impl.TableBackupClient;
040import org.apache.hadoop.hbase.backup.util.BackupUtils;
041import org.apache.hadoop.hbase.client.Admin;
042import org.apache.hadoop.hbase.client.Connection;
043import org.apache.hadoop.hbase.client.ConnectionFactory;
044import org.apache.hadoop.hbase.client.Delete;
045import org.apache.hadoop.hbase.client.Get;
046import org.apache.hadoop.hbase.client.Put;
047import org.apache.hadoop.hbase.client.RegionInfo;
048import org.apache.hadoop.hbase.client.ResultScanner;
049import org.apache.hadoop.hbase.client.Scan;
050import org.apache.hadoop.hbase.client.Table;
051import org.apache.hadoop.hbase.master.HMaster;
052import org.apache.hadoop.hbase.master.procedure.ServerCrashProcedure;
053import org.apache.hadoop.hbase.regionserver.HRegion;
054import org.apache.hadoop.hbase.regionserver.HRegionServer;
055import org.apache.hadoop.hbase.testclassification.LargeTests;
056import org.apache.hadoop.hbase.util.Bytes;
057import org.apache.hadoop.hbase.util.DNS;
058import org.junit.jupiter.api.BeforeAll;
059import org.junit.jupiter.api.Tag;
060import org.junit.jupiter.api.Test;
061import org.slf4j.Logger;
062import org.slf4j.LoggerFactory;
063
064import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
065
066/**
067 * Tests that WAL files from offline/inactive RegionServers are handled correctly during backup.
068 * Specifically verifies that WALs from an offline RS are:
069 * <ol>
070 * <li>Backed up once in the first backup after the RS goes offline</li>
071 * <li>NOT re-backed up in subsequent backups</li>
072 * </ol>
073 */
074@Tag(LargeTests.TAG)
075public class TestBackupOfflineRS extends TestBackupBase {
076
077  private static final Logger LOG = LoggerFactory.getLogger(TestBackupOfflineRS.class);
078
079  @BeforeAll
080  public static void setUp() throws Exception {
081    TEST_UTIL = new HBaseTestingUtil();
082    conf1 = TEST_UTIL.getConfiguration();
083    conf1.setInt("hbase.regionserver.info.port", -1);
084    conf1.setInt(HMaster.HBASE_MASTER_CLEANER_INTERVAL, Integer.MAX_VALUE);
085    // Forces a hostname with a capital letter. This effectively repurposes the test to also
086    // verify that the backup system is not affected by case sensitivity issues in hostnames.
087    conf1.set(DNS.UNSAFE_RS_HOSTNAME_KEY, "LocalHost");
088    autoRestoreOnFailure = true;
089    useSecondCluster = false;
090    setUpHelper();
091    TEST_UTIL.getMiniHBaseCluster().startRegionServer();
092    TEST_UTIL.waitTableAvailable(table1);
093  }
094
095  private static Runnable afterSnapshotHook;
096
097  /** Full backup client that runs {@link #afterSnapshotHook} once the table snapshots exist. */
098  public static class FullTableBackupClientWithHook extends FullTableBackupClient {
099    @Override
100    protected void snapshotCopy(BackupInfo backupInfo) throws IOException {
101      afterSnapshotHook.run();
102      super.snapshotCopy(backupInfo);
103    }
104  }
105
106  private static void stopRegionServerAndWait(ServerName serverName) throws Exception {
107    SingleProcessHBaseCluster cluster = TEST_UTIL.getMiniHBaseCluster();
108    HMaster master = cluster.getMaster();
109    cluster.stopRegionServer(serverName);
110    cluster.waitForRegionServerToStop(serverName, 60_000);
111    TEST_UTIL.waitFor(60_000,
112      () -> master.getProcedures().stream().filter(ServerCrashProcedure.class::isInstance)
113        .map(ServerCrashProcedure.class::cast)
114        .anyMatch(scp -> scp.getServerName().equals(serverName) && scp.isFinished()));
115    TEST_UTIL.waitUntilNoRegionsInTransition(60_000);
116  }
117
118  private static void restore(String backupId, TableName sourceTable, TableName restoredTable)
119    throws Exception {
120    try (Connection conn = ConnectionFactory.createConnection(conf1);
121      BackupAdminImpl backupAdmin = new BackupAdminImpl(conn)) {
122      backupAdmin.restore(BackupUtils.createRestoreRequest(BACKUP_ROOT_DIR, backupId, false,
123        new TableName[] { sourceTable }, new TableName[] { restoredTable }, true));
124    }
125  }
126
127  private static void restoreAndAssertAllRowsPresent(String backupId, String restoredTableName,
128    String message) throws Exception {
129    TableName restoredTable = TableName.valueOf(restoredTableName);
130    restore(backupId, table1, restoredTable);
131    assertEquals(TEST_UTIL.countRows(table1), TEST_UTIL.countRows(restoredTable), message);
132  }
133
134  private static Long boundary(BackupSystemTable sysTable, String host) throws IOException {
135    return sysTable.readLogTimestampMap(BACKUP_ROOT_DIR).get(table1).get(host);
136  }
137
138  private static List<String> walsOfHost(BackupSystemTable sysTable, String backupId, String host)
139    throws IOException {
140    List<String> wals = sysTable.readBackupInfo(backupId).getIncrBackupFileList();
141    if (wals == null) {
142      return List.of();
143    }
144    return wals.stream()
145      .filter(wal -> host.equals(BackupUtils.parseHostNameFromLogFile(new Path(wal)))).toList();
146  }
147
148  private static void moveRegionAndWait(TableName table, HRegionServer destination)
149    throws Exception {
150    try (Admin admin = TEST_UTIL.getConnection().getAdmin()) {
151      RegionInfo region = admin.getRegions(table).get(0);
152      admin.move(region.getEncodedNameAsBytes(), destination.getServerName());
153    }
154    TEST_UTIL.waitFor(60_000, () -> !destination.getRegions(table).isEmpty());
155    TEST_UTIL.waitUntilAllRegionsAssigned(table);
156  }
157
158  /**
159   * Tests that when a full backup is taken while an RS is offline (with WALs in oldlogs), the
160   * offline host's timestamps are recorded so subsequent incremental backups don't reinclude those
161   * WALs.
162   */
163  @Test
164  public void testBackupWithOfflineRS() throws Exception {
165    LOG.info("Starting testBackupWithOfflineRS");
166
167    SingleProcessHBaseCluster cluster = TEST_UTIL.getMiniHBaseCluster();
168    List<TableName> tables = Lists.newArrayList(table1);
169
170    HRegionServer rsBeforeStop = cluster.startRegionServerAndWait(10000).getRegionServer();
171    moveRegionAndWait(table1, rsBeforeStop);
172
173    LOG.info("Inserting data to generate WAL entries");
174    try (Connection conn = ConnectionFactory.createConnection(conf1)) {
175      insertIntoTable(conn, table1, famName, 2, 100);
176    }
177
178    String offlineHost =
179      BackupUtils.toHostKey(rsBeforeStop.getServerName().getAddress().toString());
180    LOG.info("Stopping RS: {}", offlineHost);
181
182    stopRegionServerAndWait(rsBeforeStop.getServerName());
183
184    LOG.info("Taking full backup (with offline RS WALs in oldlogs)");
185    String fullBackupId = fullTableBackup(tables);
186    assertTrue(checkSucceeded(fullBackupId), "Full backup should succeed");
187
188    try (BackupSystemTable sysTable = new BackupSystemTable(TEST_UTIL.getConnection())) {
189      Map<TableName, Map<String, Long>> timestamps = sysTable.readLogTimestampMap(BACKUP_ROOT_DIR);
190      Map<String, Long> rsTimestamps = timestamps.get(table1);
191      LOG.info("RS timestamps after full backup: {}", rsTimestamps);
192
193      Long tsAfterFullBackup = rsTimestamps.get(offlineHost);
194      assertNotNull(tsAfterFullBackup,
195        "Offline host should have timestamp recorded in trslm after full backup");
196
197      LOG.info("Taking incremental backup (should NOT include offline RS WALs)");
198      String incrBackupId = incrementalTableBackup(tables);
199      assertTrue(checkSucceeded(incrBackupId), "Incremental backup should succeed");
200
201      assertEquals(tsAfterFullBackup, boundary(sysTable, offlineHost),
202        "Incremental backup moved the boundary of the offline host");
203      List<String> offlineHostWals = walsOfHost(sysTable, incrBackupId, offlineHost);
204      assertTrue(offlineHostWals.isEmpty(),
205        "Incremental backup included WALs of the offline host that the full backup covers: "
206          + offlineHostWals);
207    }
208  }
209
210  /**
211   * Tests that WALs written to an RS after a full backup are correctly included in the subsequent
212   * incremental backup, even if that RS has gone offline before the incremental runs.
213   */
214  @Test
215  public void testRSGoesOfflineAfterFullBackupBeforeIncremental() throws Exception {
216    SingleProcessHBaseCluster cluster = TEST_UTIL.getMiniHBaseCluster();
217    List<TableName> tables = Lists.newArrayList(table1);
218
219    HRegionServer rsBeforeStop = cluster.startRegionServerAndWait(10000).getRegionServer();
220
221    try (Connection conn = ConnectionFactory.createConnection(conf1)) {
222      insertIntoTable(conn, table1, famName, 3, 50);
223    }
224
225    String fullBackupId = fullTableBackup(tables);
226    assertTrue(checkSucceeded(fullBackupId), "Full backup should succeed");
227
228    moveRegionAndWait(table1, rsBeforeStop);
229    try (Connection conn = ConnectionFactory.createConnection(conf1)) {
230      insertIntoTable(conn, table1, famName, 4, 50);
231    }
232
233    rsBeforeStop.getWalRoller().requestRollAll();
234    rsBeforeStop.getWalRoller().waitUntilWalRollFinished();
235    String offlineHost =
236      BackupUtils.toHostKey(rsBeforeStop.getServerName().getAddress().toString());
237
238    stopRegionServerAndWait(rsBeforeStop.getServerName());
239
240    String incrBackupId = incrementalTableBackup(tables);
241    assertTrue(checkSucceeded(incrBackupId), "Incremental backup should succeed");
242
243    restoreAndAssertAllRowsPresent(incrBackupId, "table1_rs_offline_after_full_backup",
244      "Restored table should contain the rows written to the RS that went offline");
245
246    try (BackupSystemTable sysTable = new BackupSystemTable(TEST_UTIL.getConnection())) {
247      Long boundaryAfterIncr1 = boundary(sysTable, offlineHost);
248      assertNotNull(boundaryAfterIncr1,
249        "Offline RS should have a timestamp boundary after the incremental backed up its WALs");
250      assertFalse(walsOfHost(sysTable, incrBackupId, offlineHost).isEmpty(),
251        "First incremental after the RS went offline should include its WALs");
252      Long staleLogRoll =
253        sysTable.readRegionServerLastLogRollResult(BACKUP_ROOT_DIR).get(offlineHost);
254
255      String incrBackupId2 = incrementalTableBackup(tables);
256      assertTrue(checkSucceeded(incrBackupId2), "Second incremental backup should succeed");
257      Long boundaryAfterIncr2 = boundary(sysTable, offlineHost);
258
259      String incrBackupId3 = incrementalTableBackup(tables);
260      assertTrue(checkSucceeded(incrBackupId3), "Third incremental backup should succeed");
261      Long boundaryAfterIncr3 = boundary(sysTable, offlineHost);
262
263      String incrBackupId4 = incrementalTableBackup(tables);
264      assertTrue(checkSucceeded(incrBackupId4), "Fourth incremental backup should succeed");
265      Long boundaryAfterIncr4 = boundary(sysTable, offlineHost);
266
267      String message = "Incremental backup moved the boundary of the offline RS, which would back "
268        + "up its WALs again (last log roll = " + staleLogRoll + ")";
269      List<String> walsBackedUpAgain = new ArrayList<>();
270      for (String laterBackupId : List.of(incrBackupId2, incrBackupId3, incrBackupId4)) {
271        walsBackedUpAgain.addAll(walsOfHost(sysTable, laterBackupId, offlineHost));
272      }
273      assertAll(() -> assertEquals(boundaryAfterIncr1, boundaryAfterIncr2, message),
274        () -> assertEquals(boundaryAfterIncr1, boundaryAfterIncr3, message),
275        () -> assertEquals(boundaryAfterIncr1, boundaryAfterIncr4, message),
276        () -> assertTrue(walsBackedUpAgain.isEmpty(),
277          "Later incremental backups included WALs of the offline RS again: " + walsBackedUpAgain));
278    }
279  }
280
281  /**
282   * Tests that a brand-new RS that comes online and goes offline before any backup correctly has
283   * its WALs covered by the full backup.
284   */
285  @Test
286  public void testTransientRSBeforeFullBackup() throws Exception {
287    SingleProcessHBaseCluster cluster = TEST_UTIL.getMiniHBaseCluster();
288    List<TableName> tables = Lists.newArrayList(table1);
289
290    HRegionServer transientRS = cluster.startRegionServerAndWait(10000).getRegionServer();
291    moveRegionAndWait(table1, transientRS);
292    try (Connection conn = ConnectionFactory.createConnection(conf1)) {
293      insertIntoTable(conn, table1, famName, 5, 50);
294    }
295    transientRS.getWalRoller().requestRollAll();
296    transientRS.getWalRoller().waitUntilWalRollFinished();
297    String transientHost =
298      BackupUtils.toHostKey(transientRS.getServerName().getAddress().toString());
299
300    stopRegionServerAndWait(transientRS.getServerName());
301
302    String fullBackupId = fullTableBackup(tables);
303    assertTrue(checkSucceeded(fullBackupId), "Full backup should succeed");
304
305    try (BackupSystemTable sysTable = new BackupSystemTable(TEST_UTIL.getConnection())) {
306      Long boundaryAfterFullBackup = boundary(sysTable, transientHost);
307      assertNotNull(boundaryAfterFullBackup,
308        "Transient RS that went offline before full backup should have its WAL boundary recorded");
309
310      String incrBackupId = incrementalTableBackup(tables);
311      assertTrue(checkSucceeded(incrBackupId),
312        "Incremental backup after transient RS should succeed");
313
314      assertEquals(boundaryAfterFullBackup, boundary(sysTable, transientHost),
315        "Incremental backup moved the boundary of the transient RS");
316    }
317  }
318
319  /**
320   * Tests that WALs from an RS that comes online and goes offline between a full backup and an
321   * incremental backup are correctly included in the incremental backup and not re-included in
322   * subsequent incremental backups.
323   */
324  @Test
325  public void testTransientRSAfterFullBackupBeforeIncremental() throws Exception {
326    SingleProcessHBaseCluster cluster = TEST_UTIL.getMiniHBaseCluster();
327    List<TableName> tables = Lists.newArrayList(table1);
328
329    try (Connection conn = ConnectionFactory.createConnection(conf1)) {
330      insertIntoTable(conn, table1, famName, 6, 50);
331    }
332
333    String fullBackupId = fullTableBackup(tables);
334    assertTrue(checkSucceeded(fullBackupId), "Full backup should succeed");
335
336    HRegionServer transientRS = cluster.startRegionServerAndWait(10000).getRegionServer();
337    moveRegionAndWait(table1, transientRS);
338    try (Connection conn = ConnectionFactory.createConnection(conf1)) {
339      insertIntoTable(conn, table1, famName, 7, 50);
340    }
341    transientRS.getWalRoller().requestRollAll();
342    transientRS.getWalRoller().waitUntilWalRollFinished();
343    String transientHost =
344      BackupUtils.toHostKey(transientRS.getServerName().getAddress().toString());
345
346    stopRegionServerAndWait(transientRS.getServerName());
347
348    String incrBackupId = incrementalTableBackup(tables);
349    assertTrue(checkSucceeded(incrBackupId), "Incremental backup should succeed");
350
351    restoreAndAssertAllRowsPresent(incrBackupId, "table1_transient_rs_after_full_backup",
352      "Restored table should contain the rows written to the transient RS");
353
354    try (BackupSystemTable sysTable = new BackupSystemTable(TEST_UTIL.getConnection())) {
355      Long boundaryAfterIncr1 = boundary(sysTable, transientHost);
356      assertNotNull(boundaryAfterIncr1,
357        "Transient RS should have a timestamp boundary after the incremental backed up its WALs");
358
359      String incrBackupId2 = incrementalTableBackup(tables);
360      assertTrue(checkSucceeded(incrBackupId2), "Second incremental backup should succeed");
361
362      assertEquals(boundaryAfterIncr1, boundary(sysTable, transientHost),
363        "Second incremental backup moved the boundary of the transient RS");
364    }
365  }
366
367  /**
368   * Tests that edits written during a full backup, after its log roll and table snapshot, to an RS
369   * that started after that log roll, are included in the next incremental backup.
370   */
371  @Test
372  public void testRSStartedDuringFullBackup() throws Exception {
373    SingleProcessHBaseCluster cluster = TEST_UTIL.getMiniHBaseCluster();
374    List<TableName> tables = Lists.newArrayList(table1);
375
376    afterSnapshotHook = () -> {
377      try {
378        HRegionServer newRS = cluster.startRegionServerAndWait(10000).getRegionServer();
379        moveRegionAndWait(table1, newRS);
380        try (Connection conn = ConnectionFactory.createConnection(conf1)) {
381          insertIntoTable(conn, table1, famName, 8, 50).close();
382        }
383        stopRegionServerAndWait(newRS.getServerName());
384      } catch (Exception e) {
385        throw new RuntimeException(e);
386      }
387    };
388    conf1.set(TableBackupClient.BACKUP_CLIENT_IMPL_CLASS,
389      FullTableBackupClientWithHook.class.getName());
390    String fullBackupId;
391    try {
392      fullBackupId = fullTableBackup(tables);
393    } finally {
394      conf1.unset(TableBackupClient.BACKUP_CLIENT_IMPL_CLASS);
395    }
396    assertTrue(checkSucceeded(fullBackupId), "Full backup should succeed");
397
398    String incrBackupId = incrementalTableBackup(tables);
399    assertTrue(checkSucceeded(incrBackupId), "Incremental backup should succeed");
400
401    restoreAndAssertAllRowsPresent(incrBackupId, "table1_rs_started_during_full_backup",
402      "Restored table should contain all rows, including those written to the new RS");
403  }
404
405  /**
406   * Tests that a row deleted before a full backup is not brought back by the WALs of a region
407   * server that went offline between two backups. The row and its delete marker are compacted away
408   * before the full backup, so only the offline RS's old WAL, which still holds the put, could
409   * bring it back.
410   */
411  @Test
412  public void testDeletedRowIsNotResurrectedByOfflineRSWALs() throws Exception {
413    SingleProcessHBaseCluster cluster = TEST_UTIL.getMiniHBaseCluster();
414    List<TableName> tables = Lists.newArrayList(table1);
415    byte[] deletedRow = Bytes.toBytes("row-deleted");
416
417    HRegionServer offlineRS = cluster.startRegionServerAndWait(10000).getRegionServer();
418    HRegionServer liveRS = cluster.startRegionServerAndWait(10000).getRegionServer();
419
420    try (Table table = TEST_UTIL.getConnection().getTable(table1)) {
421      moveRegionAndWait(table1, offlineRS);
422
423      String firstFullBackupId = fullTableBackup(tables);
424      assertTrue(checkSucceeded(firstFullBackupId), "First full backup should succeed");
425
426      for (int i = 0; i < 10; i++) {
427        table.put(new Put(Bytes.toBytes("row-kept-" + i)).addColumn(famName, qualName,
428          Bytes.toBytes("value")));
429      }
430      table.put(new Put(deletedRow).addColumn(famName, qualName, Bytes.toBytes("value")));
431      for (HRegion region : offlineRS.getRegions(table1)) {
432        region.flush(true);
433      }
434
435      moveRegionAndWait(table1, liveRS);
436
437      table.delete(new Delete(deletedRow));
438      for (HRegion region : liveRS.getRegions(table1)) {
439        region.flush(true);
440        region.compact(true);
441      }
442
443      assertTrue(table.get(new Get(deletedRow)).isEmpty(),
444        "Deleted row should be gone from the source table");
445      Scan rawScan = new Scan().withStartRow(deletedRow).withStopRow(deletedRow, true).setRaw(true);
446      try (ResultScanner scanner = table.getScanner(rawScan)) {
447        assertNull(scanner.next(),
448          "Major compaction should have purged the deleted row and its delete marker");
449      }
450
451      stopRegionServerAndWait(offlineRS.getServerName());
452
453      String secondFullBackupId = fullTableBackup(tables);
454      assertTrue(checkSucceeded(secondFullBackupId), "Second full backup should succeed");
455      String incrBackupId = incrementalTableBackup(tables);
456      assertTrue(checkSucceeded(incrBackupId), "Incremental backup should succeed");
457
458      TableName restoredTable = TableName.valueOf("table1_deleted_row_not_resurrected");
459      restore(incrBackupId, table1, restoredTable);
460      try (Table restored = TEST_UTIL.getConnection().getTable(restoredTable)) {
461        assertTrue(restored.get(new Get(deletedRow)).isEmpty(),
462          "Deleted row was brought back by the WALs of the offline RS");
463      }
464      assertEquals(TEST_UTIL.countRows(table1), TEST_UTIL.countRows(restoredTable),
465        "Restored table should match the source table");
466    }
467  }
468}