Java Code Examples for org.apache.hadoop.hdfs.DFSTestUtil#formatNameNode()

The following examples show how to use org.apache.hadoop.hdfs.DFSTestUtil#formatNameNode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestFSNamesystem.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Test that FSNamesystem#clear clears all leases.
 */
@Test
public void testFSNamespaceClearLeases() throws Exception {
  Configuration conf = new HdfsConfiguration();
  File nameDir = new File(MiniDFSCluster.getBaseDirectory(), "name");
  conf.set(DFS_NAMENODE_NAME_DIR_KEY, nameDir.getAbsolutePath());

  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);
  LeaseManager leaseMan = fsn.getLeaseManager();
  leaseMan.addLease("client1", "importantFile");
  assertEquals(1, leaseMan.countLease());
  fsn.clear();
  leaseMan = fsn.getLeaseManager();
  assertEquals(0, leaseMan.countLease());
}
 
Example 2
Source File: TestValidateConfigurationSettings.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Tests setting the rpc port to the same as the web port to test that 
 * an exception
 * is thrown when trying to re-use the same port
 */
@Test(expected = BindException.class, timeout = 300000)
public void testThatMatchingRPCandHttpPortsThrowException() 
    throws IOException {

  NameNode nameNode = null;
  try {
    Configuration conf = new HdfsConfiguration();
    File nameDir = new File(MiniDFSCluster.getBaseDirectory(), "name");
    conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
        nameDir.getAbsolutePath());

    Random rand = new Random();
    final int port = 30000 + rand.nextInt(30000);

    // set both of these to the same port. It should fail.
    FileSystem.setDefaultUri(conf, "hdfs://localhost:" + port);
    conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "127.0.0.1:" + port);
    DFSTestUtil.formatNameNode(conf);
    nameNode = new NameNode(conf);
  } finally {
    if (nameNode != null) {
      nameNode.stop();
    }
  }
}
 
Example 3
Source File: TestSaveNamespace.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Test (timeout=30000)
public void testSaveWhileEditsRolled() throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  try {
    doAnEdit(fsn, 1);
    CheckpointSignature sig = fsn.rollEditLog();
    LOG.warn("Checkpoint signature: " + sig);
    // Do another edit
    doAnEdit(fsn, 2);

    // Save namespace
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    fsn.saveNamespace();

    // Now shut down and restart the NN
    fsn.close();
    fsn = null;

    // Start a new namesystem, which should be able to recover
    // the namespace from the previous incarnation.
    fsn = FSNamesystem.loadFromDisk(conf);

    // Make sure the image loaded including our edits.
    checkEditExists(fsn, 1);
    checkEditExists(fsn, 2);
  } finally {
    if (fsn != null) {
      fsn.close();
    }
  }
}
 
Example 4
Source File: TestCreateEditsLog.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that an edits log created using CreateEditsLog is valid and can be
 * loaded successfully by a namenode.
 */
@Test(timeout=60000)
public void testCanLoadCreatedEditsLog() throws Exception {
  // Format namenode.
  HdfsConfiguration conf = new HdfsConfiguration();
  File nameDir = new File(HDFS_DIR, "name");
  conf.set(DFS_NAMENODE_NAME_DIR_KEY, Util.fileAsURI(nameDir).toString());
  DFSTestUtil.formatNameNode(conf);

  // Call CreateEditsLog and move the resulting edits to the name dir.
  CreateEditsLog.main(new String[] { "-f", "1000", "0", "1", "-d",
    TEST_DIR.getAbsolutePath() });
  Path editsWildcard = new Path(TEST_DIR.getAbsolutePath(), "*");
  FileContext localFc = FileContext.getLocalFSFileContext();
  for (FileStatus edits: localFc.util().globStatus(editsWildcard)) {
    Path src = edits.getPath();
    Path dst = new Path(new File(nameDir, "current").getAbsolutePath(),
      src.getName());
    localFc.rename(src, dst);
  }

  // Start a namenode to try to load the edits.
  cluster = new MiniDFSCluster.Builder(conf)
    .format(false)
    .manageNameDfsDirs(false)
    .waitSafeMode(false)
    .build();
  cluster.waitClusterUp();

  // Test successful, because no exception thrown.
}
 
Example 5
Source File: TestNNThroughputBenchmark.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * This test runs all benchmarks defined in {@link NNThroughputBenchmark}.
 */
@Test
public void testNNThroughput() throws Exception {
  Configuration conf = new HdfsConfiguration();
  File nameDir = new File(MiniDFSCluster.getBaseDirectory(), "name");
  conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
      nameDir.getAbsolutePath());
  FileSystem.setDefaultUri(conf, "hdfs://localhost:" + 0);
  conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "0.0.0.0:0");
  DFSTestUtil.formatNameNode(conf);
  String[] args = new String[] {"-op", "all"};
  NNThroughputBenchmark.runBenchmark(conf, Arrays.asList(args));
}
 
Example 6
Source File: TestValidateConfigurationSettings.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * HDFS-3013: NameNode format command doesn't pick up
 * dfs.namenode.name.dir.NameServiceId configuration.
 */
@Test(timeout = 300000)
public void testGenericKeysForNameNodeFormat()
    throws IOException {
  Configuration conf = new HdfsConfiguration();

  // Set ephemeral ports 
  conf.set(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY,
      "127.0.0.1:0");
  conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY,
      "127.0.0.1:0");
  
  conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1");
  
  // Set a nameservice-specific configuration for name dir
  File dir = new File(MiniDFSCluster.getBaseDirectory(),
      "testGenericKeysForNameNodeFormat");
  if (dir.exists()) {
    FileUtil.fullyDelete(dir);
  }
  conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY + ".ns1",
      dir.getAbsolutePath());
  
  // Format and verify the right dir is formatted.
  DFSTestUtil.formatNameNode(conf);
  GenericTestUtils.assertExists(dir);

  // Ensure that the same dir is picked up by the running NN
  NameNode nameNode = new NameNode(conf);
  nameNode.stop();
}
 
Example 7
Source File: TestValidateConfigurationSettings.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Tests setting the rpc port to a different as the web port that an 
 * exception is NOT thrown 
 */
@Test(timeout = 300000)
public void testThatDifferentRPCandHttpPortsAreOK() 
    throws IOException {

  Configuration conf = new HdfsConfiguration();
  File nameDir = new File(MiniDFSCluster.getBaseDirectory(), "name");
  conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
      nameDir.getAbsolutePath());

  Random rand = new Random();

  // A few retries in case the ports we choose are in use.
  for (int i = 0; i < 5; ++i) {
    final int port1 = 30000 + rand.nextInt(10000);
    final int port2 = port1 + 1 + rand.nextInt(10000);

    FileSystem.setDefaultUri(conf, "hdfs://localhost:" + port1);
    conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "127.0.0.1:" + port2);
    DFSTestUtil.formatNameNode(conf);
    NameNode nameNode = null;

    try {
      nameNode = new NameNode(conf); // should be OK!
      break;
    } catch(BindException be) {
      continue;     // Port in use? Try another.
    } finally {
      if (nameNode != null) {
        nameNode.stop();
      }
    }
  }
}
 
Example 8
Source File: TestValidateConfigurationSettings.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Tests setting the rpc port to a different as the web port that an 
 * exception is NOT thrown 
 */
@Test(timeout = 300000)
public void testThatDifferentRPCandHttpPortsAreOK() 
    throws IOException {

  Configuration conf = new HdfsConfiguration();
  File nameDir = new File(MiniDFSCluster.getBaseDirectory(), "name");
  conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
      nameDir.getAbsolutePath());

  Random rand = new Random();

  // A few retries in case the ports we choose are in use.
  for (int i = 0; i < 5; ++i) {
    final int port1 = 30000 + rand.nextInt(10000);
    final int port2 = port1 + 1 + rand.nextInt(10000);

    FileSystem.setDefaultUri(conf, "hdfs://localhost:" + port1);
    conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "127.0.0.1:" + port2);
    DFSTestUtil.formatNameNode(conf);
    NameNode nameNode = null;

    try {
      nameNode = new NameNode(conf); // should be OK!
      break;
    } catch(BindException be) {
      continue;     // Port in use? Try another.
    } finally {
      if (nameNode != null) {
        nameNode.stop();
      }
    }
  }
}
 
Example 9
Source File: TestSaveNamespace.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test (timeout=30000)
public void testTxIdPersistence() throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  try {
    // We have a BEGIN_LOG_SEGMENT txn to start
    assertEquals(1, fsn.getEditLog().getLastWrittenTxId());
    doAnEdit(fsn, 1);
    assertEquals(2, fsn.getEditLog().getLastWrittenTxId());
    
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    fsn.saveNamespace();

    // 2 more txns: END the first segment, BEGIN a new one
    assertEquals(4, fsn.getEditLog().getLastWrittenTxId());
    
    // Shut down and restart
    fsn.getFSImage().close();
    fsn.close();
    
    // 1 more txn to END that segment
    assertEquals(5, fsn.getEditLog().getLastWrittenTxId());
    fsn = null;
    
    fsn = FSNamesystem.loadFromDisk(conf);
    // 1 more txn to start new segment on restart
    assertEquals(6, fsn.getEditLog().getLastWrittenTxId());
    
  } finally {
    if (fsn != null) {
      fsn.close();
    }
  }
}
 
Example 10
Source File: TestSaveNamespace.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test (timeout=30000)
public void testSaveWhileEditsRolled() throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  try {
    doAnEdit(fsn, 1);
    CheckpointSignature sig = fsn.rollEditLog();
    LOG.warn("Checkpoint signature: " + sig);
    // Do another edit
    doAnEdit(fsn, 2);

    // Save namespace
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    fsn.saveNamespace();

    // Now shut down and restart the NN
    fsn.close();
    fsn = null;

    // Start a new namesystem, which should be able to recover
    // the namespace from the previous incarnation.
    fsn = FSNamesystem.loadFromDisk(conf);

    // Make sure the image loaded including our edits.
    checkEditExists(fsn, 1);
    checkEditExists(fsn, 2);
  } finally {
    if (fsn != null) {
      fsn.close();
    }
  }
}
 
Example 11
Source File: TestSaveNamespace.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test(timeout=20000)
public void testCancelSaveNamespace() throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  // Replace the FSImage with a spy
  final FSImage image = fsn.getFSImage();
  NNStorage storage = image.getStorage();
  storage.close(); // unlock any directories that FSNamesystem's initialization may have locked
  storage.setStorageDirectories(
      FSNamesystem.getNamespaceDirs(conf), 
      FSNamesystem.getNamespaceEditsDirs(conf));

  FSNamesystem spyFsn = spy(fsn);
  final FSNamesystem finalFsn = spyFsn;
  DelayAnswer delayer = new GenericTestUtils.DelayAnswer(LOG);
  BlockIdManager bid = spy(spyFsn.getBlockIdManager());
  Whitebox.setInternalState(finalFsn, "blockIdManager", bid);
  doAnswer(delayer).when(bid).getGenerationStampV2();

  ExecutorService pool = Executors.newFixedThreadPool(2);
  
  try {
    doAnEdit(fsn, 1);
    final Canceler canceler = new Canceler();
    
    // Save namespace
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    try {
      Future<Void> saverFuture = pool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          image.saveNamespace(finalFsn, NameNodeFile.IMAGE, canceler);
          return null;
        }
      });

      // Wait until saveNamespace calls getGenerationStamp
      delayer.waitForCall();
      // then cancel the saveNamespace
      Future<Void> cancelFuture = pool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          canceler.cancel("cancelled");
          return null;
        }
      });
      // give the cancel call time to run
      Thread.sleep(500);
      
      // allow saveNamespace to proceed - it should check the cancel flag after
      // this point and throw an exception
      delayer.proceed();

      cancelFuture.get();
      saverFuture.get();
      fail("saveNamespace did not fail even though cancelled!");
    } catch (Throwable t) {
      GenericTestUtils.assertExceptionContains(
          "SaveNamespaceCancelledException", t);
    }
    LOG.info("Successfully cancelled a saveNamespace");


    // Check that we have only the original image and not any
    // cruft left over from half-finished images
    FSImageTestUtil.logStorageContents(LOG, storage);
    for (StorageDirectory sd : storage.dirIterable(null)) {
      File curDir = sd.getCurrentDir();
      GenericTestUtils.assertGlobEquals(curDir, "fsimage_.*",
          NNStorage.getImageFileName(0),
          NNStorage.getImageFileName(0) + MD5FileUtils.MD5_SUFFIX);
    }      
  } finally {
    fsn.close();
  }
}
 
Example 12
Source File: TestSaveNamespace.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * Injects a failure on all storage directories while saving namespace.
 *
 * @param restoreStorageAfterFailure if true, will try to save again after
 *   clearing the failure injection
 */
public void doTestFailedSaveNamespace(boolean restoreStorageAfterFailure)
throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  // Replace the FSImage with a spy
  final FSImage originalImage = fsn.getFSImage();
  NNStorage storage = originalImage.getStorage();
  storage.close(); // unlock any directories that FSNamesystem's initialization may have locked

  NNStorage spyStorage = spy(storage);
  originalImage.storage = spyStorage;
  FSImage spyImage = spy(originalImage);
  Whitebox.setInternalState(fsn, "fsImage", spyImage);

  spyImage.storage.setStorageDirectories(
      FSNamesystem.getNamespaceDirs(conf), 
      FSNamesystem.getNamespaceEditsDirs(conf));

  doThrow(new IOException("Injected fault: saveFSImage")).
      when(spyImage).saveFSImage(
          (SaveNamespaceContext)anyObject(),
          (StorageDirectory)anyObject(), (NameNodeFile) anyObject());

  try {
    doAnEdit(fsn, 1);

    // Save namespace
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    try {
      fsn.saveNamespace();
      fail("saveNamespace did not fail even when all directories failed!");
    } catch (IOException ioe) {
      LOG.info("Got expected exception", ioe);
    }
    
    // Ensure that, if storage dirs come back online, things work again.
    if (restoreStorageAfterFailure) {
      Mockito.reset(spyImage);
      spyStorage.setRestoreFailedStorage(true);
      fsn.saveNamespace();
      checkEditExists(fsn, 1);
    }

    // Now shut down and restart the NN
    originalImage.close();
    fsn.close();
    fsn = null;

    // Start a new namesystem, which should be able to recover
    // the namespace from the previous incarnation.
    fsn = FSNamesystem.loadFromDisk(conf);

    // Make sure the image loaded including our edits.
    checkEditExists(fsn, 1);
  } finally {
    if (fsn != null) {
      fsn.close();
    }
  }
}
 
Example 13
Source File: TestSaveNamespace.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that a saveNamespace command brings faulty directories
 * in fs.name.dir and fs.edit.dir back online.
 */
@Test (timeout=30000)
public void testReinsertnamedirsInSavenamespace() throws Exception {
  // create a configuration with the key to restore error
  // directories in fs.name.dir
  Configuration conf = getConf();
  conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_RESTORE_KEY, true);

  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  // Replace the FSImage with a spy
  FSImage originalImage = fsn.getFSImage();
  NNStorage storage = originalImage.getStorage();

  FSImage spyImage = spy(originalImage);
  Whitebox.setInternalState(fsn, "fsImage", spyImage);
  
  FileSystem fs = FileSystem.getLocal(conf);
  File rootDir = storage.getStorageDir(0).getRoot();
  Path rootPath = new Path(rootDir.getPath(), "current");
  final FsPermission permissionNone = new FsPermission((short) 0);
  final FsPermission permissionAll = new FsPermission(
      FsAction.ALL, FsAction.READ_EXECUTE, FsAction.READ_EXECUTE);
  fs.setPermission(rootPath, permissionNone);

  try {
    doAnEdit(fsn, 1);
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);

    // Save namespace - should mark the first storage dir as faulty
    // since it's not traversable.
    LOG.info("Doing the first savenamespace.");
    fsn.saveNamespace();
    LOG.info("First savenamespace sucessful.");      
    
    assertTrue("Savenamespace should have marked one directory as bad." +
               " But found " + storage.getRemovedStorageDirs().size() +
               " bad directories.", 
                 storage.getRemovedStorageDirs().size() == 1);

    fs.setPermission(rootPath, permissionAll);

    // The next call to savenamespace should try inserting the
    // erroneous directory back to fs.name.dir. This command should
    // be successful.
    LOG.info("Doing the second savenamespace.");
    fsn.saveNamespace();
    LOG.warn("Second savenamespace sucessful.");
    assertTrue("Savenamespace should have been successful in removing " +
               " bad directories from Image."  +
               " But found " + storage.getRemovedStorageDirs().size() +
               " bad directories.", 
               storage.getRemovedStorageDirs().size() == 0);

    // Now shut down and restart the namesystem
    LOG.info("Shutting down fsimage.");
    originalImage.close();
    fsn.close();      
    fsn = null;

    // Start a new namesystem, which should be able to recover
    // the namespace from the previous incarnation.
    LOG.info("Loading new FSmage from disk.");
    fsn = FSNamesystem.loadFromDisk(conf);

    // Make sure the image loaded including our edit.
    LOG.info("Checking reloaded image.");
    checkEditExists(fsn, 1);
    LOG.info("Reloaded image is good.");
  } finally {
    if (rootDir.exists()) {
      fs.setPermission(rootPath, permissionAll);
    }

    if (fsn != null) {
      try {
        fsn.close();
      } catch (Throwable t) {
        LOG.fatal("Failed to shut down", t);
      }
    }
  }
}
 
Example 14
Source File: TestSaveNamespace.java    From hadoop with Apache License 2.0 4 votes vote down vote up
private void saveNamespaceWithInjectedFault(Fault fault) throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  // Replace the FSImage with a spy
  FSImage originalImage = fsn.getFSImage();
  NNStorage storage = originalImage.getStorage();

  NNStorage spyStorage = spy(storage);
  originalImage.storage = spyStorage;

  FSImage spyImage = spy(originalImage);
  Whitebox.setInternalState(fsn, "fsImage", spyImage);

  boolean shouldFail = false; // should we expect the save operation to fail
  // inject fault
  switch(fault) {
  case SAVE_SECOND_FSIMAGE_RTE:
    // The spy throws a RuntimeException when writing to the second directory
    doAnswer(new FaultySaveImage(true)).
      when(spyImage).saveFSImage(
          (SaveNamespaceContext)anyObject(),
          (StorageDirectory)anyObject(), (NameNodeFile) anyObject());
    shouldFail = false;
    break;
  case SAVE_SECOND_FSIMAGE_IOE:
    // The spy throws an IOException when writing to the second directory
    doAnswer(new FaultySaveImage(false)).
      when(spyImage).saveFSImage(
          (SaveNamespaceContext)anyObject(),
          (StorageDirectory)anyObject(), (NameNodeFile) anyObject());
    shouldFail = false;
    break;
  case SAVE_ALL_FSIMAGES:
    // The spy throws IOException in all directories
    doThrow(new RuntimeException("Injected")).
    when(spyImage).saveFSImage(
        (SaveNamespaceContext)anyObject(),
        (StorageDirectory)anyObject(), (NameNodeFile) anyObject());
    shouldFail = true;
    break;
  case WRITE_STORAGE_ALL:
    // The spy throws an exception before writing any VERSION files
    doThrow(new RuntimeException("Injected"))
      .when(spyStorage).writeAll();
    shouldFail = true;
    break;
  case WRITE_STORAGE_ONE:
    // The spy throws on exception on one particular storage directory
    doAnswer(new FaultySaveImage(true))
      .when(spyStorage).writeProperties((StorageDirectory)anyObject());
    // TODO: unfortunately this fails -- should be improved.
    // See HDFS-2173.
    shouldFail = true;
    break;
  }

  try {
    doAnEdit(fsn, 1);

    // Save namespace - this may fail, depending on fault injected
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    try {
      fsn.saveNamespace();
      if (shouldFail) {
        fail("Did not fail!");
      }
    } catch (Exception e) {
      if (! shouldFail) {
        throw e;
      } else {
        LOG.info("Test caught expected exception", e);
      }
    }
    
    fsn.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);
    // Should still be able to perform edits
    doAnEdit(fsn, 2);

    // Now shut down and restart the namesystem
    originalImage.close();
    fsn.close();      
    fsn = null;

    // Start a new namesystem, which should be able to recover
    // the namespace from the previous incarnation.
    fsn = FSNamesystem.loadFromDisk(conf);

    // Make sure the image loaded including our edits.
    checkEditExists(fsn, 1);
    checkEditExists(fsn, 2);
  } finally {
    if (fsn != null) {
      fsn.close();
    }
  }
}
 
Example 15
Source File: TestReplicationPolicyConsiderLoad.java    From big-c with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setupCluster() throws IOException {
  Configuration conf = new HdfsConfiguration();
  final String[] racks = {
      "/rack1",
      "/rack1",
      "/rack1",
      "/rack2",
      "/rack2",
      "/rack2"};
  storages = DFSTestUtil.createDatanodeStorageInfos(racks);
  dataNodes = DFSTestUtil.toDatanodeDescriptor(storages);
  FileSystem.setDefaultUri(conf, "hdfs://localhost:0");
  conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "0.0.0.0:0");
  File baseDir = PathUtils.getTestDir(TestReplicationPolicy.class);
  conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
      new File(baseDir, "name").getPath());
  conf.setBoolean(
      DFSConfigKeys.DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_READ_KEY, true);
  conf.setBoolean(
      DFSConfigKeys.DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_WRITE_KEY, true);
  conf.setBoolean(
      DFSConfigKeys.DFS_NAMENODE_REPLICATION_CONSIDERLOAD_KEY, true);
  DFSTestUtil.formatNameNode(conf);
  namenode = new NameNode(conf);
  int blockSize = 1024;

  dnrList = new ArrayList<DatanodeRegistration>();
  dnManager = namenode.getNamesystem().getBlockManager().getDatanodeManager();

  // Register DNs
  for (int i=0; i < 6; i++) {
    DatanodeRegistration dnr = new DatanodeRegistration(dataNodes[i],
        new StorageInfo(NodeType.DATA_NODE), new ExportedBlockKeys(),
        VersionInfo.getVersion());
    dnrList.add(dnr);
    dnManager.registerDatanode(dnr);
    dataNodes[i].getStorageInfos()[0].setUtilizationForTesting(
        2*HdfsConstants.MIN_BLOCKS_FOR_WRITE*blockSize, 0L,
        2*HdfsConstants.MIN_BLOCKS_FOR_WRITE*blockSize, 0L);
    dataNodes[i].updateHeartbeat(
        BlockManagerTestUtil.getStorageReportsForDatanode(dataNodes[i]),
        0L, 0L, 0, 0, null);
  }
}
 
Example 16
Source File: TestSaveNamespace.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Test(timeout=20000)
public void testCancelSaveNamespace() throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  // Replace the FSImage with a spy
  final FSImage image = fsn.getFSImage();
  NNStorage storage = image.getStorage();
  storage.close(); // unlock any directories that FSNamesystem's initialization may have locked
  storage.setStorageDirectories(
      FSNamesystem.getNamespaceDirs(conf), 
      FSNamesystem.getNamespaceEditsDirs(conf));

  FSNamesystem spyFsn = spy(fsn);
  final FSNamesystem finalFsn = spyFsn;
  DelayAnswer delayer = new GenericTestUtils.DelayAnswer(LOG);
  BlockIdManager bid = spy(spyFsn.getBlockIdManager());
  Whitebox.setInternalState(finalFsn, "blockIdManager", bid);
  doAnswer(delayer).when(bid).getGenerationStampV2();

  ExecutorService pool = Executors.newFixedThreadPool(2);
  
  try {
    doAnEdit(fsn, 1);
    final Canceler canceler = new Canceler();
    
    // Save namespace
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    try {
      Future<Void> saverFuture = pool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          image.saveNamespace(finalFsn, NameNodeFile.IMAGE, canceler);
          return null;
        }
      });

      // Wait until saveNamespace calls getGenerationStamp
      delayer.waitForCall();
      // then cancel the saveNamespace
      Future<Void> cancelFuture = pool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          canceler.cancel("cancelled");
          return null;
        }
      });
      // give the cancel call time to run
      Thread.sleep(500);
      
      // allow saveNamespace to proceed - it should check the cancel flag after
      // this point and throw an exception
      delayer.proceed();

      cancelFuture.get();
      saverFuture.get();
      fail("saveNamespace did not fail even though cancelled!");
    } catch (Throwable t) {
      GenericTestUtils.assertExceptionContains(
          "SaveNamespaceCancelledException", t);
    }
    LOG.info("Successfully cancelled a saveNamespace");


    // Check that we have only the original image and not any
    // cruft left over from half-finished images
    FSImageTestUtil.logStorageContents(LOG, storage);
    for (StorageDirectory sd : storage.dirIterable(null)) {
      File curDir = sd.getCurrentDir();
      GenericTestUtils.assertGlobEquals(curDir, "fsimage_.*",
          NNStorage.getImageFileName(0),
          NNStorage.getImageFileName(0) + MD5FileUtils.MD5_SUFFIX);
    }      
  } finally {
    fsn.close();
  }
}
 
Example 17
Source File: TestSaveNamespace.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * Injects a failure on all storage directories while saving namespace.
 *
 * @param restoreStorageAfterFailure if true, will try to save again after
 *   clearing the failure injection
 */
public void doTestFailedSaveNamespace(boolean restoreStorageAfterFailure)
throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  // Replace the FSImage with a spy
  final FSImage originalImage = fsn.getFSImage();
  NNStorage storage = originalImage.getStorage();
  storage.close(); // unlock any directories that FSNamesystem's initialization may have locked

  NNStorage spyStorage = spy(storage);
  originalImage.storage = spyStorage;
  FSImage spyImage = spy(originalImage);
  Whitebox.setInternalState(fsn, "fsImage", spyImage);

  spyImage.storage.setStorageDirectories(
      FSNamesystem.getNamespaceDirs(conf), 
      FSNamesystem.getNamespaceEditsDirs(conf));

  doThrow(new IOException("Injected fault: saveFSImage")).
      when(spyImage).saveFSImage(
          (SaveNamespaceContext)anyObject(),
          (StorageDirectory)anyObject(), (NameNodeFile) anyObject());

  try {
    doAnEdit(fsn, 1);

    // Save namespace
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    try {
      fsn.saveNamespace();
      fail("saveNamespace did not fail even when all directories failed!");
    } catch (IOException ioe) {
      LOG.info("Got expected exception", ioe);
    }
    
    // Ensure that, if storage dirs come back online, things work again.
    if (restoreStorageAfterFailure) {
      Mockito.reset(spyImage);
      spyStorage.setRestoreFailedStorage(true);
      fsn.saveNamespace();
      checkEditExists(fsn, 1);
    }

    // Now shut down and restart the NN
    originalImage.close();
    fsn.close();
    fsn = null;

    // Start a new namesystem, which should be able to recover
    // the namespace from the previous incarnation.
    fsn = FSNamesystem.loadFromDisk(conf);

    // Make sure the image loaded including our edits.
    checkEditExists(fsn, 1);
  } finally {
    if (fsn != null) {
      fsn.close();
    }
  }
}
 
Example 18
Source File: TestSaveNamespace.java    From big-c with Apache License 2.0 4 votes vote down vote up
private void saveNamespaceWithInjectedFault(Fault fault) throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  // Replace the FSImage with a spy
  FSImage originalImage = fsn.getFSImage();
  NNStorage storage = originalImage.getStorage();

  NNStorage spyStorage = spy(storage);
  originalImage.storage = spyStorage;

  FSImage spyImage = spy(originalImage);
  Whitebox.setInternalState(fsn, "fsImage", spyImage);

  boolean shouldFail = false; // should we expect the save operation to fail
  // inject fault
  switch(fault) {
  case SAVE_SECOND_FSIMAGE_RTE:
    // The spy throws a RuntimeException when writing to the second directory
    doAnswer(new FaultySaveImage(true)).
      when(spyImage).saveFSImage(
          (SaveNamespaceContext)anyObject(),
          (StorageDirectory)anyObject(), (NameNodeFile) anyObject());
    shouldFail = false;
    break;
  case SAVE_SECOND_FSIMAGE_IOE:
    // The spy throws an IOException when writing to the second directory
    doAnswer(new FaultySaveImage(false)).
      when(spyImage).saveFSImage(
          (SaveNamespaceContext)anyObject(),
          (StorageDirectory)anyObject(), (NameNodeFile) anyObject());
    shouldFail = false;
    break;
  case SAVE_ALL_FSIMAGES:
    // The spy throws IOException in all directories
    doThrow(new RuntimeException("Injected")).
    when(spyImage).saveFSImage(
        (SaveNamespaceContext)anyObject(),
        (StorageDirectory)anyObject(), (NameNodeFile) anyObject());
    shouldFail = true;
    break;
  case WRITE_STORAGE_ALL:
    // The spy throws an exception before writing any VERSION files
    doThrow(new RuntimeException("Injected"))
      .when(spyStorage).writeAll();
    shouldFail = true;
    break;
  case WRITE_STORAGE_ONE:
    // The spy throws on exception on one particular storage directory
    doAnswer(new FaultySaveImage(true))
      .when(spyStorage).writeProperties((StorageDirectory)anyObject());
    // TODO: unfortunately this fails -- should be improved.
    // See HDFS-2173.
    shouldFail = true;
    break;
  }

  try {
    doAnEdit(fsn, 1);

    // Save namespace - this may fail, depending on fault injected
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    try {
      fsn.saveNamespace();
      if (shouldFail) {
        fail("Did not fail!");
      }
    } catch (Exception e) {
      if (! shouldFail) {
        throw e;
      } else {
        LOG.info("Test caught expected exception", e);
      }
    }
    
    fsn.setSafeMode(SafeModeAction.SAFEMODE_LEAVE);
    // Should still be able to perform edits
    doAnEdit(fsn, 2);

    // Now shut down and restart the namesystem
    originalImage.close();
    fsn.close();      
    fsn = null;

    // Start a new namesystem, which should be able to recover
    // the namespace from the previous incarnation.
    fsn = FSNamesystem.loadFromDisk(conf);

    // Make sure the image loaded including our edits.
    checkEditExists(fsn, 1);
    checkEditExists(fsn, 2);
  } finally {
    if (fsn != null) {
      fsn.close();
    }
  }
}
 
Example 19
Source File: TestReplicationPolicy.java    From big-c with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setupCluster() throws Exception {
  Configuration conf = new HdfsConfiguration();
  final String[] racks = {
      "/d1/r1",
      "/d1/r1",
      "/d1/r2",
      "/d1/r2",
      "/d2/r3",
      "/d2/r3"};
  storages = DFSTestUtil.createDatanodeStorageInfos(racks);
  dataNodes = DFSTestUtil.toDatanodeDescriptor(storages);

  FileSystem.setDefaultUri(conf, "hdfs://localhost:0");
  conf.set(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY, "0.0.0.0:0");
  File baseDir = PathUtils.getTestDir(TestReplicationPolicy.class);
  conf.set(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY,
      new File(baseDir, "name").getPath());

  conf.setBoolean(
      DFSConfigKeys.DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_READ_KEY, true);
  conf.setBoolean(
      DFSConfigKeys.DFS_NAMENODE_AVOID_STALE_DATANODE_FOR_WRITE_KEY, true);
  DFSTestUtil.formatNameNode(conf);
  namenode = new NameNode(conf);

  final BlockManager bm = namenode.getNamesystem().getBlockManager();
  replicator = bm.getBlockPlacementPolicy();
  cluster = bm.getDatanodeManager().getNetworkTopology();
  // construct network topology
  for (int i=0; i < NUM_OF_DATANODES; i++) {
    cluster.add(dataNodes[i]);
    bm.getDatanodeManager().getHeartbeatManager().addDatanode(
        dataNodes[i]);
  }
  for (int i=0; i < NUM_OF_DATANODES; i++) {
    updateHeartbeatWithUsage(dataNodes[i],
        2*HdfsConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L,
        2*HdfsConstants.MIN_BLOCKS_FOR_WRITE*BLOCK_SIZE, 0L, 0L, 0L, 0, 0);
  }    
}
 
Example 20
Source File: TestDataNodeMultipleRegistrations.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Test
public void testDNWithInvalidStorageWithHA() throws Exception {
  MiniDFSNNTopology top = new MiniDFSNNTopology()
    .addNameservice(new MiniDFSNNTopology.NSConf("ns1")
      .addNN(new MiniDFSNNTopology.NNConf("nn0").setClusterId("cluster-1"))
      .addNN(new MiniDFSNNTopology.NNConf("nn1").setClusterId("cluster-1")));

  top.setFederation(true);

  MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).nnTopology(top)
      .numDataNodes(0).build();
  try {
    cluster.startDataNodes(conf, 1, true, null, null);
    // let the initialization be complete
    Thread.sleep(10000);
    DataNode dn = cluster.getDataNodes().get(0);
    assertTrue("Datanode should be running", dn.isDatanodeUp());
    assertEquals("BPOfferService should be running", 1,
        dn.getAllBpOs().length);
    DataNodeProperties dnProp = cluster.stopDataNode(0);

    cluster.getNameNode(0).stop();
    cluster.getNameNode(1).stop();
    Configuration nn1 = cluster.getConfiguration(0);
    Configuration nn2 = cluster.getConfiguration(1);
    // setting up invalid cluster
    StartupOption.FORMAT.setClusterId("cluster-2");
    DFSTestUtil.formatNameNode(nn1);
    MiniDFSCluster.copyNameDirs(FSNamesystem.getNamespaceDirs(nn1),
        FSNamesystem.getNamespaceDirs(nn2), nn2);
    cluster.restartNameNode(0, false);
    cluster.restartNameNode(1, false);
    cluster.restartDataNode(dnProp);
    
    // let the initialization be complete
    Thread.sleep(10000);
    dn = cluster.getDataNodes().get(0);
    assertFalse("Datanode should have shutdown as only service failed",
        dn.isDatanodeUp());
  } finally {
    cluster.shutdown();
  }
}