Search in sources :

Example 21 with TransportAddress

use of org.opensearch.common.transport.TransportAddress in project OpenSearch by opensearch-project.

the class Ec2DiscoveryTests method testReadHostFromTag.

public void testReadHostFromTag() throws UnknownHostException {
    int nodes = randomIntBetween(5, 10);
    String[] addresses = new String[nodes];
    for (int node = 0; node < nodes; node++) {
        addresses[node] = "192.168.0." + (node + 1);
        poorMansDNS.put("node" + (node + 1), new TransportAddress(InetAddress.getByName(addresses[node]), 9300));
    }
    Settings nodeSettings = Settings.builder().put(AwsEc2Service.HOST_TYPE_SETTING.getKey(), "tag:foo").build();
    List<List<Tag>> tagsList = new ArrayList<>();
    for (int node = 0; node < nodes; node++) {
        List<Tag> tags = new ArrayList<>();
        tags.add(new Tag("foo", "node" + (node + 1)));
        tagsList.add(tags);
    }
    logger.info("started [{}] instances", nodes);
    List<TransportAddress> dynamicHosts = buildDynamicHosts(nodeSettings, nodes, tagsList);
    assertThat(dynamicHosts, hasSize(nodes));
    int node = 1;
    for (TransportAddress address : dynamicHosts) {
        TransportAddress expected = poorMansDNS.get("node" + node++);
        assertEquals(address, expected);
    }
}
Also used : TransportAddress(org.opensearch.common.transport.TransportAddress) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) Matchers.containsString(org.hamcrest.Matchers.containsString) Tag(com.amazonaws.services.ec2.model.Tag) Settings(org.opensearch.common.settings.Settings)

Example 22 with TransportAddress

use of org.opensearch.common.transport.TransportAddress in project OpenSearch by opensearch-project.

the class Ec2DiscoveryTests method buildDynamicHosts.

protected List<TransportAddress> buildDynamicHosts(Settings nodeSettings, int nodes, List<List<Tag>> tagsList) {
    final String accessKey = "ec2_key";
    try (Ec2DiscoveryPlugin plugin = new Ec2DiscoveryPlugin(buildSettings(accessKey))) {
        AwsEc2SeedHostsProvider provider = new AwsEc2SeedHostsProvider(nodeSettings, transportService, plugin.ec2Service);
        httpServer.createContext("/", exchange -> {
            if (exchange.getRequestMethod().equals(HttpMethodName.POST.name())) {
                final String request = Streams.readFully(exchange.getRequestBody()).toBytesRef().utf8ToString();
                final String userAgent = exchange.getRequestHeaders().getFirst("User-Agent");
                if (userAgent != null && userAgent.startsWith("aws-sdk-java")) {
                    final String auth = exchange.getRequestHeaders().getFirst("Authorization");
                    if (auth == null || auth.contains(accessKey) == false) {
                        throw new IllegalArgumentException("wrong access key: " + auth);
                    }
                    // Simulate an EC2 DescribeInstancesResponse
                    final Map<String, List<String>> tagsIncluded = new HashMap<>();
                    final String[] params = request.split("&");
                    Arrays.stream(params).filter(entry -> entry.startsWith("Filter.") && entry.contains("=tag%3A")).forEach(entry -> {
                        final int startIndex = "Filter.".length();
                        final int filterId = Integer.parseInt(entry.substring(startIndex, entry.indexOf(".", startIndex)));
                        tagsIncluded.put(entry.substring(entry.indexOf("=tag%3A") + "=tag%3A".length()), Arrays.stream(params).filter(param -> param.startsWith("Filter." + filterId + ".Value.")).map(param -> param.substring(param.indexOf("=") + 1)).collect(Collectors.toList()));
                    });
                    final List<Instance> instances = IntStream.range(1, nodes + 1).mapToObj(node -> {
                        final String instanceId = "node" + node;
                        final Instance instance = new Instance().withInstanceId(instanceId).withState(new InstanceState().withName(InstanceStateName.Running)).withPrivateDnsName(PREFIX_PRIVATE_DNS + instanceId + SUFFIX_PRIVATE_DNS).withPublicDnsName(PREFIX_PUBLIC_DNS + instanceId + SUFFIX_PUBLIC_DNS).withPrivateIpAddress(PREFIX_PRIVATE_IP + node).withPublicIpAddress(PREFIX_PUBLIC_IP + node);
                        if (tagsList != null) {
                            instance.setTags(tagsList.get(node - 1));
                        }
                        return instance;
                    }).filter(instance -> tagsIncluded.entrySet().stream().allMatch(entry -> instance.getTags().stream().filter(t -> t.getKey().equals(entry.getKey())).map(Tag::getValue).collect(Collectors.toList()).containsAll(entry.getValue()))).collect(Collectors.toList());
                    for (NameValuePair parse : URLEncodedUtils.parse(request, UTF_8)) {
                        if ("Action".equals(parse.getName())) {
                            final byte[] responseBody = generateDescribeInstancesResponse(instances);
                            exchange.getResponseHeaders().set("Content-Type", "text/xml; charset=UTF-8");
                            exchange.sendResponseHeaders(HttpStatus.SC_OK, responseBody.length);
                            exchange.getResponseBody().write(responseBody);
                            return;
                        }
                    }
                }
            }
            fail("did not send response");
        });
        List<TransportAddress> dynamicHosts = provider.getSeedAddresses(null);
        logger.debug("--> addresses found: {}", dynamicHosts);
        return dynamicHosts;
    } catch (IOException e) {
        fail("Unexpected IOException");
        return null;
    }
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) HttpStatus(org.apache.http.HttpStatus) Version(org.opensearch.Version) HashMap(java.util.HashMap) MockTransportService(org.opensearch.test.transport.MockTransportService) ArrayList(java.util.ArrayList) Transport(org.opensearch.transport.Transport) InetAddress(java.net.InetAddress) Streams(org.opensearch.common.io.Streams) Map(java.util.Map) Matchers.hasSize(org.hamcrest.Matchers.hasSize) InstanceState(com.amazonaws.services.ec2.model.InstanceState) Instance(com.amazonaws.services.ec2.model.Instance) MockNioTransport(org.opensearch.transport.nio.MockNioTransport) SuppressForbidden(org.opensearch.common.SuppressForbidden) InstanceStateName(com.amazonaws.services.ec2.model.InstanceStateName) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Settings(org.opensearch.common.settings.Settings) IOException(java.io.IOException) HttpMethodName(com.amazonaws.http.HttpMethodName) TransportService(org.opensearch.transport.TransportService) UnknownHostException(java.net.UnknownHostException) Collectors(java.util.stream.Collectors) TransportAddress(org.opensearch.common.transport.TransportAddress) List(java.util.List) Tag(com.amazonaws.services.ec2.model.Tag) URLEncodedUtils(org.apache.http.client.utils.URLEncodedUtils) NetworkService(org.opensearch.common.network.NetworkService) Matchers.is(org.hamcrest.Matchers.is) NameValuePair(org.apache.http.NameValuePair) Collections(java.util.Collections) Matchers.containsString(org.hamcrest.Matchers.containsString) PageCacheRecycler(org.opensearch.common.util.PageCacheRecycler) NameValuePair(org.apache.http.NameValuePair) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Instance(com.amazonaws.services.ec2.model.Instance) TransportAddress(org.opensearch.common.transport.TransportAddress) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) InstanceState(com.amazonaws.services.ec2.model.InstanceState) ArrayList(java.util.ArrayList) List(java.util.List)

Example 23 with TransportAddress

use of org.opensearch.common.transport.TransportAddress in project OpenSearch by opensearch-project.

the class Ec2DiscoveryTests method testPrivateDns.

public void testPrivateDns() throws InterruptedException {
    int nodes = randomInt(10);
    for (int i = 0; i < nodes; i++) {
        String instanceId = "node" + (i + 1);
        poorMansDNS.put(PREFIX_PRIVATE_DNS + instanceId + SUFFIX_PRIVATE_DNS, buildNewFakeTransportAddress());
    }
    Settings nodeSettings = Settings.builder().put(AwsEc2Service.HOST_TYPE_SETTING.getKey(), "private_dns").build();
    List<TransportAddress> dynamicHosts = buildDynamicHosts(nodeSettings, nodes);
    assertThat(dynamicHosts, hasSize(nodes));
    // We check that we are using here expected address
    int node = 1;
    for (TransportAddress address : dynamicHosts) {
        String instanceId = "node" + node++;
        TransportAddress expected = poorMansDNS.get(PREFIX_PRIVATE_DNS + instanceId + SUFFIX_PRIVATE_DNS);
        assertEquals(address, expected);
    }
}
Also used : TransportAddress(org.opensearch.common.transport.TransportAddress) Matchers.containsString(org.hamcrest.Matchers.containsString) Settings(org.opensearch.common.settings.Settings)

Example 24 with TransportAddress

use of org.opensearch.common.transport.TransportAddress in project OpenSearch by opensearch-project.

the class Ec2DiscoveryTests method testPublicDns.

public void testPublicDns() throws InterruptedException {
    int nodes = randomInt(10);
    for (int i = 0; i < nodes; i++) {
        String instanceId = "node" + (i + 1);
        poorMansDNS.put(PREFIX_PUBLIC_DNS + instanceId + SUFFIX_PUBLIC_DNS, buildNewFakeTransportAddress());
    }
    Settings nodeSettings = Settings.builder().put(AwsEc2Service.HOST_TYPE_SETTING.getKey(), "public_dns").build();
    List<TransportAddress> dynamicHosts = buildDynamicHosts(nodeSettings, nodes);
    assertThat(dynamicHosts, hasSize(nodes));
    // We check that we are using here expected address
    int node = 1;
    for (TransportAddress address : dynamicHosts) {
        String instanceId = "node" + node++;
        TransportAddress expected = poorMansDNS.get(PREFIX_PUBLIC_DNS + instanceId + SUFFIX_PUBLIC_DNS);
        assertEquals(address, expected);
    }
}
Also used : TransportAddress(org.opensearch.common.transport.TransportAddress) Matchers.containsString(org.hamcrest.Matchers.containsString) Settings(org.opensearch.common.settings.Settings)

Example 25 with TransportAddress

use of org.opensearch.common.transport.TransportAddress in project OpenSearch by opensearch-project.

the class AwsEc2SeedHostsProvider method fetchDynamicNodes.

protected List<TransportAddress> fetchDynamicNodes() {
    final List<TransportAddress> dynamicHosts = new ArrayList<>();
    final DescribeInstancesResult descInstances;
    try (AmazonEc2Reference clientReference = awsEc2Service.client()) {
        // Query EC2 API based on AZ, instance state, and tag.
        // NOTE: we don't filter by security group during the describe instances request for two reasons:
        // 1. differences in VPCs require different parameters during query (ID vs Name)
        // 2. We want to use two different strategies: (all security groups vs. any security groups)
        descInstances = SocketAccess.doPrivileged(() -> clientReference.client().describeInstances(buildDescribeInstancesRequest()));
    } catch (final AmazonClientException e) {
        logger.info("Exception while retrieving instance list from AWS API: {}", e.getMessage());
        logger.debug("Full exception:", e);
        return dynamicHosts;
    }
    logger.trace("finding seed nodes...");
    for (final Reservation reservation : descInstances.getReservations()) {
        for (final Instance instance : reservation.getInstances()) {
            // lets see if we can filter based on groups
            if (!groups.isEmpty()) {
                final List<GroupIdentifier> instanceSecurityGroups = instance.getSecurityGroups();
                final List<String> securityGroupNames = new ArrayList<>(instanceSecurityGroups.size());
                final List<String> securityGroupIds = new ArrayList<>(instanceSecurityGroups.size());
                for (final GroupIdentifier sg : instanceSecurityGroups) {
                    securityGroupNames.add(sg.getGroupName());
                    securityGroupIds.add(sg.getGroupId());
                }
                if (bindAnyGroup) {
                    // We check if we can find at least one group name or one group id in groups.
                    if (disjoint(securityGroupNames, groups) && disjoint(securityGroupIds, groups)) {
                        logger.trace("filtering out instance {} based on groups {}, not part of {}", instance.getInstanceId(), instanceSecurityGroups, groups);
                        // continue to the next instance
                        continue;
                    }
                } else {
                    // We need tp match all group names or group ids, otherwise we ignore this instance
                    if (!(securityGroupNames.containsAll(groups) || securityGroupIds.containsAll(groups))) {
                        logger.trace("filtering out instance {} based on groups {}, does not include all of {}", instance.getInstanceId(), instanceSecurityGroups, groups);
                        // continue to the next instance
                        continue;
                    }
                }
            }
            String address = null;
            if (hostType.equals(PRIVATE_DNS)) {
                address = instance.getPrivateDnsName();
            } else if (hostType.equals(PRIVATE_IP)) {
                address = instance.getPrivateIpAddress();
            } else if (hostType.equals(PUBLIC_DNS)) {
                address = instance.getPublicDnsName();
            } else if (hostType.equals(PUBLIC_IP)) {
                address = instance.getPublicIpAddress();
            } else if (hostType.startsWith(TAG_PREFIX)) {
                // Reading the node host from its metadata
                final String tagName = hostType.substring(TAG_PREFIX.length());
                logger.debug("reading hostname from [{}] instance tag", tagName);
                final List<Tag> tags = instance.getTags();
                for (final Tag tag : tags) {
                    if (tag.getKey().equals(tagName)) {
                        address = tag.getValue();
                        logger.debug("using [{}] as the instance address", address);
                    }
                }
            } else {
                throw new IllegalArgumentException(hostType + " is unknown for discovery.ec2.host_type");
            }
            if (address != null) {
                try {
                    final TransportAddress[] addresses = transportService.addressesFromString(address);
                    for (int i = 0; i < addresses.length; i++) {
                        logger.trace("adding {}, address {}, transport_address {}", instance.getInstanceId(), address, addresses[i]);
                        dynamicHosts.add(addresses[i]);
                    }
                } catch (final Exception e) {
                    final String finalAddress = address;
                    logger.warn((Supplier<?>) () -> new ParameterizedMessage("failed to add {}, address {}", instance.getInstanceId(), finalAddress), e);
                }
            } else {
                logger.trace("not adding {}, address is null, host_type {}", instance.getInstanceId(), hostType);
            }
        }
    }
    logger.debug("using dynamic transport addresses {}", dynamicHosts);
    return dynamicHosts;
}
Also used : Instance(com.amazonaws.services.ec2.model.Instance) TransportAddress(org.opensearch.common.transport.TransportAddress) AmazonClientException(com.amazonaws.AmazonClientException) ArrayList(java.util.ArrayList) Collections.disjoint(java.util.Collections.disjoint) AmazonClientException(com.amazonaws.AmazonClientException) GroupIdentifier(com.amazonaws.services.ec2.model.GroupIdentifier) DescribeInstancesResult(com.amazonaws.services.ec2.model.DescribeInstancesResult) Reservation(com.amazonaws.services.ec2.model.Reservation) Supplier(org.apache.logging.log4j.util.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Tag(com.amazonaws.services.ec2.model.Tag)

Aggregations

TransportAddress (org.opensearch.common.transport.TransportAddress)170 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)57 Settings (org.opensearch.common.settings.Settings)57 IOException (java.io.IOException)31 BoundTransportAddress (org.opensearch.common.transport.BoundTransportAddress)31 Version (org.opensearch.Version)28 ArrayList (java.util.ArrayList)27 List (java.util.List)25 InetAddress (java.net.InetAddress)24 HashSet (java.util.HashSet)22 CountDownLatch (java.util.concurrent.CountDownLatch)21 ThreadPool (org.opensearch.threadpool.ThreadPool)21 ClusterSettings (org.opensearch.common.settings.ClusterSettings)20 Set (java.util.Set)16 PlainActionFuture (org.opensearch.action.support.PlainActionFuture)16 ClusterName (org.opensearch.cluster.ClusterName)16 HttpServerTransport (org.opensearch.http.HttpServerTransport)16 InetSocketAddress (java.net.InetSocketAddress)15 TimeUnit (java.util.concurrent.TimeUnit)15 OpenSearchTestCase (org.opensearch.test.OpenSearchTestCase)15