Search in sources :

Example 6 with Node

use of org.opensearch.node.Node in project OpenSearch by opensearch-project.

the class InternalTestCluster method reset.

private synchronized void reset(boolean wipeData) throws IOException {
    // clear all rules for mock transport services
    for (NodeAndClient nodeAndClient : nodes.values()) {
        TransportService transportService = nodeAndClient.node.injector().getInstance(TransportService.class);
        if (transportService instanceof MockTransportService) {
            final MockTransportService mockTransportService = (MockTransportService) transportService;
            mockTransportService.clearAllRules();
        }
    }
    randomlyResetClients();
    final int newSize = sharedNodesSeeds.length;
    if (nextNodeId.get() == newSize && nodes.size() == newSize) {
        if (wipeData) {
            wipePendingDataDirectories();
        }
        logger.debug("Cluster hasn't changed - moving out - nodes: [{}] nextNodeId: [{}] numSharedNodes: [{}]", nodes.keySet(), nextNodeId.get(), newSize);
        return;
    }
    logger.debug("Cluster is NOT consistent - restarting shared nodes - nodes: [{}] nextNodeId: [{}] numSharedNodes: [{}]", nodes.keySet(), nextNodeId.get(), newSize);
    // trash all nodes with id >= sharedNodesSeeds.length - they are non shared
    final List<NodeAndClient> toClose = new ArrayList<>();
    for (NodeAndClient nodeAndClient : nodes.values()) {
        if (nodeAndClient.nodeAndClientId() >= sharedNodesSeeds.length) {
            logger.debug("Close Node [{}] not shared", nodeAndClient.name);
            toClose.add(nodeAndClient);
        }
    }
    stopNodesAndClients(toClose);
    // clean up what the nodes left that is unused
    if (wipeData) {
        wipePendingDataDirectories();
    }
    assertTrue("expected at least one master-eligible node left in " + nodes, nodes.isEmpty() || nodes.values().stream().anyMatch(NodeAndClient::isMasterEligible));
    final int prevNodeCount = nodes.size();
    // start any missing node
    assert newSize == numSharedDedicatedMasterNodes + numSharedDataNodes + numSharedCoordOnlyNodes;
    final int numberOfMasterNodes = numSharedDedicatedMasterNodes > 0 ? numSharedDedicatedMasterNodes : numSharedDataNodes;
    final int defaultMinMasterNodes = (numberOfMasterNodes / 2) + 1;
    // we want to start nodes in one go
    final List<NodeAndClient> toStartAndPublish = new ArrayList<>();
    final Runnable onTransportServiceStarted = () -> rebuildUnicastHostFiles(toStartAndPublish);
    final List<Settings> settings = new ArrayList<>();
    for (int i = 0; i < numSharedDedicatedMasterNodes; i++) {
        final Settings nodeSettings = getNodeSettings(i, sharedNodesSeeds[i], Settings.EMPTY, defaultMinMasterNodes);
        settings.add(removeRoles(nodeSettings, Collections.singleton(DiscoveryNodeRole.DATA_ROLE)));
    }
    for (int i = numSharedDedicatedMasterNodes; i < numSharedDedicatedMasterNodes + numSharedDataNodes; i++) {
        final Settings nodeSettings = getNodeSettings(i, sharedNodesSeeds[i], Settings.EMPTY, defaultMinMasterNodes);
        if (numSharedDedicatedMasterNodes > 0) {
            settings.add(removeRoles(nodeSettings, Collections.singleton(DiscoveryNodeRole.MASTER_ROLE)));
        } else {
            // if we don't have dedicated master nodes, keep things default
            settings.add(nodeSettings);
        }
    }
    for (int i = numSharedDedicatedMasterNodes + numSharedDataNodes; i < numSharedDedicatedMasterNodes + numSharedDataNodes + numSharedCoordOnlyNodes; i++) {
        final Builder extraSettings = Settings.builder().put(noRoles());
        settings.add(getNodeSettings(i, sharedNodesSeeds[i], extraSettings.build(), defaultMinMasterNodes));
    }
    int autoBootstrapMasterNodeIndex = -1;
    final List<String> masterNodeNames = settings.stream().filter(DiscoveryNode::isMasterNode).map(Node.NODE_NAME_SETTING::get).collect(Collectors.toList());
    if (prevNodeCount == 0 && autoManageMasterNodes) {
        if (numSharedDedicatedMasterNodes > 0) {
            autoBootstrapMasterNodeIndex = RandomNumbers.randomIntBetween(random, 0, numSharedDedicatedMasterNodes - 1);
        } else if (numSharedDataNodes > 0) {
            autoBootstrapMasterNodeIndex = RandomNumbers.randomIntBetween(random, 0, numSharedDataNodes - 1);
        }
    }
    final List<Settings> updatedSettings = bootstrapMasterNodeWithSpecifiedIndex(settings);
    for (int i = 0; i < numSharedDedicatedMasterNodes + numSharedDataNodes + numSharedCoordOnlyNodes; i++) {
        Settings nodeSettings = updatedSettings.get(i);
        if (i == autoBootstrapMasterNodeIndex) {
            nodeSettings = Settings.builder().putList(INITIAL_MASTER_NODES_SETTING.getKey(), masterNodeNames).put(nodeSettings).build();
        }
        final NodeAndClient nodeAndClient = buildNode(i, nodeSettings, true, onTransportServiceStarted);
        toStartAndPublish.add(nodeAndClient);
    }
    startAndPublishNodesAndClients(toStartAndPublish);
    nextNodeId.set(newSize);
    assert size() == newSize;
    if (autoManageMasterNodes && newSize > 0) {
        validateClusterFormed();
    }
    logger.debug("Cluster is consistent again - nodes: [{}] nextNodeId: [{}] numSharedNodes: [{}]", nodes.keySet(), nextNodeId.get(), newSize);
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) MockTransportService(org.opensearch.test.transport.MockTransportService) Builder(org.opensearch.common.settings.Settings.Builder) NodeRoles.masterOnlyNode(org.opensearch.test.NodeRoles.masterOnlyNode) NodeRoles.dataOnlyNode(org.opensearch.test.NodeRoles.dataOnlyNode) Node(org.opensearch.node.Node) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) MockNode(org.opensearch.node.MockNode) ArrayList(java.util.ArrayList) TransportService(org.opensearch.transport.TransportService) MockTransportService(org.opensearch.test.transport.MockTransportService) MockSecureSettings(org.opensearch.common.settings.MockSecureSettings) Settings(org.opensearch.common.settings.Settings) SecureSettings(org.opensearch.common.settings.SecureSettings) TransportSettings(org.opensearch.transport.TransportSettings) RecoverySettings(org.opensearch.indices.recovery.RecoverySettings) DiskThresholdSettings(org.opensearch.cluster.routing.allocation.DiskThresholdSettings) DiscoverySettings(org.opensearch.node.Node.DiscoverySettings)

Example 7 with Node

use of org.opensearch.node.Node in project OpenSearch by opensearch-project.

the class InternalTestCluster method assertRequestsFinished.

public void assertRequestsFinished() {
    assert Thread.holdsLock(this);
    if (size() > 0) {
        for (NodeAndClient nodeAndClient : nodes.values()) {
            CircuitBreaker inFlightRequestsBreaker = getInstance(CircuitBreakerService.class, nodeAndClient.name).getBreaker(CircuitBreaker.IN_FLIGHT_REQUESTS);
            TaskManager taskManager = getInstance(TransportService.class, nodeAndClient.name).getTaskManager();
            try {
                // see #ensureEstimatedStats()
                assertBusy(() -> {
                    // ensure that our size accounting on transport level is reset properly
                    long bytesUsed = inFlightRequestsBreaker.getUsed();
                    if (bytesUsed != 0) {
                        String pendingTasks = taskManager.getTasks().values().stream().map(t -> t.taskInfo(nodeAndClient.name, true).toString()).collect(Collectors.joining(",", "[", "]"));
                        throw new AssertionError("All incoming requests on node [" + nodeAndClient.name + "] should have finished. " + "Expected 0 but got " + bytesUsed + "; pending tasks [" + pendingTasks + "]");
                    }
                }, 1, TimeUnit.MINUTES);
            } catch (Exception e) {
                logger.error("Could not assert finished requests within timeout", e);
                fail("Could not assert finished requests within timeout on node [" + nodeAndClient.name + "]");
            }
        }
    }
}
Also used : SeqNoStats(org.opensearch.index.seqno.SeqNoStats) SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) Arrays(java.util.Arrays) ClusterBootstrapService(org.opensearch.cluster.coordination.ClusterBootstrapService) NodeRoles.masterOnlyNode(org.opensearch.test.NodeRoles.masterOnlyNode) MockSecureSettings(org.opensearch.common.settings.MockSecureSettings) ScriptModule(org.opensearch.script.ScriptModule) Matchers.not(org.hamcrest.Matchers.not) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ThrottlingAllocationDecider(org.opensearch.cluster.routing.allocation.decider.ThrottlingAllocationDecider) FileSystemUtils(org.opensearch.common.io.FileSystemUtils) FutureUtils(org.opensearch.common.util.concurrent.FutureUtils) NodeRoles.dataOnlyNode(org.opensearch.test.NodeRoles.dataOnlyNode) Strings(org.opensearch.common.Strings) ClearVotingConfigExclusionsRequest(org.opensearch.action.admin.cluster.configuration.ClearVotingConfigExclusionsRequest) InternalEngine(org.opensearch.index.engine.InternalEngine) IndexShardTestCase(org.opensearch.index.shard.IndexShardTestCase) Future(java.util.concurrent.Future) RandomNumbers(com.carrotsearch.randomizedtesting.generators.RandomNumbers) NodeRoles.removeRoles(org.opensearch.test.NodeRoles.removeRoles) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) ObjectLongMap(com.carrotsearch.hppc.ObjectLongMap) Path(java.nio.file.Path) RandomStrings(com.carrotsearch.randomizedtesting.generators.RandomStrings) NodeEnvironment(org.opensearch.env.NodeEnvironment) ScriptService(org.opensearch.script.ScriptService) Client(org.opensearch.client.Client) ClearVotingConfigExclusionsAction(org.opensearch.action.admin.cluster.configuration.ClearVotingConfigExclusionsAction) TimeValue(org.opensearch.common.unit.TimeValue) Index(org.opensearch.index.Index) INITIAL_MASTER_NODES_SETTING(org.opensearch.cluster.coordination.ClusterBootstrapService.INITIAL_MASTER_NODES_SETTING) AddVotingConfigExclusionsRequest(org.opensearch.action.admin.cluster.configuration.AddVotingConfigExclusionsRequest) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) DiscoveryNodeRole(org.opensearch.cluster.node.DiscoveryNodeRole) TransportService(org.opensearch.transport.TransportService) TaskManager(org.opensearch.tasks.TaskManager) RandomizedTest(com.carrotsearch.randomizedtesting.RandomizedTest) TimeValue.timeValueSeconds(org.opensearch.common.unit.TimeValue.timeValueSeconds) Engine(org.opensearch.index.engine.Engine) UncheckedIOException(java.io.UncheckedIOException) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) Randomness(org.opensearch.common.Randomness) Assert.assertFalse(org.junit.Assert.assertFalse) NodeStats(org.opensearch.action.admin.cluster.node.stats.NodeStats) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Builder(org.opensearch.common.settings.Settings.Builder) IntObjectCursor(com.carrotsearch.hppc.cursors.IntObjectCursor) RandomPicks(com.carrotsearch.randomizedtesting.generators.RandomPicks) LifecycleListener(org.opensearch.common.component.LifecycleListener) HierarchyCircuitBreakerService(org.opensearch.indices.breaker.HierarchyCircuitBreakerService) Node(org.opensearch.node.Node) MockTransportService(org.opensearch.test.transport.MockTransportService) ZEN2_DISCOVERY_TYPE(org.opensearch.discovery.DiscoveryModule.ZEN2_DISCOVERY_TYPE) UNICAST_HOSTS_FILE(org.opensearch.discovery.FileBasedSeedHostsProvider.UNICAST_HOSTS_FILE) OpenSearchExecutors(org.opensearch.common.util.concurrent.OpenSearchExecutors) ArrayList(java.util.ArrayList) DISCOVERY_TYPE_SETTING(org.opensearch.discovery.DiscoveryModule.DISCOVERY_TYPE_SETTING) DocIdSeqNoAndSource(org.opensearch.index.engine.DocIdSeqNoAndSource) ClusterState(org.opensearch.cluster.ClusterState) NoMasterBlockService(org.opensearch.cluster.coordination.NoMasterBlockService) HttpServerTransport(org.opensearch.http.HttpServerTransport) Environment(org.opensearch.env.Environment) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Files(java.nio.file.Files) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) IndexService(org.opensearch.index.IndexService) Plugin(org.opensearch.plugins.Plugin) SeedUtils(com.carrotsearch.randomizedtesting.SeedUtils) NodeValidationException(org.opensearch.node.NodeValidationException) SecureSettings(org.opensearch.common.settings.SecureSettings) ExecutionException(java.util.concurrent.ExecutionException) TransportSettings(org.opensearch.transport.TransportSettings) LuceneTestCase.rarely(org.apache.lucene.util.LuceneTestCase.rarely) TreeMap(java.util.TreeMap) Flag(org.opensearch.action.admin.indices.stats.CommonStatsFlags.Flag) ClusterService(org.opensearch.cluster.service.ClusterService) PageCacheRecycler(org.opensearch.common.util.PageCacheRecycler) Assert.assertEquals(org.junit.Assert.assertEquals) ByteSizeUnit(org.opensearch.common.unit.ByteSizeUnit) Random(java.util.Random) CircuitBreaker(org.opensearch.common.breaker.CircuitBreaker) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) Releasables(org.opensearch.common.lease.Releasables) CommonStatsFlags(org.opensearch.action.admin.indices.stats.CommonStatsFlags) TEST_NIGHTLY(org.apache.lucene.util.LuceneTestCase.TEST_NIGHTLY) Assert.assertThat(org.junit.Assert.assertThat) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Assert.fail(org.junit.Assert.fail) RecoverySettings(org.opensearch.indices.recovery.RecoverySettings) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) EngineTestCase(org.opensearch.index.engine.EngineTestCase) Predicate(java.util.function.Predicate) Collection(java.util.Collection) IndicesService(org.opensearch.indices.IndicesService) ServiceDisruptionScheme(org.opensearch.test.disruption.ServiceDisruptionScheme) NavigableMap(java.util.NavigableMap) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) Nullable(org.opensearch.common.Nullable) Objects(java.util.Objects) OperationRouting(org.opensearch.cluster.routing.OperationRouting) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) NodeRoles.onlyRole(org.opensearch.test.NodeRoles.onlyRole) IntStream(java.util.stream.IntStream) TimeValue.timeValueMillis(org.opensearch.common.unit.TimeValue.timeValueMillis) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) IndexingPressure(org.opensearch.index.IndexingPressure) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) NodeRoles.noRoles(org.opensearch.test.NodeRoles.noRoles) IndicesFieldDataCache(org.opensearch.indices.fielddata.cache.IndicesFieldDataCache) DiskThresholdSettings(org.opensearch.cluster.routing.allocation.DiskThresholdSettings) Function(java.util.function.Function) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) OpenSearchTestCase.randomFrom(org.opensearch.test.OpenSearchTestCase.randomFrom) MappingUpdatedAction(org.opensearch.cluster.action.index.MappingUpdatedAction) HashSet(java.util.HashSet) IndexRoutingTable(org.opensearch.cluster.routing.IndexRoutingTable) IndexShard(org.opensearch.index.shard.IndexShard) AddVotingConfigExclusionsAction(org.opensearch.action.admin.cluster.configuration.AddVotingConfigExclusionsAction) ExecutorService(java.util.concurrent.ExecutorService) SearchService(org.opensearch.search.SearchService) OpenSearchTestCase.assertBusy(org.opensearch.test.OpenSearchTestCase.assertBusy) Iterator(java.util.Iterator) NodeService(org.opensearch.node.NodeService) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException) DiscoverySettings(org.opensearch.node.Node.DiscoverySettings) TransportReplicationAction(org.opensearch.action.support.replication.TransportReplicationAction) MockNode(org.opensearch.node.MockNode) ShardRouting(org.opensearch.cluster.routing.ShardRouting) IOUtils(org.opensearch.core.internal.io.IOUtils) ShardId(org.opensearch.index.shard.ShardId) TimeUnit(java.util.concurrent.TimeUnit) Sets(org.opensearch.common.util.set.Sets) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) Closeable(java.io.Closeable) ClusterName(org.opensearch.cluster.ClusterName) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) CircuitBreaker(org.opensearch.common.breaker.CircuitBreaker) TaskManager(org.opensearch.tasks.TaskManager) TransportService(org.opensearch.transport.TransportService) MockTransportService(org.opensearch.test.transport.MockTransportService) HierarchyCircuitBreakerService(org.opensearch.indices.breaker.HierarchyCircuitBreakerService) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) NodeValidationException(org.opensearch.node.NodeValidationException) ExecutionException(java.util.concurrent.ExecutionException) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException)

Example 8 with Node

use of org.opensearch.node.Node in project OpenSearch by opensearch-project.

the class OpenSearchSingleNodeTestCase method stopNode.

private static void stopNode() throws IOException, InterruptedException {
    Node node = NODE;
    NODE = null;
    IOUtils.close(node);
    if (node != null && node.awaitClose(10, TimeUnit.SECONDS) == false) {
        throw new AssertionError("Node couldn't close within 10 seconds.");
    }
}
Also used : NodeRoles.dataNode(org.opensearch.test.NodeRoles.dataNode) Node(org.opensearch.node.Node) MockNode(org.opensearch.node.MockNode)

Example 9 with Node

use of org.opensearch.node.Node in project security by opensearch-project.

the class SSLTest method testNodeClientSSLwithJavaTLSv13.

@Test
public void testNodeClientSSLwithJavaTLSv13() throws Exception {
    // Java TLS 1.3 is available since Java 11
    Assume.assumeTrue(!allowOpenSSL && PlatformDependent.javaVersion() >= 11);
    final Settings settings = Settings.builder().put("plugins.security.ssl.transport.enabled", true).put(ConfigConstants.SECURITY_SSL_ONLY, true).put(SSLConfigConstants.SECURITY_SSL_HTTP_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL).put(SSLConfigConstants.SECURITY_SSL_TRANSPORT_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL).put(SSLConfigConstants.SECURITY_SSL_TRANSPORT_KEYSTORE_ALIAS, "node-0").put("plugins.security.ssl.transport.keystore_filepath", FileHelper.getAbsoluteFilePathFromClassPath("ssl/node-0-keystore.jks")).put(SSLConfigConstants.SECURITY_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, FileHelper.getAbsoluteFilePathFromClassPath("ssl/truststore.jks")).put("plugins.security.ssl.transport.enforce_hostname_verification", false).put("plugins.security.ssl.transport.resolve_hostname", false).putList(SSLConfigConstants.SECURITY_SSL_TRANSPORT_ENABLED_PROTOCOLS, "TLSv1.3").putList(SSLConfigConstants.SECURITY_SSL_TRANSPORT_ENABLED_CIPHERS, "TLS_AES_128_GCM_SHA256").build();
    setupSslOnlyMode(settings);
    RestHelper rh = nonSslRestHelper();
    final Settings tcSettings = Settings.builder().put("cluster.name", clusterInfo.clustername).put("path.data", "./target/data/" + clusterInfo.clustername + "/ssl/data").put("path.logs", "./target/data/" + clusterInfo.clustername + "/ssl/logs").put("path.home", "./target").put("node.name", "client_node_" + new Random().nextInt()).put("discovery.initial_state_timeout", "8s").putList("discovery.zen.ping.unicast.hosts", clusterInfo.nodeHost + ":" + clusterInfo.nodePort).put(// -----
    settings).build();
    try (Node node = new PluginAwareNode(false, tcSettings, Netty4Plugin.class, OpenSearchSecurityPlugin.class).start()) {
        ClusterHealthResponse res = node.client().admin().cluster().health(new ClusterHealthRequest().waitForNodes("4").timeout(TimeValue.timeValueSeconds(5))).actionGet();
        Assert.assertFalse(res.isTimedOut());
        Assert.assertEquals(4, res.getNumberOfNodes());
        Assert.assertEquals(4, node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size());
    }
    Assert.assertFalse(rh.executeSimpleRequest("_nodes/stats?pretty").contains("\"tx_size_in_bytes\" : 0"));
    Assert.assertFalse(rh.executeSimpleRequest("_nodes/stats?pretty").contains("\"rx_count\" : 0"));
    Assert.assertFalse(rh.executeSimpleRequest("_nodes/stats?pretty").contains("\"rx_size_in_bytes\" : 0"));
    Assert.assertFalse(rh.executeSimpleRequest("_nodes/stats?pretty").contains("\"tx_count\" : 0"));
}
Also used : PluginAwareNode(org.opensearch.node.PluginAwareNode) Random(java.util.Random) ClusterHealthResponse(org.opensearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequest(org.opensearch.action.admin.cluster.health.ClusterHealthRequest) Netty4Plugin(org.opensearch.transport.Netty4Plugin) Node(org.opensearch.node.Node) PluginAwareNode(org.opensearch.node.PluginAwareNode) OpenSearchSecurityPlugin(org.opensearch.security.OpenSearchSecurityPlugin) NodesInfoRequest(org.opensearch.action.admin.cluster.node.info.NodesInfoRequest) RestHelper(org.opensearch.security.test.helper.rest.RestHelper) Settings(org.opensearch.common.settings.Settings) Test(org.junit.Test) SingleClusterTest(org.opensearch.security.test.SingleClusterTest)

Example 10 with Node

use of org.opensearch.node.Node in project security by opensearch-project.

the class RolesInjectorIntegTest method testRolesInject.

@Test
public void testRolesInject() throws Exception {
    setup(Settings.EMPTY, new DynamicSecurityConfig().setSecurityRoles("roles.yml"), Settings.EMPTY);
    Assert.assertEquals(clusterInfo.numNodes, clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getNumberOfNodes());
    Assert.assertEquals(ClusterHealthStatus.GREEN, clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus());
    final Settings tcSettings = Settings.builder().put(minimumSecuritySettings(Settings.EMPTY).get(0)).put("cluster.name", clusterInfo.clustername).put("node.data", false).put("node.master", false).put("node.ingest", false).put("path.data", "./target/data/" + clusterInfo.clustername + "/cert/data").put("path.logs", "./target/data/" + clusterInfo.clustername + "/cert/logs").put("path.home", "./target").put("node.name", "testclient").put("discovery.initial_state_timeout", "8s").put("plugins.security.allow_default_init_securityindex", "true").putList("discovery.zen.ping.unicast.hosts", clusterInfo.nodeHost + ":" + clusterInfo.nodePort).build();
    // 1. Without roles injection.
    try (Node node = new PluginAwareNode(false, tcSettings, Netty4Plugin.class, OpenSearchSecurityPlugin.class, RolesInjectorPlugin.class).start()) {
        waitForInit(node.client());
        CreateIndexResponse cir = node.client().admin().indices().create(new CreateIndexRequest("captain-logs-1")).actionGet();
        Assert.assertTrue(cir.isAcknowledged());
        IndicesExistsResponse ier = node.client().admin().indices().exists(new IndicesExistsRequest("captain-logs-1")).actionGet();
        Assert.assertTrue(ier.isExists());
    }
    // 2. With invalid roles, must throw security exception.
    RolesInjectorPlugin.injectedRoles = "invalid_user|invalid_role";
    Exception exception = null;
    try (Node node = new PluginAwareNode(false, tcSettings, Netty4Plugin.class, OpenSearchSecurityPlugin.class, RolesInjectorPlugin.class).start()) {
        waitForInit(node.client());
        CreateIndexResponse cir = node.client().admin().indices().create(new CreateIndexRequest("captain-logs-2")).actionGet();
        Assert.assertTrue(cir.isAcknowledged());
    } catch (OpenSearchSecurityException ex) {
        exception = ex;
        log.warn(ex.toString());
    }
    Assert.assertNotNull(exception);
    Assert.assertTrue(exception.getMessage().contains("indices:admin/create"));
    // 3. With valid roles - which has permission to create index.
    RolesInjectorPlugin.injectedRoles = "valid_user|opendistro_security_all_access";
    try (Node node = new PluginAwareNode(false, tcSettings, Netty4Plugin.class, OpenSearchSecurityPlugin.class, RolesInjectorPlugin.class).start()) {
        waitForInit(node.client());
        CreateIndexResponse cir = node.client().admin().indices().create(new CreateIndexRequest("captain-logs-3")).actionGet();
        Assert.assertTrue(cir.isAcknowledged());
        IndicesExistsResponse ier = node.client().admin().indices().exists(new IndicesExistsRequest("captain-logs-3")).actionGet();
        Assert.assertTrue(ier.isExists());
    }
}
Also used : OpenSearchSecurityException(org.opensearch.OpenSearchSecurityException) ClusterHealthRequest(org.opensearch.action.admin.cluster.health.ClusterHealthRequest) Netty4Plugin(org.opensearch.transport.Netty4Plugin) Node(org.opensearch.node.Node) PluginAwareNode(org.opensearch.node.PluginAwareNode) OpenSearchSecurityException(org.opensearch.OpenSearchSecurityException) PluginAwareNode(org.opensearch.node.PluginAwareNode) DynamicSecurityConfig(org.opensearch.security.test.DynamicSecurityConfig) IndicesExistsResponse(org.opensearch.action.admin.indices.exists.indices.IndicesExistsResponse) CreateIndexResponse(org.opensearch.action.admin.indices.create.CreateIndexResponse) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) Settings(org.opensearch.common.settings.Settings) IndicesExistsRequest(org.opensearch.action.admin.indices.exists.indices.IndicesExistsRequest) Test(org.junit.Test) SingleClusterTest(org.opensearch.security.test.SingleClusterTest)

Aggregations

Node (org.opensearch.node.Node)34 Settings (org.opensearch.common.settings.Settings)25 MockNode (org.opensearch.node.MockNode)15 PluginAwareNode (org.opensearch.node.PluginAwareNode)13 Test (org.junit.Test)12 Netty4Plugin (org.opensearch.transport.Netty4Plugin)12 IOException (java.io.IOException)10 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)10 NodeRoles.dataNode (org.opensearch.test.NodeRoles.dataNode)10 ArrayList (java.util.ArrayList)9 List (java.util.List)9 IndexService (org.opensearch.index.IndexService)9 SingleClusterTest (org.opensearch.security.test.SingleClusterTest)9 Collections (java.util.Collections)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)8 Collectors (java.util.stream.Collectors)8 TimeValue (org.opensearch.common.unit.TimeValue)8 IndexShard (org.opensearch.index.shard.IndexShard)8 Random (java.util.Random)7 Set (java.util.Set)7