Search in sources :

Example 1 with Assert

use of org.junit.Assert in project elasticsearch by elastic.

the class InternalTestCluster method fullRestart.

/**
     * Restarts all nodes in the cluster. It first stops all nodes and then restarts all the nodes again.
     */
public synchronized void fullRestart(RestartCallback callback) throws Exception {
    int numNodesRestarted = 0;
    Map<Set<Role>, List<NodeAndClient>> nodesByRoles = new HashMap<>();
    Set[] rolesOrderedByOriginalStartupOrder = new Set[nextNodeId.get()];
    for (NodeAndClient nodeAndClient : nodes.values()) {
        callback.doAfterNodes(numNodesRestarted++, nodeAndClient.nodeClient());
        logger.info("Stopping node [{}] ", nodeAndClient.name);
        if (activeDisruptionScheme != null) {
            activeDisruptionScheme.removeFromNode(nodeAndClient.name, this);
        }
        nodeAndClient.closeNode();
        // delete data folders now, before we start other nodes that may claim it
        nodeAndClient.clearDataIfNeeded(callback);
        DiscoveryNode discoveryNode = getInstanceFromNode(ClusterService.class, nodeAndClient.node()).localNode();
        rolesOrderedByOriginalStartupOrder[nodeAndClient.nodeAndClientId] = discoveryNode.getRoles();
        nodesByRoles.computeIfAbsent(discoveryNode.getRoles(), k -> new ArrayList<>()).add(nodeAndClient);
    }
    assert nodesByRoles.values().stream().collect(Collectors.summingInt(List::size)) == nodes.size();
    //    will still belong to data nodes
    for (List<NodeAndClient> sameRoleNodes : nodesByRoles.values()) {
        Collections.shuffle(sameRoleNodes, random);
    }
    List<NodeAndClient> startUpOrder = new ArrayList<>();
    for (Set roles : rolesOrderedByOriginalStartupOrder) {
        if (roles == null) {
            // if some nodes were stopped, we want have a role for that ordinal
            continue;
        }
        final List<NodeAndClient> nodesByRole = nodesByRoles.get(roles);
        startUpOrder.add(nodesByRole.remove(0));
    }
    assert nodesByRoles.values().stream().collect(Collectors.summingInt(List::size)) == 0;
    // do two rounds to minimize pinging (mock zen pings pings with no delay and can create a lot of logs)
    for (NodeAndClient nodeAndClient : startUpOrder) {
        logger.info("resetting node [{}] ", nodeAndClient.name);
        // we already cleared data folders, before starting nodes up
        nodeAndClient.recreateNodeOnRestart(callback, false, autoManageMinMasterNodes ? getMinMasterNodes(getMasterNodesCount()) : -1);
    }
    startAndPublishNodesAndClients(startUpOrder);
    if (callback.validateClusterForming()) {
        validateClusterFormed();
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) ByteSizeUnit(org.elasticsearch.common.unit.ByteSizeUnit) Arrays(java.util.Arrays) Nullable(org.elasticsearch.common.Nullable) Releasables(org.elasticsearch.common.lease.Releasables) NetworkModule(org.elasticsearch.common.network.NetworkModule) ZenDiscovery(org.elasticsearch.discovery.zen.ZenDiscovery) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) NodeValidationException(org.elasticsearch.node.NodeValidationException) SearchService(org.elasticsearch.search.SearchService) RecoverySettings(org.elasticsearch.indices.recovery.RecoverySettings) ClusterState(org.elasticsearch.cluster.ClusterState) Future(java.util.concurrent.Future) RandomNumbers(com.carrotsearch.randomizedtesting.generators.RandomNumbers) Map(java.util.Map) Role(org.elasticsearch.cluster.node.DiscoveryNode.Role) Path(java.nio.file.Path) RandomStrings(com.carrotsearch.randomizedtesting.generators.RandomStrings) ServiceDisruptionScheme(org.elasticsearch.test.disruption.ServiceDisruptionScheme) Transport(org.elasticsearch.transport.Transport) MappingUpdatedAction(org.elasticsearch.cluster.action.index.MappingUpdatedAction) Set(java.util.Set) PageCacheRecycler(org.elasticsearch.common.util.PageCacheRecycler) ESTestCase.assertBusy(org.elasticsearch.test.ESTestCase.assertBusy) RandomizedTest(com.carrotsearch.randomizedtesting.RandomizedTest) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) TransportSettings(org.elasticsearch.transport.TransportSettings) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) XContentFactory(org.elasticsearch.common.xcontent.XContentFactory) ThrottlingAllocationDecider(org.elasticsearch.cluster.routing.allocation.decider.ThrottlingAllocationDecider) RandomPicks(com.carrotsearch.randomizedtesting.generators.RandomPicks) DiskThresholdSettings(org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings) TransportClient(org.elasticsearch.client.transport.TransportClient) ClusterService(org.elasticsearch.cluster.service.ClusterService) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) ArrayList(java.util.ArrayList) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) TcpTransport(org.elasticsearch.transport.TcpTransport) CircuitBreaker(org.elasticsearch.common.breaker.CircuitBreaker) IndicesService(org.elasticsearch.indices.IndicesService) TransportService(org.elasticsearch.transport.TransportService) Loggers(org.elasticsearch.common.logging.Loggers) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) FileSystemUtils(org.elasticsearch.common.io.FileSystemUtils) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) OperationRouting(org.elasticsearch.cluster.routing.OperationRouting) Client(org.elasticsearch.client.Client) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) NodeService(org.elasticsearch.node.NodeService) SeedUtils(com.carrotsearch.randomizedtesting.SeedUtils) ExecutionException(java.util.concurrent.ExecutionException) LuceneTestCase.rarely(org.apache.lucene.util.LuceneTestCase.rarely) HierarchyCircuitBreakerService(org.elasticsearch.indices.breaker.HierarchyCircuitBreakerService) IndicesFieldDataCache(org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache) TreeMap(java.util.TreeMap) CommonStatsFlags(org.elasticsearch.action.admin.indices.stats.CommonStatsFlags) Assert(org.junit.Assert) ScriptService(org.elasticsearch.script.ScriptService) Builder(org.elasticsearch.common.settings.Settings.Builder) ElasticsearchAssertions.assertAcked(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked) ElasticsearchException(org.elasticsearch.ElasticsearchException) Environment(org.elasticsearch.env.Environment) Random(java.util.Random) TEST_NIGHTLY(org.apache.lucene.util.LuceneTestCase.TEST_NIGHTLY) Assert.assertThat(org.junit.Assert.assertThat) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SysGlobals(com.carrotsearch.randomizedtesting.SysGlobals) Assert.fail(org.junit.Assert.fail) ClusterName(org.elasticsearch.cluster.ClusterName) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) Flag(org.elasticsearch.action.admin.indices.stats.CommonStatsFlags.Flag) NavigableMap(java.util.NavigableMap) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) Engine(org.elasticsearch.index.engine.Engine) ESTestCase.randomFrom(org.elasticsearch.test.ESTestCase.randomFrom) MockTransportClient(org.elasticsearch.transport.MockTransportClient) List(java.util.List) TransportAddress(org.elasticsearch.common.transport.TransportAddress) Matchers.equalTo(org.hamcrest.Matchers.equalTo) DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING(org.elasticsearch.discovery.zen.ElectMasterService.DISCOVERY_ZEN_MINIMUM_MASTER_NODES_SETTING) ElectMasterService(org.elasticsearch.discovery.zen.ElectMasterService) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) CommitStats(org.elasticsearch.index.engine.CommitStats) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) Function(java.util.function.Function) Strings(org.elasticsearch.common.Strings) ListTasksResponse(org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse) HashSet(java.util.HashSet) TimeValue(org.elasticsearch.common.unit.TimeValue) Node(org.elasticsearch.node.Node) MockTransportService(org.elasticsearch.test.transport.MockTransportService) ExecutorService(java.util.concurrent.ExecutorService) NodeStats(org.elasticsearch.action.admin.cluster.node.stats.NodeStats) TaskInfo(org.elasticsearch.tasks.TaskInfo) MockNode(org.elasticsearch.node.MockNode) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) Iterator(java.util.Iterator) Plugin(org.elasticsearch.plugins.Plugin) ESTestCase.awaitBusy(org.elasticsearch.test.ESTestCase.awaitBusy) TimeUnit(java.util.concurrent.TimeUnit) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) Closeable(java.io.Closeable) TaskManager(org.elasticsearch.tasks.TaskManager) Collections(java.util.Collections) ReplicationTask(org.elasticsearch.action.support.replication.ReplicationTask) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Set(java.util.Set) HashSet(java.util.HashSet) ClusterService(org.elasticsearch.cluster.service.ClusterService) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with Assert

use of org.junit.Assert in project java-design-patterns by iluwatar.

the class SimpleFileWriterTest method testWriterNotNull.

/**
   * Verify if the given writer is not 'null'
   */
@Test
public void testWriterNotNull() throws Exception {
    final File temporaryFile = this.testFolder.newFile();
    new SimpleFileWriter(temporaryFile.getPath(), Assert::assertNotNull);
}
Also used : Assert(org.junit.Assert) File(java.io.File) Test(org.junit.Test)

Example 3 with Assert

use of org.junit.Assert in project neo4j by neo4j.

the class NeoStoreFileListingTest method shouldListNeostoreDbLast.

@Test
public void shouldListNeostoreDbLast() throws Exception {
    Boolean[] foundStoreType = new Boolean[StoreType.values().length];
    boolean foundTxLogs = false;
    final ResourceIterator<StoreFileMetadata> storeFiles = neoStoreDataSource.listStoreFiles(true);
    while (storeFiles.hasNext()) {
        final StoreFileMetadata storeFile = storeFiles.next();
        if (storeFile.storeType().isPresent()) {
            StoreType storeType = storeFile.storeType().get();
            foundStoreType[storeType.ordinal()] = true;
            if (storeType == StoreType.META_DATA) {
                Arrays.stream(foundStoreType).forEach(Assert::assertTrue);
                assertTrue("Transaction logs was not listed before neostore.db", foundTxLogs);
            }
        } else if (transactionLogFile(storeFile.file().getName())) {
            foundTxLogs = true;
        }
    }
}
Also used : StoreType(org.neo4j.kernel.impl.store.StoreType) Assert(org.junit.Assert) StoreFileMetadata(org.neo4j.storageengine.api.StoreFileMetadata) Test(org.junit.Test)

Example 4 with Assert

use of org.junit.Assert in project spring-framework by spring-projects.

the class AsyncRestTemplateIntegrationTests method deleteCallbackWithLambdas.

@Test
public void deleteCallbackWithLambdas() throws Exception {
    ListenableFuture<?> deletedFuture = template.delete(new URI(baseUrl + "/delete"));
    deletedFuture.addCallback(Assert::assertNull, ex -> fail(ex.getMessage()));
    waitTillDone(deletedFuture);
}
Also used : Assert(org.junit.Assert) URI(java.net.URI) Test(org.junit.Test)

Example 5 with Assert

use of org.junit.Assert in project cassandra by apache.

the class LongBTreeTest method randomKeys.

// select a random subset of the keys, with an optional random population of keys inbetween those that are present
// return a value with the search position
private static List<Integer> randomKeys(Iterable<Integer> canonical, boolean mixInNotPresentItems) {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    boolean useFake = mixInNotPresentItems && rnd.nextBoolean();
    final float fakeRatio = rnd.nextFloat();
    List<Integer> results = new ArrayList<>();
    Long fakeLb = (long) Integer.MIN_VALUE, fakeUb = null;
    Integer max = null;
    for (Integer v : canonical) {
        if (!useFake || (fakeUb == null ? v - 1 : fakeUb) <= fakeLb + 1 || rnd.nextFloat() < fakeRatio) {
            // if we cannot safely construct a fake value, or our randomizer says not to, we emit the next real value
            results.add(v);
            fakeLb = v.longValue();
            fakeUb = null;
        } else {
            // exceeding the real value that would have proceeded (ignoring any other suppressed real values since)
            if (fakeUb == null)
                fakeUb = v.longValue() - 1;
            long mid = (fakeLb + fakeUb) / 2;
            assert mid < fakeUb;
            results.add((int) mid);
            fakeLb = mid;
        }
        max = v;
    }
    if (useFake && max != null && max < Integer.MAX_VALUE)
        results.add(max + 1);
    final float useChance = rnd.nextFloat();
    return Lists.newArrayList(filter(results, (x) -> rnd.nextFloat() < useChance));
}
Also used : java.util(java.util) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Iterables.transform(com.google.common.collect.Iterables.transform) Comparator.naturalOrder(java.util.Comparator.naturalOrder) Callable(java.util.concurrent.Callable) Predicates.notNull(com.google.common.base.Predicates.notNull) BTree.iterable(org.apache.cassandra.utils.btree.BTree.iterable) Lists(com.google.common.collect.Lists) ListenableFutureTask(com.google.common.util.concurrent.ListenableFutureTask) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Method(java.lang.reflect.Method) org.apache.cassandra.utils.btree(org.apache.cassandra.utils.btree) ExecutorService(java.util.concurrent.ExecutorService) Function(com.google.common.base.Function) MetricRegistry(com.codahale.metrics.MetricRegistry) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Executors(java.util.concurrent.Executors) Snapshot(com.codahale.metrics.Snapshot) InvocationTargetException(java.lang.reflect.InvocationTargetException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) Futures(com.google.common.util.concurrent.Futures) NamedThreadFactory(org.apache.cassandra.concurrent.NamedThreadFactory) Annotation(java.lang.annotation.Annotation) Timer(com.codahale.metrics.Timer) Comparator.reverseOrder(java.util.Comparator.reverseOrder) Iterables.filter(com.google.common.collect.Iterables.filter) Assert(org.junit.Assert) AtomicLong(java.util.concurrent.atomic.AtomicLong) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom)

Aggregations

Assert (org.junit.Assert)18 Test (org.junit.Test)14 List (java.util.List)7 ArrayList (java.util.ArrayList)5 UUID (java.util.UUID)5 SSTableReader (org.apache.cassandra.io.sstable.format.SSTableReader)5 HashSet (java.util.HashSet)3 Collectors (java.util.stream.Collectors)3 SSTableAddedNotification (org.apache.cassandra.notifications.SSTableAddedNotification)3 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)2 Project (com.intellij.openapi.project.Project)2 Ref (com.intellij.openapi.util.Ref)2 InetAddress (java.net.InetAddress)2 Arrays (java.util.Arrays)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 HashMap (java.util.HashMap)2 Iterator (java.util.Iterator)2 Map (java.util.Map)2 Set (java.util.Set)2