public void checkKeyRotation() {
        if (!isEncrypted()) {
            return;
        }
        long keyValidSec = Config.key_rotation_days * 24 * 3600;
        keysLock.writeLock().lock();
        try {
            if (idToKey.isEmpty()) {
                return;
            }
            EncryptionKey lastKEK = idToKey.lastEntry().getValue();
            Preconditions.checkState(lastKEK.isKEK(), "should be KEK:" + lastKEK);
            long now = System.currentTimeMillis() / 1000;
            if (lastKEK.createTime + keyValidSec <= now) {
                generateNewKEK();
            }
            if (MetricRepo.hasInit) {
                MetricRepo.GAUGE_ENCRYPTION_KEY_NUM.setValue((long) idToKey.size());
            }
        } finally {
            keysLock.writeLock().unlock();
        }
    }
@Test
    public void testCheckKeyRotation() {
        String oldConfig = Config.default_master_key;
        try {
            Config.default_master_key = "plain:aes_128:enwSdCUAiCLLx2Bs9E/neQ==";
            KeyMgr keyMgr = new KeyMgr();
            EncryptionKeyPB pb = new EncryptionKeyPB();
            pb.id = 1L;
            pb.algorithm = EncryptionAlgorithmPB.AES_128;
            pb.encryptedKey = new byte[16];
            pb.type = EncryptionKeyTypePB.NORMAL_KEY;
            pb.createTime = 1L;
            keyMgr.replayAddKey(pb);
            Assert.assertEquals(1, keyMgr.numKeys());
            EncryptionKey root = keyMgr.getKeyById(1);
            byte[] plainKey = new byte[16];
            plainKey[0] = 1;
            plainKey[8] = 1;
            ((NormalKey) root).setPlainKey(plainKey);
            EncryptionKey kek = root.generateKey();
            kek.id = 2;
            EncryptionKeyPB pb2 = new EncryptionKeyPB();
            kek.toPB(pb2, keyMgr);
            // set time to 1 so rotation do happen
            pb2.createTime = 1L;
            keyMgr.replayAddKey(pb2);
            Assert.assertEquals(2, keyMgr.numKeys());
            keyMgr.checkKeyRotation();
            Assert.assertEquals(3, keyMgr.numKeys());
        } finally {
            Config.default_master_key = oldConfig;
        }
    }