Search in sources :

Example 21 with MockLogAppender

use of org.opensearch.test.MockLogAppender in project OpenSearch by opensearch-project.

the class CoordinatorTests method testLogsWarningPeriodicallyIfClusterNotFormed.

public void testLogsWarningPeriodicallyIfClusterNotFormed() throws IllegalAccessException {
    final long warningDelayMillis;
    final Settings settings;
    if (randomBoolean()) {
        settings = Settings.EMPTY;
        warningDelayMillis = ClusterFormationFailureHelper.DISCOVERY_CLUSTER_FORMATION_WARNING_TIMEOUT_SETTING.get(settings).millis();
    } else {
        warningDelayMillis = randomLongBetween(1, 100000);
        settings = Settings.builder().put(ClusterFormationFailureHelper.DISCOVERY_CLUSTER_FORMATION_WARNING_TIMEOUT_SETTING.getKey(), warningDelayMillis + "ms").build();
    }
    logger.info("--> emitting warnings every [{}ms]", warningDelayMillis);
    try (Cluster cluster = new Cluster(3, true, settings)) {
        cluster.runRandomly();
        cluster.stabilise();
        logger.info("--> disconnecting all nodes");
        for (final ClusterNode clusterNode : cluster.clusterNodes) {
            clusterNode.disconnect();
        }
        cluster.runFor(// to wait for any in-flight check to time out
        defaultMillis(LEADER_CHECK_TIMEOUT_SETTING) + // to wait for the next check to be sent
        defaultMillis(LEADER_CHECK_INTERVAL_SETTING) + // to send the failing check and receive the disconnection response
        2 * DEFAULT_DELAY_VARIABILITY, "waiting for leader failure");
        for (final ClusterNode clusterNode : cluster.clusterNodes) {
            assertThat(clusterNode.getId() + " is CANDIDATE", clusterNode.coordinator.getMode(), is(CANDIDATE));
        }
        for (int i = scaledRandomIntBetween(1, 10); i >= 0; i--) {
            try (MockLogAppender mockLogAppender = MockLogAppender.createForLoggers(LogManager.getLogger(ClusterFormationFailureHelper.class))) {
                mockLogAppender.addExpectation(new MockLogAppender.LoggingExpectation() {

                    final Set<DiscoveryNode> nodesLogged = new HashSet<>();

                    @Override
                    public void match(LogEvent event) {
                        final String message = event.getMessage().getFormattedMessage();
                        assertThat(message, startsWith("master not discovered or elected yet, an election requires at least 2 nodes with ids from ["));
                        final List<ClusterNode> matchingNodes = cluster.clusterNodes.stream().filter(n -> event.getContextData().<String>getValue(NODE_ID_LOG_CONTEXT_KEY).equals(getNodeIdForLogContext(n.getLocalNode()))).collect(Collectors.toList());
                        assertThat(matchingNodes, hasSize(1));
                        assertTrue(Regex.simpleMatch("*have discovered *" + matchingNodes.get(0).toString() + "*discovery will continue*", message));
                        nodesLogged.add(matchingNodes.get(0).getLocalNode());
                    }

                    @Override
                    public void assertMatched() {
                        assertThat(nodesLogged + " vs " + cluster.clusterNodes, nodesLogged, equalTo(cluster.clusterNodes.stream().map(ClusterNode::getLocalNode).collect(Collectors.toSet())));
                    }
                });
                cluster.runFor(warningDelayMillis + DEFAULT_DELAY_VARIABILITY, "waiting for warning to be emitted");
                mockLogAppender.assertAllExpectationsMatched();
            }
        }
    }
}
Also used : ClusterNode(org.opensearch.cluster.coordination.AbstractCoordinatorTestCase.Cluster.ClusterNode) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) MockLogAppender(org.opensearch.test.MockLogAppender) LogEvent(org.apache.logging.log4j.core.LogEvent) Matchers.containsString(org.hamcrest.Matchers.containsString) List(java.util.List) Settings(org.opensearch.common.settings.Settings) HashSet(java.util.HashSet)

Example 22 with MockLogAppender

use of org.opensearch.test.MockLogAppender in project OpenSearch by opensearch-project.

the class DiskThresholdMonitorTests method assertLogging.

private void assertLogging(DiskThresholdMonitor monitor, ImmutableOpenMap<String, DiskUsage> diskUsages, Level level, String message) throws IllegalAccessException {
    try (MockLogAppender mockAppender = MockLogAppender.createForLoggers(LogManager.getLogger(DiskThresholdMonitor.class))) {
        mockAppender.start();
        mockAppender.addExpectation(new MockLogAppender.SeenEventExpectation("expected message", DiskThresholdMonitor.class.getCanonicalName(), level, message));
        mockAppender.addExpectation(new MockLogAppender.UnseenEventExpectation("any message of another level", DiskThresholdMonitor.class.getCanonicalName(), level == Level.INFO ? Level.WARN : Level.INFO, "*"));
        monitor.onNewInfo(clusterInfo(diskUsages));
        mockAppender.assertAllExpectationsMatched();
    }
}
Also used : MockLogAppender(org.opensearch.test.MockLogAppender)

Example 23 with MockLogAppender

use of org.opensearch.test.MockLogAppender in project OpenSearch by opensearch-project.

the class DiskThresholdMonitorTests method assertNoLogging.

private void assertNoLogging(DiskThresholdMonitor monitor, ImmutableOpenMap<String, DiskUsage> diskUsages) throws IllegalAccessException {
    try (MockLogAppender mockAppender = MockLogAppender.createForLoggers(LogManager.getLogger(DiskThresholdMonitor.class))) {
        mockAppender.addExpectation(new MockLogAppender.UnseenEventExpectation("any INFO message", DiskThresholdMonitor.class.getCanonicalName(), Level.INFO, "*"));
        mockAppender.addExpectation(new MockLogAppender.UnseenEventExpectation("any WARN message", DiskThresholdMonitor.class.getCanonicalName(), Level.WARN, "*"));
        for (int i = between(1, 3); i >= 0; i--) {
            monitor.onNewInfo(clusterInfo(diskUsages));
        }
        mockAppender.assertAllExpectationsMatched();
    }
}
Also used : MockLogAppender(org.opensearch.test.MockLogAppender)

Example 24 with MockLogAppender

use of org.opensearch.test.MockLogAppender in project OpenSearch by opensearch-project.

the class InboundHandlerTests method testClosesChannelOnErrorInHandshakeWithIncompatibleVersion.

public void testClosesChannelOnErrorInHandshakeWithIncompatibleVersion() throws Exception {
    try (MockLogAppender mockAppender = MockLogAppender.createForLoggers(LogManager.getLogger(InboundHandler.class))) {
        mockAppender.addExpectation(new MockLogAppender.SeenEventExpectation("expected message", InboundHandler.class.getCanonicalName(), Level.WARN, "could not send error response to handshake"));
        final AtomicBoolean isClosed = new AtomicBoolean();
        channel.addCloseListener(ActionListener.wrap(() -> assertTrue(isClosed.compareAndSet(false, true))));
        final Version remoteVersion = Version.fromId(randomIntBetween(0, version.minimumCompatibilityVersion().id - 1));
        final long requestId = randomNonNegativeLong();
        final Header requestHeader = new Header(between(0, 100), requestId, TransportStatus.setRequest(TransportStatus.setHandshake((byte) 0)), remoteVersion);
        final InboundMessage requestMessage = unreadableInboundHandshake(remoteVersion, requestHeader);
        requestHeader.actionName = TransportHandshaker.HANDSHAKE_ACTION_NAME;
        requestHeader.headers = Tuple.tuple(org.opensearch.common.collect.Map.of(), org.opensearch.common.collect.Map.of());
        requestHeader.features = org.opensearch.common.collect.Set.of();
        handler.inboundMessage(channel, requestMessage);
        assertTrue(isClosed.get());
        assertNull(channel.getMessageCaptor().get());
        mockAppender.assertAllExpectationsMatched();
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MockLogAppender(org.opensearch.test.MockLogAppender) Version(org.opensearch.Version)

Example 25 with MockLogAppender

use of org.opensearch.test.MockLogAppender in project OpenSearch by opensearch-project.

the class TcpTransportTests method testExceptionHandling.

private void testExceptionHandling(boolean startTransport, Exception exception, boolean expectClosed, MockLogAppender.LoggingExpectation... expectations) throws IllegalAccessException {
    final TestThreadPool testThreadPool = new TestThreadPool("test");
    try (MockLogAppender appender = MockLogAppender.createForLoggers(LogManager.getLogger(TcpTransport.class))) {
        for (MockLogAppender.LoggingExpectation expectation : expectations) {
            appender.addExpectation(expectation);
        }
        final Lifecycle lifecycle = new Lifecycle();
        if (startTransport) {
            lifecycle.moveToStarted();
        }
        final FakeTcpChannel channel = new FakeTcpChannel();
        final PlainActionFuture<Void> listener = new PlainActionFuture<>();
        channel.addCloseListener(listener);
        TcpTransport.handleException(channel, exception, lifecycle, new OutboundHandler(randomAlphaOfLength(10), Version.CURRENT, new String[0], new StatsTracker(), testThreadPool, BigArrays.NON_RECYCLING_INSTANCE));
        if (expectClosed) {
            assertTrue(listener.isDone());
            assertThat(listener.actionGet(), nullValue());
        } else {
            assertFalse(listener.isDone());
        }
        appender.assertAllExpectationsMatched();
    } finally {
        ThreadPool.terminate(testThreadPool, 30, TimeUnit.SECONDS);
    }
}
Also used : MockLogAppender(org.opensearch.test.MockLogAppender) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) Lifecycle(org.opensearch.common.component.Lifecycle) TestThreadPool(org.opensearch.threadpool.TestThreadPool)

Aggregations

MockLogAppender (org.opensearch.test.MockLogAppender)29 Logger (org.apache.logging.log4j.Logger)11 TestLogging (org.opensearch.test.junit.annotations.TestLogging)10 Matchers.containsString (org.hamcrest.Matchers.containsString)8 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)5 OpenSearchException (org.opensearch.OpenSearchException)4 ClusterState (org.opensearch.cluster.ClusterState)4 ClusterSettings (org.opensearch.common.settings.ClusterSettings)4 Settings (org.opensearch.common.settings.Settings)4 Path (java.nio.file.Path)3 HashSet (java.util.HashSet)3 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 LogEvent (org.apache.logging.log4j.core.LogEvent)3 Version (org.opensearch.Version)3 ClusterNode (org.opensearch.cluster.coordination.AbstractCoordinatorTestCase.Cluster.ClusterNode)3 IOException (java.io.IOException)2 InetSocketAddress (java.net.InetSocketAddress)2 UnknownHostException (java.net.UnknownHostException)2