org.apache.bookkeeper.stats.NullStatsLogger Java Examples

The following examples show how to use org.apache.bookkeeper.stats.NullStatsLogger. 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: TestEntry.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testWriteTooLongRecord() throws Exception {
    Writer writer = Entry.newEntry(
            "test-write-too-long-record",
            1024,
            false,
            CompressionCodec.Type.NONE,
            NullStatsLogger.INSTANCE);
    assertEquals("zero bytes", 0, writer.getNumBytes());
    assertEquals("zero records", 0, writer.getNumRecords());

    LogRecord largeRecord = new LogRecord(1L, new byte[MAX_LOGRECORD_SIZE + 1]);
    try {
        writer.writeRecord(largeRecord, new Promise<DLSN>());
        Assert.fail("Should fail on writing large record");
    } catch (LogRecordTooLongException lrtle) {
        // expected
    }
    assertEquals("zero bytes", 0, writer.getNumBytes());
    assertEquals("zero records", 0, writer.getNumRecords());

    Buffer buffer = writer.getBuffer();
    Assert.assertEquals("zero bytes", 0, buffer.size());
}
 
Example #2
Source File: TestBKLogSegmentWriter.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
private BKLogSegmentWriter createLogSegmentWriter(DistributedLogConfiguration conf,
                                                  long logSegmentSequenceNumber,
                                                  long startTxId,
                                                  ZKDistributedLock lock) throws Exception {
    LedgerHandle lh = bkc.get().createLedger(3, 2, 2,
            BookKeeper.DigestType.CRC32, conf.getBKDigestPW().getBytes(UTF_8));
    return new BKLogSegmentWriter(
            runtime.getMethodName(),
            runtime.getMethodName(),
            conf,
            LogSegmentMetadata.LEDGER_METADATA_CURRENT_LAYOUT_VERSION,
            new BKLogSegmentEntryWriter(lh),
            lock,
            startTxId,
            logSegmentSequenceNumber,
            scheduler,
            NullStatsLogger.INSTANCE,
            NullStatsLogger.INSTANCE,
            new AlertStatsLogger(NullStatsLogger.INSTANCE, "test"),
            PermitLimiter.NULL_PERMIT_LIMITER,
            new SettableFeatureProvider("", 0),
            ConfUtils.getConstDynConf(conf));
}
 
Example #3
Source File: TestDistributedLogService.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
private DistributedLogServiceImpl createService(
        ServerConfiguration serverConf,
        DistributedLogConfiguration dlConf,
        CountDownLatch latch) throws Exception {
    // Build the stream partition converter
    StreamPartitionConverter converter;
    try {
        converter = ReflectionUtils.newInstance(serverConf.getStreamPartitionConverterClass());
    } catch (ConfigurationException e) {
        logger.warn("Failed to load configured stream-to-partition converter. Fallback to use {}",
                IdentityStreamPartitionConverter.class.getName());
        converter = new IdentityStreamPartitionConverter();
    }
    return new DistributedLogServiceImpl(
            serverConf,
            dlConf,
            ConfUtils.getConstDynConf(dlConf),
            new NullStreamConfigProvider(),
            uri,
            converter,
            NullStatsLogger.INSTANCE,
            NullStatsLogger.INSTANCE,
            latch);
}
 
Example #4
Source File: ZkIsolatedBookieEnsemblePlacementPolicyTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoIsolationGroup() throws Exception {
    String data = "{\"group1\": {\"" + BOOKIE1
            + "\": {\"rack\": \"rack0\", \"hostname\": \"bookie1.example.com\"}, \"" + BOOKIE2
            + "\": {\"rack\": \"rack1\", \"hostname\": \"bookie2.example.com\"}}, \"group2\": {\"" + BOOKIE3
            + "\": {\"rack\": \"rack0\", \"hostname\": \"bookie3.example.com\"}, \"" + BOOKIE4
            + "\": {\"rack\": \"rack2\", \"hostname\": \"bookie4.example.com\"}}}";

    ZkUtils.createFullPathOptimistic(localZkc, ZkBookieRackAffinityMapping.BOOKIE_INFO_ROOT_PATH, data.getBytes(),
            ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    Thread.sleep(100);

    ZkIsolatedBookieEnsemblePlacementPolicy isolationPolicy = new ZkIsolatedBookieEnsemblePlacementPolicy();
    ClientConfiguration bkClientConf = new ClientConfiguration();
    bkClientConf.setProperty(ZooKeeperCache.ZK_CACHE_INSTANCE, new ZooKeeperCache("test", localZkc, 30) {
    });
    isolationPolicy.initialize(bkClientConf, Optional.empty(), timer, SettableFeatureProvider.DISABLE_ALL,
            NullStatsLogger.INSTANCE);
    isolationPolicy.onClusterChanged(writableBookies, readOnlyBookies);

    isolationPolicy.newEnsemble(4, 4, 4, Collections.emptyMap(), new HashSet<>());
}
 
Example #5
Source File: TestServiceRequestLimiter.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testDynamicLimiterWithException() throws Exception {
    final AtomicInteger id = new AtomicInteger(0);
    final DynamicDistributedLogConfiguration dynConf = new DynamicDistributedLogConfiguration(
            new ConcurrentConstConfiguration(new DistributedLogConfiguration()));
    DynamicRequestLimiter<MockRequest> limiter = new DynamicRequestLimiter<MockRequest>(
            dynConf, NullStatsLogger.INSTANCE, new SettableFeature("", 0)) {
        @Override
        public RequestLimiter<MockRequest> build() {
            if (id.incrementAndGet() >= 2) {
                throw new RuntimeException("exception in dynamic limiter build()");
            }
            return new MockRequestLimiter();
        }
    };
    limiter.initialize();
    assertEquals(1, id.get());
    try {
        dynConf.setProperty("test1", 1);
        fail("should have thrown on config failure");
    } catch (RuntimeException ex) {
    }
    assertEquals(2, id.get());
}
 
Example #6
Source File: AlterTablespaceSQLTest.java    From herddb with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultReplicaCount() throws Exception {
    String nodeId = "localhost";
    ServerConfiguration config = new ServerConfiguration();
    config.set(ServerConfiguration.PROPERTY_DEFAULT_REPLICA_COUNT, "4");
    try (DBManager manager = new DBManager(nodeId, new MemoryMetadataStorageManager(), new MemoryDataStorageManager(), new MemoryCommitLogManager(),
            null, null, config, NullStatsLogger.INSTANCE)) {
        manager.start();
        assertTrue(manager.waitForTablespace(TableSpace.DEFAULT, 10000));
        execute(manager, "CREATE TABLESPACE myts", Collections.emptyList());
        assertEquals(4, manager.getMetadataStorageManager().describeTableSpace("myts").expectedReplicaCount);
    }

    // default ServerConfiguration, defaults to 1
    try (DBManager manager = new DBManager(nodeId, new MemoryMetadataStorageManager(), new MemoryDataStorageManager(), new MemoryCommitLogManager(), null, null)) {
        manager.start();
        assertTrue(manager.waitForTablespace(TableSpace.DEFAULT, 10000));
        execute(manager, "CREATE TABLESPACE myts", Collections.emptyList());
        assertEquals(1, manager.getMetadataStorageManager().describeTableSpace("myts").expectedReplicaCount);
    }
}
 
Example #7
Source File: TestZooKeeperClient.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testAclFailedAuthenticationCanBeRecovered() throws Exception {
    FailingCredentials credentials = new FailingCredentials();
    ZooKeeperClient zkc = new ZooKeeperClient("test", 2000, 2000, zkServers,
            null, NullStatsLogger.INSTANCE, 1, 10000, credentials);

    try {
        zkc.get();
        fail("should have failed on auth");
    } catch (Exception ex) {
        assertEquals("authfailed", ex.getMessage());
    }

    // Should recover fine
    credentials.setShouldFail(false);
    zkc.get().create("/test", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    rmAll(zkc, "/test");
}
 
Example #8
Source File: TestServiceRequestLimiter.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
MockHardRequestLimiter(RateLimiter limiter) {
    this.limiter = new ComposableRequestLimiter<MockRequest>(
        limiter,
        new OverlimitFunction<MockRequest>() {
            public void apply(MockRequest request) throws OverCapacityException {
                limitHitCount++;
                throw new OverCapacityException("Limit exceeded");
            }
        },
        new CostFunction<MockRequest>() {
            public int apply(MockRequest request) {
                return request.getSize();
            }
        },
        NullStatsLogger.INSTANCE);
}
 
Example #9
Source File: TestServiceRequestLimiter.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
MockHardRequestLimiter(RateLimiter limiter) {
    this.limiter = new ComposableRequestLimiter<MockRequest>(
        limiter,
        new OverlimitFunction<MockRequest>() {
            public void apply(MockRequest request) throws OverCapacityException {
                limitHitCount++;
                throw new OverCapacityException("Limit exceeded");
            }
        },
        new CostFunction<MockRequest>() {
            public int apply(MockRequest request) {
                return request.getSize();
            }
        },
        NullStatsLogger.INSTANCE);
}
 
Example #10
Source File: TestServiceRequestLimiter.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testDynamicLimiter() throws Exception {
    final AtomicInteger id = new AtomicInteger(0);
    final DynamicDistributedLogConfiguration dynConf = new DynamicDistributedLogConfiguration(
            new ConcurrentConstConfiguration(new DistributedLogConfiguration()));
    DynamicRequestLimiter<MockRequest> limiter = new DynamicRequestLimiter<MockRequest>(
            dynConf, NullStatsLogger.INSTANCE, new SettableFeature("", 0)) {
        @Override
        public RequestLimiter<MockRequest> build() {
            id.getAndIncrement();
            return new MockRequestLimiter();
        }
    };
    limiter.initialize();
    assertEquals(1, id.get());
    dynConf.setProperty("test1", 1);
    assertEquals(2, id.get());
    dynConf.setProperty("test2", 2);
    assertEquals(3, id.get());
}
 
Example #11
Source File: TestServiceRequestLimiter.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testDynamicLimiterWithDisabledFeature() throws Exception {
    final DynamicDistributedLogConfiguration dynConf = new DynamicDistributedLogConfiguration(
            new ConcurrentConstConfiguration(new DistributedLogConfiguration()));
    final MockSoftRequestLimiter rateLimiter = new MockSoftRequestLimiter(0);
    final SettableFeature disabledFeature = new SettableFeature("", 0);
    DynamicRequestLimiter<MockRequest> limiter = new DynamicRequestLimiter<MockRequest>(
            dynConf, NullStatsLogger.INSTANCE, disabledFeature) {
        @Override
        public RequestLimiter<MockRequest> build() {
            return rateLimiter;
        }
    };
    limiter.initialize();
    assertEquals(0, rateLimiter.getLimitHitCount());

    // Not disabled, rate limiter was invoked
    limiter.apply(new MockRequest(Integer.MAX_VALUE));
    assertEquals(1, rateLimiter.getLimitHitCount());

    // Disabled, rate limiter not invoked
    disabledFeature.set(1);
    limiter.apply(new MockRequest(Integer.MAX_VALUE));
    assertEquals(1, rateLimiter.getLimitHitCount());
}
 
Example #12
Source File: TestBKLogSegmentWriter.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
private BKLogSegmentWriter createLogSegmentWriter(DistributedLogConfiguration conf,
                                                  long logSegmentSequenceNumber,
                                                  long startTxId,
                                                  ZKDistributedLock lock) throws Exception {
    LedgerHandle lh = bkc.get().createLedger(3, 2, 2,
            BookKeeper.DigestType.CRC32, conf.getBKDigestPW().getBytes(UTF_8));
    return new BKLogSegmentWriter(
            runtime.getMethodName(),
            runtime.getMethodName(),
            conf,
            LogSegmentMetadata.LEDGER_METADATA_CURRENT_LAYOUT_VERSION,
            new BKLogSegmentEntryWriter(lh),
            lock,
            startTxId,
            logSegmentSequenceNumber,
            scheduler,
            NullStatsLogger.INSTANCE,
            NullStatsLogger.INSTANCE,
            new AlertStatsLogger(NullStatsLogger.INSTANCE, "test"),
            PermitLimiter.NULL_PERMIT_LIMITER,
            new SettableFeatureProvider("", 0),
            ConfUtils.getConstDynConf(conf));
}
 
Example #13
Source File: TestLeastLoadPlacementPolicy.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 10000)
public void testCalculateBalances() throws Exception {
    int numSevers = new Random().nextInt(20) + 1;
    int numStreams = new Random().nextInt(200) + 1;
    RoutingService mockRoutingService = mock(RoutingService.class);
    Namespace mockNamespace = mock(Namespace.class);
    LeastLoadPlacementPolicy leastLoadPlacementPolicy = new LeastLoadPlacementPolicy(
        new EqualLoadAppraiser(),
        mockRoutingService,
        mockNamespace,
        null,
        Duration.fromSeconds(600),
        new NullStatsLogger());
    TreeSet<ServerLoad> serverLoads =
        Await.result(leastLoadPlacementPolicy.calculate(generateServers(numSevers), generateStreams(numStreams)));
    long lowLoadPerServer = numStreams / numSevers;
    long highLoadPerServer = lowLoadPerServer + 1;
    for (ServerLoad serverLoad : serverLoads) {
        long load = serverLoad.getLoad();
        assertEquals(load, serverLoad.getStreamLoads().size());
        assertTrue(String.format("Load %d is not between %d and %d",
            load, lowLoadPerServer, highLoadPerServer), load == lowLoadPerServer || load == highLoadPerServer);
    }
}
 
Example #14
Source File: TestDistributedLogService.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
private DistributedLogServiceImpl createService(
        ServerConfiguration serverConf,
        DistributedLogConfiguration dlConf,
        CountDownLatch latch) throws Exception {
    // Build the stream partition converter
    StreamPartitionConverter converter;
    try {
        converter = ReflectionUtils.newInstance(serverConf.getStreamPartitionConverterClass());
    } catch (ConfigurationException e) {
        logger.warn("Failed to load configured stream-to-partition converter. Fallback to use {}",
                IdentityStreamPartitionConverter.class.getName());
        converter = new IdentityStreamPartitionConverter();
    }
    return new DistributedLogServiceImpl(
        serverConf,
        dlConf,
        ConfUtils.getConstDynConf(dlConf),
        new NullStreamConfigProvider(),
        uri,
        converter,
        new LocalRoutingService(),
        NullStatsLogger.INSTANCE,
        NullStatsLogger.INSTANCE,
        latch,
        new EqualLoadAppraiser());
}
 
Example #15
Source File: LocalBookkeeperEnsemble.java    From pulsar with Apache License 2.0 6 votes vote down vote up
public void startBK() throws Exception {
    for (int i = 0; i < numberOfBookies; i++) {

        try {
            bs[i] = new BookieServer(bsConfs[i], NullStatsLogger.INSTANCE);
        } catch (InvalidCookieException e) {
            // InvalidCookieException can happen if the machine IP has changed
            // Since we are running here a local bookie that is always accessed
            // from localhost, we can ignore the error
            for (String path : zkc.getChildren("/ledgers/cookies", false)) {
                zkc.delete("/ledgers/cookies/" + path, -1);
            }

            // Also clean the on-disk cookie
            new File(new File(bsConfs[i].getJournalDirNames()[0], "current"), "VERSION").delete();

            // Retry to start the bookie after cleaning the old left cookie
            bs[i] = new BookieServer(bsConfs[i], NullStatsLogger.INSTANCE);

        }
        bs[i].start();
    }
}
 
Example #16
Source File: TestDistributedLock.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
public ZKDistributedLock createLock(int id, ZooKeeperClient zkc) throws Exception {
    SessionLockFactory lockFactory = new ZKSessionLockFactory(
            zkc,
            clientId + id,
            lockStateExecutor,
            0,
            Long.MAX_VALUE,
            sessionTimeoutMs,
            NullStatsLogger.INSTANCE);
    return new ZKDistributedLock(
            this.lockStateExecutor,
            lockFactory,
            this.lockPath,
            Long.MAX_VALUE,
            NullStatsLogger.INSTANCE);
}
 
Example #17
Source File: TestEntry.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20000)
public void testEmptyRecordSet() throws Exception {
    Writer writer = Entry.newEntry(
            "test-empty-record-set",
            1024,
            true,
            CompressionCodec.Type.NONE,
            NullStatsLogger.INSTANCE);
    assertEquals("zero bytes", 0, writer.getNumBytes());
    assertEquals("zero records", 0, writer.getNumRecords());

    Buffer buffer = writer.getBuffer();
    Entry recordSet = Entry.newBuilder()
            .setData(buffer.getData(), 0, buffer.size())
            .setLogSegmentInfo(1L, 0L)
            .setEntryId(0L)
            .build();
    Reader reader = recordSet.reader();
    Assert.assertNull("Empty record set should return null",
            reader.nextRecord());
}
 
Example #18
Source File: SameThreadOrderedSafeExecutor.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public SameThreadOrderedSafeExecutor() {
    super(
        "same-thread-executor",
        1,
        new DefaultThreadFactory("test"),
        NullStatsLogger.INSTANCE,
        false,
        false,
        100000,
        -1,
        false);
}
 
Example #19
Source File: TestReadAheadEntryReader.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private ReadAheadEntryReader createEntryReader(String streamName,
                                               DLSN fromDLSN,
                                               BKDistributedLogManager dlm,
                                               DistributedLogConfiguration conf)
        throws Exception {
    BKLogReadHandler readHandler = dlm.createReadHandler(
            Optional.<String>absent(),
            true);
    LogSegmentEntryStore entryStore = new BKLogSegmentEntryStore(
            conf,
            ConfUtils.getConstDynConf(conf),
            zkc,
            bkc,
            scheduler,
            null,
            NullStatsLogger.INSTANCE,
            AsyncFailureInjector.NULL);
    return new ReadAheadEntryReader(
            streamName,
            fromDLSN,
            conf,
            readHandler,
            entryStore,
            scheduler,
            Ticker.systemTicker(),
            new AlertStatsLogger(NullStatsLogger.INSTANCE, "test-alert"));
}
 
Example #20
Source File: TestBKLogSegmentWriter.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private ZKDistributedLock createLock(String path,
                                     ZooKeeperClient zkClient,
                                     boolean acquireLock)
        throws Exception {
    try {
        Await.result(Utils.zkAsyncCreateFullPathOptimistic(zkClient, path, new byte[0],
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
    } catch (KeeperException.NodeExistsException nee) {
        // node already exists
    }
    SessionLockFactory lockFactory = new ZKSessionLockFactory(
            zkClient,
            "test-lock",
            lockStateExecutor,
            0,
            Long.MAX_VALUE,
            conf.getZKSessionTimeoutMilliseconds(),
            NullStatsLogger.INSTANCE
    );
    ZKDistributedLock lock = new ZKDistributedLock(
            lockStateExecutor,
            lockFactory,
            path,
            Long.MAX_VALUE,
            NullStatsLogger.INSTANCE);
    if (acquireLock) {
        return FutureUtils.result(lock.asyncAcquire());
    } else {
        return lock;
    }
}
 
Example #21
Source File: TestZKSessionLock.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
/**
 * Test unlock timeout.
 *
 * @throws Exception
 */
@Test(timeout = 60000)
public void testUnlockTimeout() throws Exception {
    String name = testNames.getMethodName();
    String lockPath = "/" + name;
    String clientId = name;

    createLockPath(zkc.get(), lockPath);

    ZKSessionLock lock = new ZKSessionLock(
            zkc, lockPath, clientId, lockStateExecutor,
            1 * 1000 /* op timeout */, NullStatsLogger.INSTANCE,
            new DistributedLockContext());

    lock.tryLock(0, TimeUnit.MILLISECONDS);
    assertEquals(State.CLAIMED, lock.getLockState());

    try {
        FailpointUtils.setFailpoint(FailpointUtils.FailPointName.FP_LockUnlockCleanup,
                                    new DelayFailpointAction(60 * 60 * 1000));

        lock.unlock();
        assertEquals(State.CLOSING, lock.getLockState());
    } finally {
        FailpointUtils.removeFailpoint(FailpointUtils.FailPointName.FP_LockUnlockCleanup);
    }
}
 
Example #22
Source File: TestDistributedLogService.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private WriteOp getWriteOp(String name, SettableFeature disabledFeature, Long checksum) {
    return new WriteOp(name,
        ByteBuffer.wrap("test".getBytes()),
        new NullStatsLogger(),
        new NullStatsLogger(),
        new ServerConfiguration(),
        (byte)0,
        checksum,
        false,
        disabledFeature,
        DefaultAccessControlManager.INSTANCE);
}
 
Example #23
Source File: ZKSessionLock.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
ZKSessionLock(ZooKeeperClient zkClient,
              String lockPath,
              String clientId,
              OrderedScheduler lockStateExecutor)
        throws IOException {
    this(zkClient,
            lockPath,
            clientId,
            lockStateExecutor,
            DistributedLogConstants.LOCK_OP_TIMEOUT_DEFAULT * 1000, NullStatsLogger.INSTANCE,
            new DistributedLockContext());
}
 
Example #24
Source File: TestDynamicConfigurationFeatureProvider.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 60000)
public void testLoadFeaturesFromBase() throws Exception {
    PropertiesWriter writer = new PropertiesWriter();
    writer.setProperty("feature_1", "10000");
    writer.setProperty("feature_2", "5000");
    writer.save();

    DistributedLogConfiguration conf = new DistributedLogConfiguration()
            .setDynamicConfigReloadIntervalSec(Integer.MAX_VALUE)
            .setFileFeatureProviderBaseConfigPath(writer.getFile().toURI().toURL().getPath());
    DynamicConfigurationFeatureProvider provider =
            new DynamicConfigurationFeatureProvider("", conf, NullStatsLogger.INSTANCE);
    provider.start();
    ensureConfigReloaded();

    Feature feature1 = provider.getFeature("feature_1");
    assertTrue(feature1.isAvailable());
    assertEquals(10000, feature1.availability());
    Feature feature2 = provider.getFeature("feature_2");
    assertTrue(feature2.isAvailable());
    assertEquals(5000, feature2.availability());
    Feature feature3 = provider.getFeature("feature_3");
    assertFalse(feature3.isAvailable());
    assertEquals(0, feature3.availability());
    Feature feature4 = provider.getFeature("unknown_feature");
    assertFalse(feature4.isAvailable());
    assertEquals(0, feature4.availability());

    provider.stop();
}
 
Example #25
Source File: TestZKSessionLock.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
/**
 * Test try-create after close race condition.
 *
 * @throws Exception
 */
@Test(timeout = 60000)
public void testTryCloseRaceCondition() throws Exception {
    String name = testNames.getMethodName();
    String lockPath = "/" + name;
    String clientId = name;

    createLockPath(zkc.get(), lockPath);

    ZKSessionLock lock = new ZKSessionLock(
            zkc, lockPath, clientId, lockStateExecutor,
            1 * 1000 /* op timeout */, NullStatsLogger.INSTANCE,
            new DistributedLockContext());

    try {
        FailpointUtils.setFailpoint(FailpointUtils.FailPointName.FP_LockTryCloseRaceCondition,
                                    FailpointUtils.DEFAULT_ACTION);

        lock.tryLock(0, TimeUnit.MILLISECONDS);
    } catch (LockClosedException ex) {
    } finally {
        FailpointUtils.removeFailpoint(FailpointUtils.FailPointName.FP_LockTryCloseRaceCondition);
    }

    assertEquals(State.CLOSED, lock.getLockState());
    List<String> children = getLockWaiters(zkc, lockPath);
    assertEquals(0, children.size());
}
 
Example #26
Source File: ZKSessionLock.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
ZKSessionLock(ZooKeeperClient zkClient,
              String lockPath,
              String clientId,
              OrderedScheduler lockStateExecutor)
        throws IOException {
    this(zkClient,
            lockPath,
            clientId,
            lockStateExecutor,
            DistributedLogConstants.LOCK_OP_TIMEOUT_DEFAULT * 1000, NullStatsLogger.INSTANCE,
            new DistributedLockContext());
}
 
Example #27
Source File: ZkIsolatedBookieEnsemblePlacementPolicyTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoBookieInfo() throws Exception {
    ZkIsolatedBookieEnsemblePlacementPolicy isolationPolicy = new ZkIsolatedBookieEnsemblePlacementPolicy();
    ClientConfiguration bkClientConf = new ClientConfiguration();
    bkClientConf.setProperty(ZooKeeperCache.ZK_CACHE_INSTANCE, new ZooKeeperCache("test", localZkc, 30) {
    });
    bkClientConf.setProperty(ZkIsolatedBookieEnsemblePlacementPolicy.ISOLATION_BOOKIE_GROUPS, isolationGroups);
    isolationPolicy.initialize(bkClientConf, Optional.empty(), timer, SettableFeatureProvider.DISABLE_ALL, NullStatsLogger.INSTANCE);
    isolationPolicy.onClusterChanged(writableBookies, readOnlyBookies);

    isolationPolicy.newEnsemble(4, 4, 4, Collections.emptyMap(), new HashSet<>());

    String data = "{\"group1\": {\"" + BOOKIE1
            + "\": {\"rack\": \"rack0\", \"hostname\": \"bookie1.example.com\"}, \"" + BOOKIE2
            + "\": {\"rack\": \"rack1\", \"hostname\": \"bookie2.example.com\"}}, \"group2\": {\"" + BOOKIE3
            + "\": {\"rack\": \"rack0\", \"hostname\": \"bookie3.example.com\"}, \"" + BOOKIE4
            + "\": {\"rack\": \"rack2\", \"hostname\": \"bookie4.example.com\"}}}";

    ZkUtils.createFullPathOptimistic(localZkc, ZkBookieRackAffinityMapping.BOOKIE_INFO_ROOT_PATH, data.getBytes(),
            ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    Thread.sleep(100);

    List<BookieSocketAddress> ensemble = isolationPolicy.newEnsemble(2, 2, 2, Collections.emptyMap(), new HashSet<>()).getResult();
    assertTrue(ensemble.contains(new BookieSocketAddress(BOOKIE1)));
    assertTrue(ensemble.contains(new BookieSocketAddress(BOOKIE2)));

    try {
        isolationPolicy.newEnsemble(3, 3, 3, Collections.emptyMap(), new HashSet<>());
        fail("should not pass");
    } catch (BKNotEnoughBookiesException e) {
        // ok
    }

    localZkc.delete(ZkBookieRackAffinityMapping.BOOKIE_INFO_ROOT_PATH, -1);
}
 
Example #28
Source File: Entry.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
public Entry.Reader buildReader() throws IOException {
    checkNotNull(buffer,
            "Serialized data or input stream isn't provided");
    return new EnvelopedEntryReader(
            logSegmentSequenceNumber,
            entryId,
            startSequenceId,
            buffer,
            envelopeEntry,
            deserializeRecordSet,
            NullStatsLogger.INSTANCE);
}
 
Example #29
Source File: TestZKSessionLock.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
/**
 * Test try acquire timeout.
 *
 * @throws Exception
 */
@Test(timeout = 60000)
public void testTryAcquireTimeout() throws Exception {
    String name = testNames.getMethodName();
    String lockPath = "/" + name;
    String clientId = name;

    createLockPath(zkc.get(), lockPath);

    ZKSessionLock lock = new ZKSessionLock(
            zkc, lockPath, clientId, lockStateExecutor,
            1 /* op timeout */, NullStatsLogger.INSTANCE,
            new DistributedLockContext());

    try {
        FailpointUtils.setFailpoint(FailpointUtils.FailPointName.FP_LockTryAcquire,
                                    new DelayFailpointAction(60 * 60 * 1000));

        lock.tryLock(0, TimeUnit.MILLISECONDS);
        assertEquals(State.CLOSED, lock.getLockState());
    } catch (LockingException le) {
    } catch (Exception e) {
        fail("expected locking exception");
    } finally {
        FailpointUtils.removeFailpoint(FailpointUtils.FailPointName.FP_LockTryAcquire);
    }
}
 
Example #30
Source File: TestDistributedLock.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private SessionLockFactory createLockFactory(String clientId,
                                             ZooKeeperClient zkc,
                                             long lockTimeoutMs,
                                             int recreationTimes) {
    return new ZKSessionLockFactory(
            zkc,
            clientId,
            lockStateExecutor,
            recreationTimes,
            lockTimeoutMs,
            sessionTimeoutMs,
            NullStatsLogger.INSTANCE);
}