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 static org.junit.Assert.assertEquals; 021import static org.junit.Assert.assertFalse; 022import static org.junit.Assert.assertNotNull; 023import static org.junit.Assert.assertTrue; 024import static org.junit.Assert.fail; 025 026import java.io.IOException; 027import java.lang.reflect.Method; 028import java.net.BindException; 029import java.util.List; 030import java.util.NavigableMap; 031import java.util.TreeMap; 032import org.apache.hadoop.conf.Configuration; 033import org.apache.hadoop.fs.FSDataInputStream; 034import org.apache.hadoop.fs.FSDataOutputStream; 035import org.apache.hadoop.fs.FileStatus; 036import org.apache.hadoop.fs.FileSystem; 037import org.apache.hadoop.fs.Path; 038import org.apache.hadoop.hbase.Cell; 039import org.apache.hadoop.hbase.CellUtil; 040import org.apache.hadoop.hbase.Coprocessor; 041import org.apache.hadoop.hbase.HBaseClassTestRule; 042import org.apache.hadoop.hbase.HBaseTestingUtility; 043import org.apache.hadoop.hbase.HConstants; 044import org.apache.hadoop.hbase.KeyValue; 045import org.apache.hadoop.hbase.ServerName; 046import org.apache.hadoop.hbase.TableName; 047import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; 048import org.apache.hadoop.hbase.client.RegionInfo; 049import org.apache.hadoop.hbase.client.RegionInfoBuilder; 050import org.apache.hadoop.hbase.client.TableDescriptor; 051import org.apache.hadoop.hbase.client.TableDescriptorBuilder; 052import org.apache.hadoop.hbase.coprocessor.CoprocessorHost; 053import org.apache.hadoop.hbase.coprocessor.SampleRegionWALCoprocessor; 054import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl; 055import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener; 056import org.apache.hadoop.hbase.regionserver.wal.WALCoprocessorHost; 057import org.apache.hadoop.hbase.testclassification.MediumTests; 058import org.apache.hadoop.hbase.testclassification.RegionServerTests; 059import org.apache.hadoop.hbase.util.Bytes; 060import org.apache.hadoop.hbase.util.FSUtils; 061import org.apache.hadoop.hbase.util.Threads; 062import org.apache.hadoop.hdfs.DistributedFileSystem; 063import org.apache.hadoop.hdfs.MiniDFSCluster; 064import org.apache.hadoop.hdfs.protocol.HdfsConstants; 065import org.junit.After; 066import org.junit.AfterClass; 067import org.junit.Before; 068import org.junit.BeforeClass; 069import org.junit.ClassRule; 070import org.junit.Rule; 071import org.junit.Test; 072import org.junit.experimental.categories.Category; 073import org.junit.rules.TestName; 074import org.slf4j.Logger; 075import org.slf4j.LoggerFactory; 076 077/** 078 * WAL tests that can be reused across providers. 079 */ 080@Category({RegionServerTests.class, MediumTests.class}) 081public class TestWALFactory { 082 083 @ClassRule 084 public static final HBaseClassTestRule CLASS_RULE = 085 HBaseClassTestRule.forClass(TestWALFactory.class); 086 087 private static final Logger LOG = LoggerFactory.getLogger(TestWALFactory.class); 088 089 protected static Configuration conf; 090 private static MiniDFSCluster cluster; 091 protected final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); 092 protected static Path hbaseDir; 093 protected static Path hbaseWALDir; 094 095 protected FileSystem fs; 096 protected Path dir; 097 protected WALFactory wals; 098 private ServerName currentServername; 099 100 @Rule 101 public final TestName currentTest = new TestName(); 102 103 @Before 104 public void setUp() throws Exception { 105 fs = cluster.getFileSystem(); 106 dir = new Path(hbaseDir, currentTest.getMethodName()); 107 this.currentServername = ServerName.valueOf(currentTest.getMethodName(), 16010, 1); 108 wals = new WALFactory(conf, this.currentServername.toString()); 109 } 110 111 @After 112 public void tearDown() throws Exception { 113 // testAppendClose closes the FileSystem, which will prevent us from closing cleanly here. 114 try { 115 wals.close(); 116 } catch (IOException exception) { 117 LOG.warn("Encountered exception while closing wal factory. If you have other errors, this" + 118 " may be the cause. Message: " + exception); 119 LOG.debug("Exception details for failure to close wal factory.", exception); 120 } 121 FileStatus[] entries = fs.listStatus(new Path("/")); 122 for (FileStatus dir : entries) { 123 fs.delete(dir.getPath(), true); 124 } 125 } 126 127 @BeforeClass 128 public static void setUpBeforeClass() throws Exception { 129 // Make block sizes small. 130 TEST_UTIL.getConfiguration().setInt("dfs.blocksize", 1024 * 1024); 131 // needed for testAppendClose() 132 // quicker heartbeat interval for faster DN death notification 133 TEST_UTIL.getConfiguration().setInt("dfs.namenode.heartbeat.recheck-interval", 5000); 134 TEST_UTIL.getConfiguration().setInt("dfs.heartbeat.interval", 1); 135 TEST_UTIL.getConfiguration().setInt("dfs.client.socket-timeout", 5000); 136 137 // faster failover with cluster.shutdown();fs.close() idiom 138 TEST_UTIL.getConfiguration() 139 .setInt("hbase.ipc.client.connect.max.retries", 1); 140 TEST_UTIL.getConfiguration().setInt( 141 "dfs.client.block.recovery.retries", 1); 142 TEST_UTIL.getConfiguration().setInt( 143 "hbase.ipc.client.connection.maxidletime", 500); 144 TEST_UTIL.getConfiguration().setInt("hbase.lease.recovery.timeout", 10000); 145 TEST_UTIL.getConfiguration().setInt("hbase.lease.recovery.dfs.timeout", 1000); 146 TEST_UTIL.getConfiguration().set(CoprocessorHost.WAL_COPROCESSOR_CONF_KEY, 147 SampleRegionWALCoprocessor.class.getName()); 148 TEST_UTIL.startMiniDFSCluster(3); 149 150 conf = TEST_UTIL.getConfiguration(); 151 cluster = TEST_UTIL.getDFSCluster(); 152 153 hbaseDir = TEST_UTIL.createRootDir(); 154 hbaseWALDir = TEST_UTIL.createWALRootDir(); 155 } 156 157 @AfterClass 158 public static void tearDownAfterClass() throws Exception { 159 TEST_UTIL.shutdownMiniCluster(); 160 } 161 162 @Test 163 public void canCloseSingleton() throws IOException { 164 WALFactory.getInstance(conf).close(); 165 } 166 167 /** 168 * Just write multiple logs then split. Before fix for HADOOP-2283, this 169 * would fail. 170 * @throws IOException 171 */ 172 @Test 173 public void testSplit() throws IOException { 174 final TableName tableName = TableName.valueOf(currentTest.getMethodName()); 175 final byte [] rowName = tableName.getName(); 176 final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1); 177 final int howmany = 3; 178 RegionInfo[] infos = new RegionInfo[3]; 179 Path tabledir = FSUtils.getTableDir(hbaseWALDir, tableName); 180 fs.mkdirs(tabledir); 181 for (int i = 0; i < howmany; i++) { 182 infos[i] = RegionInfoBuilder.newBuilder(tableName).setStartKey(Bytes.toBytes("" + i)) 183 .setEndKey(Bytes.toBytes("" + (i + 1))).build(); 184 fs.mkdirs(new Path(tabledir, infos[i].getEncodedName())); 185 LOG.info("allo " + new Path(tabledir, infos[i].getEncodedName()).toString()); 186 } 187 NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR); 188 scopes.put(Bytes.toBytes("column"), 0); 189 190 191 // Add edits for three regions. 192 for (int ii = 0; ii < howmany; ii++) { 193 for (int i = 0; i < howmany; i++) { 194 final WAL log = 195 wals.getWAL(infos[i]); 196 for (int j = 0; j < howmany; j++) { 197 WALEdit edit = new WALEdit(); 198 byte [] family = Bytes.toBytes("column"); 199 byte [] qualifier = Bytes.toBytes(Integer.toString(j)); 200 byte [] column = Bytes.toBytes("column:" + Integer.toString(j)); 201 edit.add(new KeyValue(rowName, family, qualifier, 202 System.currentTimeMillis(), column)); 203 LOG.info("Region " + i + ": " + edit); 204 WALKeyImpl walKey = new WALKeyImpl(infos[i].getEncodedNameAsBytes(), tableName, 205 System.currentTimeMillis(), mvcc, scopes); 206 log.append(infos[i], walKey, edit, true); 207 walKey.getWriteEntry(); 208 } 209 log.sync(); 210 log.rollWriter(true); 211 } 212 } 213 wals.shutdown(); 214 // The below calculation of logDir relies on insider information... WALSplitter should be connected better 215 // with the WAL system.... not requiring explicit path. The oldLogDir is just made up not used. 216 Path logDir = 217 new Path(new Path(hbaseWALDir, HConstants.HREGION_LOGDIR_NAME), 218 this.currentServername.toString()); 219 Path oldLogDir = new Path(hbaseDir, HConstants.HREGION_OLDLOGDIR_NAME); 220 List<Path> splits = WALSplitter.split(hbaseWALDir, logDir, oldLogDir, fs, conf, wals); 221 verifySplits(splits, howmany); 222 } 223 224 /** 225 * Test new HDFS-265 sync. 226 * @throws Exception 227 */ 228 @Test 229 public void Broken_testSync() throws Exception { 230 TableName tableName = TableName.valueOf(currentTest.getMethodName()); 231 MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1); 232 // First verify that using streams all works. 233 Path p = new Path(dir, currentTest.getMethodName() + ".fsdos"); 234 FSDataOutputStream out = fs.create(p); 235 out.write(tableName.getName()); 236 Method syncMethod = null; 237 try { 238 syncMethod = out.getClass().getMethod("hflush", new Class<?> []{}); 239 } catch (NoSuchMethodException e) { 240 try { 241 syncMethod = out.getClass().getMethod("sync", new Class<?> []{}); 242 } catch (NoSuchMethodException ex) { 243 fail("This version of Hadoop supports neither Syncable.sync() " + 244 "nor Syncable.hflush()."); 245 } 246 } 247 syncMethod.invoke(out, new Object[]{}); 248 FSDataInputStream in = fs.open(p); 249 assertTrue(in.available() > 0); 250 byte [] buffer = new byte [1024]; 251 int read = in.read(buffer); 252 assertEquals(tableName.getName().length, read); 253 out.close(); 254 in.close(); 255 256 final int total = 20; 257 WAL.Reader reader = null; 258 259 try { 260 RegionInfo info = RegionInfoBuilder.newBuilder(tableName).build(); 261 NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR); 262 scopes.put(tableName.getName(), 0); 263 final WAL wal = wals.getWAL(info); 264 265 for (int i = 0; i < total; i++) { 266 WALEdit kvs = new WALEdit(); 267 kvs.add(new KeyValue(Bytes.toBytes(i), tableName.getName(), tableName.getName())); 268 wal.append(info, new WALKeyImpl(info.getEncodedNameAsBytes(), tableName, 269 System.currentTimeMillis(), mvcc, scopes), kvs, true); 270 } 271 // Now call sync and try reading. Opening a Reader before you sync just 272 // gives you EOFE. 273 wal.sync(); 274 // Open a Reader. 275 Path walPath = AbstractFSWALProvider.getCurrentFileName(wal); 276 reader = wals.createReader(fs, walPath); 277 int count = 0; 278 WAL.Entry entry = new WAL.Entry(); 279 while ((entry = reader.next(entry)) != null) count++; 280 assertEquals(total, count); 281 reader.close(); 282 // Add test that checks to see that an open of a Reader works on a file 283 // that has had a sync done on it. 284 for (int i = 0; i < total; i++) { 285 WALEdit kvs = new WALEdit(); 286 kvs.add(new KeyValue(Bytes.toBytes(i), tableName.getName(), tableName.getName())); 287 wal.append(info, new WALKeyImpl(info.getEncodedNameAsBytes(), tableName, 288 System.currentTimeMillis(), mvcc, scopes), kvs, true); 289 } 290 wal.sync(); 291 reader = wals.createReader(fs, walPath); 292 count = 0; 293 while((entry = reader.next(entry)) != null) count++; 294 assertTrue(count >= total); 295 reader.close(); 296 // If I sync, should see double the edits. 297 wal.sync(); 298 reader = wals.createReader(fs, walPath); 299 count = 0; 300 while((entry = reader.next(entry)) != null) count++; 301 assertEquals(total * 2, count); 302 reader.close(); 303 // Now do a test that ensures stuff works when we go over block boundary, 304 // especially that we return good length on file. 305 final byte [] value = new byte[1025 * 1024]; // Make a 1M value. 306 for (int i = 0; i < total; i++) { 307 WALEdit kvs = new WALEdit(); 308 kvs.add(new KeyValue(Bytes.toBytes(i), tableName.getName(), value)); 309 wal.append(info, new WALKeyImpl(info.getEncodedNameAsBytes(), tableName, 310 System.currentTimeMillis(), mvcc, scopes), kvs, true); 311 } 312 // Now I should have written out lots of blocks. Sync then read. 313 wal.sync(); 314 reader = wals.createReader(fs, walPath); 315 count = 0; 316 while((entry = reader.next(entry)) != null) count++; 317 assertEquals(total * 3, count); 318 reader.close(); 319 // shutdown and ensure that Reader gets right length also. 320 wal.shutdown(); 321 reader = wals.createReader(fs, walPath); 322 count = 0; 323 while((entry = reader.next(entry)) != null) count++; 324 assertEquals(total * 3, count); 325 reader.close(); 326 } finally { 327 if (reader != null) reader.close(); 328 } 329 } 330 331 private void verifySplits(final List<Path> splits, final int howmany) 332 throws IOException { 333 assertEquals(howmany * howmany, splits.size()); 334 for (int i = 0; i < splits.size(); i++) { 335 LOG.info("Verifying=" + splits.get(i)); 336 WAL.Reader reader = wals.createReader(fs, splits.get(i)); 337 try { 338 int count = 0; 339 String previousRegion = null; 340 long seqno = -1; 341 WAL.Entry entry = new WAL.Entry(); 342 while((entry = reader.next(entry)) != null) { 343 WALKey key = entry.getKey(); 344 String region = Bytes.toString(key.getEncodedRegionName()); 345 // Assert that all edits are for same region. 346 if (previousRegion != null) { 347 assertEquals(previousRegion, region); 348 } 349 LOG.info("oldseqno=" + seqno + ", newseqno=" + key.getSequenceId()); 350 assertTrue(seqno < key.getSequenceId()); 351 seqno = key.getSequenceId(); 352 previousRegion = region; 353 count++; 354 } 355 assertEquals(howmany, count); 356 } finally { 357 reader.close(); 358 } 359 } 360 } 361 362 /* 363 * We pass different values to recoverFileLease() so that different code paths are covered 364 * 365 * For this test to pass, requires: 366 * 1. HDFS-200 (append support) 367 * 2. HDFS-988 (SafeMode should freeze file operations 368 * [FSNamesystem.nextGenerationStampForBlock]) 369 * 3. HDFS-142 (on restart, maintain pendingCreates) 370 */ 371 @Test 372 public void testAppendClose() throws Exception { 373 TableName tableName = 374 TableName.valueOf(currentTest.getMethodName()); 375 RegionInfo regionInfo = RegionInfoBuilder.newBuilder(tableName).build(); 376 377 WAL wal = wals.getWAL(regionInfo); 378 int total = 20; 379 380 NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR); 381 scopes.put(tableName.getName(), 0); 382 MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(); 383 for (int i = 0; i < total; i++) { 384 WALEdit kvs = new WALEdit(); 385 kvs.add(new KeyValue(Bytes.toBytes(i), tableName.getName(), tableName.getName())); 386 wal.append(regionInfo, new WALKeyImpl(regionInfo.getEncodedNameAsBytes(), tableName, 387 System.currentTimeMillis(), mvcc, scopes), 388 kvs, true); 389 } 390 // Now call sync to send the data to HDFS datanodes 391 wal.sync(); 392 int namenodePort = cluster.getNameNodePort(); 393 final Path walPath = AbstractFSWALProvider.getCurrentFileName(wal); 394 395 396 // Stop the cluster. (ensure restart since we're sharing MiniDFSCluster) 397 try { 398 DistributedFileSystem dfs = cluster.getFileSystem(); 399 dfs.setSafeMode(HdfsConstants.SafeModeAction.SAFEMODE_ENTER); 400 TEST_UTIL.shutdownMiniDFSCluster(); 401 try { 402 // wal.writer.close() will throw an exception, 403 // but still call this since it closes the LogSyncer thread first 404 wal.shutdown(); 405 } catch (IOException e) { 406 LOG.info(e.toString(), e); 407 } 408 fs.close(); // closing FS last so DFSOutputStream can't call close 409 LOG.info("STOPPED first instance of the cluster"); 410 } finally { 411 // Restart the cluster 412 while (cluster.isClusterUp()){ 413 LOG.error("Waiting for cluster to go down"); 414 Thread.sleep(1000); 415 } 416 assertFalse(cluster.isClusterUp()); 417 cluster = null; 418 for (int i = 0; i < 100; i++) { 419 try { 420 cluster = TEST_UTIL.startMiniDFSClusterForTestWAL(namenodePort); 421 break; 422 } catch (BindException e) { 423 LOG.info("Sleeping. BindException bringing up new cluster"); 424 Threads.sleep(1000); 425 } 426 } 427 cluster.waitActive(); 428 fs = cluster.getFileSystem(); 429 LOG.info("STARTED second instance."); 430 } 431 432 // set the lease period to be 1 second so that the 433 // namenode triggers lease recovery upon append request 434 Method setLeasePeriod = cluster.getClass() 435 .getDeclaredMethod("setLeasePeriod", new Class[]{Long.TYPE, Long.TYPE}); 436 setLeasePeriod.setAccessible(true); 437 setLeasePeriod.invoke(cluster, 1000L, 1000L); 438 try { 439 Thread.sleep(1000); 440 } catch (InterruptedException e) { 441 LOG.info(e.toString(), e); 442 } 443 444 // Now try recovering the log, like the HMaster would do 445 final FileSystem recoveredFs = fs; 446 final Configuration rlConf = conf; 447 448 class RecoverLogThread extends Thread { 449 public Exception exception = null; 450 @Override 451 public void run() { 452 try { 453 FSUtils.getInstance(fs, rlConf) 454 .recoverFileLease(recoveredFs, walPath, rlConf, null); 455 } catch (IOException e) { 456 exception = e; 457 } 458 } 459 } 460 461 RecoverLogThread t = new RecoverLogThread(); 462 t.start(); 463 // Timeout after 60 sec. Without correct patches, would be an infinite loop 464 t.join(60 * 1000); 465 if(t.isAlive()) { 466 t.interrupt(); 467 throw new Exception("Timed out waiting for WAL.recoverLog()"); 468 } 469 470 if (t.exception != null) 471 throw t.exception; 472 473 // Make sure you can read all the content 474 WAL.Reader reader = wals.createReader(fs, walPath); 475 int count = 0; 476 WAL.Entry entry = new WAL.Entry(); 477 while (reader.next(entry) != null) { 478 count++; 479 assertTrue("Should be one KeyValue per WALEdit", 480 entry.getEdit().getCells().size() == 1); 481 } 482 assertEquals(total, count); 483 reader.close(); 484 485 // Reset the lease period 486 setLeasePeriod.invoke(cluster, new Object[]{ 60000L, 3600000L }); 487 } 488 489 /** 490 * Tests that we can write out an edit, close, and then read it back in again. 491 */ 492 @Test 493 public void testEditAdd() throws IOException { 494 int colCount = 10; 495 TableDescriptor htd = 496 TableDescriptorBuilder.newBuilder(TableName.valueOf(currentTest.getMethodName())) 497 .setColumnFamily(ColumnFamilyDescriptorBuilder.of("column")).build(); 498 NavigableMap<byte[], Integer> scopes = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR); 499 for (byte[] fam : htd.getColumnFamilyNames()) { 500 scopes.put(fam, 0); 501 } 502 byte[] row = Bytes.toBytes("row"); 503 WAL.Reader reader = null; 504 try { 505 final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1); 506 507 // Write columns named 1, 2, 3, etc. and then values of single byte 508 // 1, 2, 3... 509 long timestamp = System.currentTimeMillis(); 510 WALEdit cols = new WALEdit(); 511 for (int i = 0; i < colCount; i++) { 512 cols.add(new KeyValue(row, Bytes.toBytes("column"), 513 Bytes.toBytes(Integer.toString(i)), 514 timestamp, new byte[] { (byte)(i + '0') })); 515 } 516 RegionInfo info = RegionInfoBuilder.newBuilder(htd.getTableName()).setStartKey(row) 517 .setEndKey(Bytes.toBytes(Bytes.toString(row) + "1")).build(); 518 final WAL log = wals.getWAL(info); 519 520 final long txid = log.append(info, 521 new WALKeyImpl(info.getEncodedNameAsBytes(), htd.getTableName(), System.currentTimeMillis(), 522 mvcc, scopes), 523 cols, true); 524 log.sync(txid); 525 log.startCacheFlush(info.getEncodedNameAsBytes(), htd.getColumnFamilyNames()); 526 log.completeCacheFlush(info.getEncodedNameAsBytes()); 527 log.shutdown(); 528 Path filename = AbstractFSWALProvider.getCurrentFileName(log); 529 // Now open a reader on the log and assert append worked. 530 reader = wals.createReader(fs, filename); 531 // Above we added all columns on a single row so we only read one 532 // entry in the below... thats why we have '1'. 533 for (int i = 0; i < 1; i++) { 534 WAL.Entry entry = reader.next(null); 535 if (entry == null) break; 536 WALKey key = entry.getKey(); 537 WALEdit val = entry.getEdit(); 538 assertTrue(Bytes.equals(info.getEncodedNameAsBytes(), key.getEncodedRegionName())); 539 assertTrue(htd.getTableName().equals(key.getTableName())); 540 Cell cell = val.getCells().get(0); 541 assertTrue(Bytes.equals(row, 0, row.length, cell.getRowArray(), cell.getRowOffset(), 542 cell.getRowLength())); 543 assertEquals((byte)(i + '0'), CellUtil.cloneValue(cell)[0]); 544 System.out.println(key + " " + val); 545 } 546 } finally { 547 if (reader != null) { 548 reader.close(); 549 } 550 } 551 } 552 553 @Test 554 public void testAppend() throws IOException { 555 int colCount = 10; 556 TableDescriptor htd = 557 TableDescriptorBuilder.newBuilder(TableName.valueOf(currentTest.getMethodName())) 558 .setColumnFamily(ColumnFamilyDescriptorBuilder.of("column")).build(); 559 NavigableMap<byte[], Integer> scopes = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR); 560 for (byte[] fam : htd.getColumnFamilyNames()) { 561 scopes.put(fam, 0); 562 } 563 byte[] row = Bytes.toBytes("row"); 564 WAL.Reader reader = null; 565 final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1); 566 try { 567 // Write columns named 1, 2, 3, etc. and then values of single byte 568 // 1, 2, 3... 569 long timestamp = System.currentTimeMillis(); 570 WALEdit cols = new WALEdit(); 571 for (int i = 0; i < colCount; i++) { 572 cols.add(new KeyValue(row, Bytes.toBytes("column"), 573 Bytes.toBytes(Integer.toString(i)), 574 timestamp, new byte[] { (byte)(i + '0') })); 575 } 576 RegionInfo hri = RegionInfoBuilder.newBuilder(htd.getTableName()).build(); 577 final WAL log = wals.getWAL(hri); 578 final long txid = log.append(hri, 579 new WALKeyImpl(hri.getEncodedNameAsBytes(), htd.getTableName(), System.currentTimeMillis(), 580 mvcc, scopes), 581 cols, true); 582 log.sync(txid); 583 log.startCacheFlush(hri.getEncodedNameAsBytes(), htd.getColumnFamilyNames()); 584 log.completeCacheFlush(hri.getEncodedNameAsBytes()); 585 log.shutdown(); 586 Path filename = AbstractFSWALProvider.getCurrentFileName(log); 587 // Now open a reader on the log and assert append worked. 588 reader = wals.createReader(fs, filename); 589 WAL.Entry entry = reader.next(); 590 assertEquals(colCount, entry.getEdit().size()); 591 int idx = 0; 592 for (Cell val : entry.getEdit().getCells()) { 593 assertTrue(Bytes.equals(hri.getEncodedNameAsBytes(), 594 entry.getKey().getEncodedRegionName())); 595 assertTrue(htd.getTableName().equals(entry.getKey().getTableName())); 596 assertTrue(Bytes.equals(row, 0, row.length, val.getRowArray(), val.getRowOffset(), 597 val.getRowLength())); 598 assertEquals((byte) (idx + '0'), CellUtil.cloneValue(val)[0]); 599 System.out.println(entry.getKey() + " " + val); 600 idx++; 601 } 602 } finally { 603 if (reader != null) { 604 reader.close(); 605 } 606 } 607 } 608 609 /** 610 * Test that we can visit entries before they are appended 611 * @throws Exception 612 */ 613 @Test 614 public void testVisitors() throws Exception { 615 final int COL_COUNT = 10; 616 final TableName tableName = TableName.valueOf(currentTest.getMethodName()); 617 final byte [] row = Bytes.toBytes("row"); 618 final DumbWALActionsListener visitor = new DumbWALActionsListener(); 619 final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1); 620 long timestamp = System.currentTimeMillis(); 621 NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR); 622 scopes.put(Bytes.toBytes("column"), 0); 623 624 RegionInfo hri = RegionInfoBuilder.newBuilder(tableName).build(); 625 final WAL log = wals.getWAL(hri); 626 log.registerWALActionsListener(visitor); 627 for (int i = 0; i < COL_COUNT; i++) { 628 WALEdit cols = new WALEdit(); 629 cols.add(new KeyValue(row, Bytes.toBytes("column"), 630 Bytes.toBytes(Integer.toString(i)), 631 timestamp, new byte[]{(byte) (i + '0')})); 632 log.append(hri, new WALKeyImpl(hri.getEncodedNameAsBytes(), tableName, 633 System.currentTimeMillis(), mvcc, scopes), cols, true); 634 } 635 log.sync(); 636 assertEquals(COL_COUNT, visitor.increments); 637 log.unregisterWALActionsListener(visitor); 638 WALEdit cols = new WALEdit(); 639 cols.add(new KeyValue(row, Bytes.toBytes("column"), 640 Bytes.toBytes(Integer.toString(11)), 641 timestamp, new byte[]{(byte) (11 + '0')})); 642 log.append(hri, new WALKeyImpl(hri.getEncodedNameAsBytes(), tableName, 643 System.currentTimeMillis(), mvcc, scopes), cols, true); 644 log.sync(); 645 assertEquals(COL_COUNT, visitor.increments); 646 } 647 648 /** 649 * A loaded WAL coprocessor won't break existing WAL test cases. 650 */ 651 @Test 652 public void testWALCoprocessorLoaded() throws Exception { 653 // test to see whether the coprocessor is loaded or not. 654 WALCoprocessorHost host = wals.getWAL(null).getCoprocessorHost(); 655 Coprocessor c = host.findCoprocessor(SampleRegionWALCoprocessor.class); 656 assertNotNull(c); 657 } 658 659 static class DumbWALActionsListener implements WALActionsListener { 660 int increments = 0; 661 662 @Override 663 public void visitLogEntryBeforeWrite(RegionInfo info, WALKey logKey, WALEdit logEdit) { 664 increments++; 665 } 666 667 @Override 668 public void visitLogEntryBeforeWrite(WALKey logKey, WALEdit logEdit) { 669 // To change body of implemented methods use File | Settings | File 670 // Templates. 671 increments++; 672 } 673 } 674}