KeyManager implements Closeable, DataEncryptionKeyFactory { @Override public DataEncryptionKey newDataEncryptionKey() { if (encryptDataTransfer) { synchronized (this) { if (encryptionKey == null || encryptionKey.expiryDate < timer.now()) { LOG.debug("Generating new data encryption key because current key " + (encryptionKey == null ? "is null." : "expired on " + encryptionKey.expiryDate)); encryptionKey = blockTokenSecretManager.generateDataEncryptionKey(); } return encryptionKey; } } else { return null; } } KeyManager(String blockpoolID, NamenodeProtocol namenode,
      boolean encryptDataTransfer, Configuration conf); void startBlockKeyUpdater(); Token<BlockTokenIdentifier> getAccessToken(ExtendedBlock eb,
      StorageType[] storageTypes, String[] storageIds); @Override DataEncryptionKey newDataEncryptionKey(); @Override void close();  }
@Test public void testNewDataEncryptionKey() throws Exception { final Configuration conf = new HdfsConfiguration(); conf.setBoolean(DFSConfigKeys.DFS_ENCRYPT_DATA_TRANSFER_KEY, true); conf.setBoolean(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, true); final long keyUpdateInterval = 2 * 1000; final long tokenLifeTime = keyUpdateInterval; final String blockPoolId = "bp-foo"; FakeTimer fakeTimer = new FakeTimer(); BlockTokenSecretManager btsm = new BlockTokenSecretManager( keyUpdateInterval, tokenLifeTime, 0, 1, blockPoolId, null, false); Whitebox.setInternalState(btsm, "timer", fakeTimer); NamenodeProtocol namenode = mock(NamenodeProtocol.class); when(namenode.getBlockKeys()).thenReturn(btsm.exportKeys()); KeyManager keyManager = new KeyManager(blockPoolId, namenode, true, conf); Whitebox.setInternalState(keyManager, "timer", fakeTimer); Whitebox.setInternalState( Whitebox.getInternalState(keyManager, "blockTokenSecretManager"), "timer", fakeTimer); final DataEncryptionKey dek = keyManager.newDataEncryptionKey(); final long remainingTime = dek.expiryDate - fakeTimer.now(); assertEquals("KeyManager dataEncryptionKey should expire in 2 seconds", keyUpdateInterval, remainingTime); fakeTimer.advance(keyUpdateInterval + 1); final DataEncryptionKey dekAfterExpiration = keyManager.newDataEncryptionKey(); assertNotEquals("KeyManager should generate a new data encryption key", dek, dekAfterExpiration); assertTrue("KeyManager has an expired DataEncryptionKey!", dekAfterExpiration.expiryDate > fakeTimer.now()); }