Search in sources :

Example 1 with PortsRange

use of org.elasticsearch.common.transport.PortsRange in project elasticsearch-jetty by sonian.

the class JettyHttpServerTransport method doStart.

@Override
protected void doStart() throws ElasticsearchException {
    PortsRange portsRange = new PortsRange(port);
    final AtomicReference<Exception> lastException = new AtomicReference<Exception>();
    Log.setLog(loggerWrapper);
    portsRange.iterate(new PortsRange.PortCallback() {

        @Override
        public boolean onPortNumber(int portNumber) {
            try {
                Server server = null;
                XmlConfiguration lastXmlConfiguration = null;
                Object[] objs = new Object[jettyConfig.length];
                Map<String, String> esProperties = jettySettings(bindHost, portNumber);
                for (int i = 0; i < jettyConfig.length; i++) {
                    String configFile = jettyConfig[i];
                    URL config = environment.resolveConfig(configFile);
                    XmlConfiguration xmlConfiguration = new XmlConfiguration(config);
                    // in the later configurations
                    if (lastXmlConfiguration != null) {
                        xmlConfiguration.getIdMap().putAll(lastXmlConfiguration.getIdMap());
                    } else {
                        xmlConfiguration.getIdMap().put("ESServerTransport", JettyHttpServerTransport.this);
                        xmlConfiguration.getIdMap().put("ESClient", client);
                    }
                    // Inject elasticsearch properties
                    xmlConfiguration.getProperties().putAll(esProperties);
                    objs[i] = xmlConfiguration.configure();
                    lastXmlConfiguration = xmlConfiguration;
                }
                // Find jetty Server with id  jettyConfigServerId
                Object serverObject = lastXmlConfiguration.getIdMap().get(jettyConfigServerId);
                if (serverObject != null) {
                    if (serverObject instanceof Server) {
                        server = (Server) serverObject;
                    }
                } else {
                    // For compatibility - if it's not available, find first available jetty Server
                    for (Object obj : objs) {
                        if (obj instanceof Server) {
                            server = (Server) obj;
                            break;
                        }
                    }
                }
                if (server == null) {
                    logger.error("Cannot find server with id [{}] in configuration files [{}]", jettyConfigServerId, jettyConfig);
                    lastException.set(new ElasticsearchException("Cannot find server with id " + jettyConfigServerId));
                    return true;
                }
                // Keep it for now for backward compatibility with previous versions of jetty.xml
                server.setAttribute(TRANSPORT_ATTRIBUTE, JettyHttpServerTransport.this);
                // Start all lifecycle objects configured by xml configurations
                for (Object obj : objs) {
                    if (obj instanceof LifeCycle) {
                        LifeCycle lifeCycle = (LifeCycle) obj;
                        if (!lifeCycle.isRunning()) {
                            lifeCycle.start();
                        }
                    }
                }
                jettyServer = server;
                lastException.set(null);
            } catch (BindException e) {
                lastException.set(e);
                return false;
            } catch (Exception e) {
                logger.error("Jetty Startup Failed ", e);
                lastException.set(e);
                return true;
            }
            return true;
        }
    });
    if (lastException.get() != null) {
        throw new BindHttpException("Failed to bind to [" + port + "]", lastException.get());
    }
    InetSocketAddress jettyBoundAddress = findFirstInetConnector(jettyServer);
    if (jettyBoundAddress != null) {
        InetSocketAddress publishAddress;
        try {
            publishAddress = new InetSocketAddress(networkService.resolvePublishHostAddress(publishHost), jettyBoundAddress.getPort());
        } catch (Exception e) {
            throw new BindTransportException("Failed to resolve publish address", e);
        }
        this.boundAddress = new BoundTransportAddress(new InetSocketTransportAddress(jettyBoundAddress), new InetSocketTransportAddress(publishAddress));
    } else {
        throw new BindHttpException("Failed to find a jetty connector with Inet transport");
    }
}
Also used : LifeCycle(org.eclipse.jetty.util.component.LifeCycle) Server(org.eclipse.jetty.server.Server) AtomicReference(java.util.concurrent.atomic.AtomicReference) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) ElasticsearchException(org.elasticsearch.ElasticsearchException) PortsRange(org.elasticsearch.common.transport.PortsRange) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) ElasticsearchException(org.elasticsearch.ElasticsearchException) BindTransportException(org.elasticsearch.transport.BindTransportException) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) BindTransportException(org.elasticsearch.transport.BindTransportException) Map(java.util.Map)

Example 2 with PortsRange

use of org.elasticsearch.common.transport.PortsRange in project crate by crate.

the class PostgresNetty method bindAddress.

private InetSocketTransportAddress bindAddress(final InetAddress hostAddress) {
    PortsRange portsRange = new PortsRange(port);
    final AtomicReference<Exception> lastException = new AtomicReference<>();
    final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>();
    boolean success = portsRange.iterate(new PortsRange.PortCallback() {

        @Override
        public boolean onPortNumber(int portNumber) {
            try {
                synchronized (serverChannels) {
                    Channel channel = bootstrap.bind(new InetSocketAddress(hostAddress, portNumber));
                    serverChannels.add(channel);
                    boundSocket.set((InetSocketAddress) channel.getLocalAddress());
                }
            } catch (Exception e) {
                lastException.set(e);
                return false;
            }
            return true;
        }
    });
    if (!success) {
        throw new BindPostgresException("Failed to bind to [" + port + "]", lastException.get());
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Bound psql to address {{}}", NetworkAddress.format(boundSocket.get()));
    }
    return new InetSocketTransportAddress(boundSocket.get());
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(org.jboss.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) PortsRange(org.elasticsearch.common.transport.PortsRange) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) BindTransportException(org.elasticsearch.transport.BindTransportException) BindHttpException(org.elasticsearch.http.BindHttpException) IOException(java.io.IOException)

Example 3 with PortsRange

use of org.elasticsearch.common.transport.PortsRange in project elasticsearch by elastic.

the class TcpTransport method bindToPort.

protected InetSocketAddress bindToPort(final String name, final InetAddress hostAddress, String port) {
    PortsRange portsRange = new PortsRange(port);
    final AtomicReference<Exception> lastException = new AtomicReference<>();
    final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>();
    boolean success = portsRange.iterate(portNumber -> {
        try {
            Channel channel = bind(name, new InetSocketAddress(hostAddress, portNumber));
            synchronized (serverChannels) {
                List<Channel> list = serverChannels.get(name);
                if (list == null) {
                    list = new ArrayList<>();
                    serverChannels.put(name, list);
                }
                list.add(channel);
                boundSocket.set(getLocalAddress(channel));
            }
        } catch (Exception e) {
            lastException.set(e);
            return false;
        }
        return true;
    });
    if (!success) {
        throw new BindTransportException("Failed to bind to [" + port + "]", lastException.get());
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Bound profile [{}] to address {{}}", name, NetworkAddress.format(boundSocket.get()));
    }
    return boundSocket.get();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) PortsRange(org.elasticsearch.common.transport.PortsRange) ElasticsearchException(org.elasticsearch.ElasticsearchException) NotCompressedException(org.elasticsearch.common.compress.NotCompressedException) StreamCorruptedException(java.io.StreamCorruptedException) CancelledKeyException(java.nio.channels.CancelledKeyException) NetworkExceptionHelper.isCloseConnectionException(org.elasticsearch.common.transport.NetworkExceptionHelper.isCloseConnectionException) BindException(java.net.BindException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) NetworkExceptionHelper.isConnectException(org.elasticsearch.common.transport.NetworkExceptionHelper.isConnectException)

Example 4 with PortsRange

use of org.elasticsearch.common.transport.PortsRange in project elasticsearch by elastic.

the class TcpTransport method parse.

/** parse a hostname+port range spec into its equivalent addresses */
static TransportAddress[] parse(String hostPortString, String defaultPortRange, int perAddressLimit) throws UnknownHostException {
    Objects.requireNonNull(hostPortString);
    String host;
    String portString = null;
    if (hostPortString.startsWith("[")) {
        // Parse a bracketed host, typically an IPv6 literal.
        Matcher matcher = BRACKET_PATTERN.matcher(hostPortString);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("Invalid bracketed host/port range: " + hostPortString);
        }
        host = matcher.group(1);
        // could be null
        portString = matcher.group(2);
    } else {
        int colonPos = hostPortString.indexOf(':');
        if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) {
            // Exactly 1 colon.  Split into host:port.
            host = hostPortString.substring(0, colonPos);
            portString = hostPortString.substring(colonPos + 1);
        } else {
            // 0 or 2+ colons.  Bare hostname or IPv6 literal.
            host = hostPortString;
            // 2+ colons and not bracketed: exception
            if (colonPos >= 0) {
                throw new IllegalArgumentException("IPv6 addresses must be bracketed: " + hostPortString);
            }
        }
    }
    // if port isn't specified, fill with the default
    if (portString == null || portString.isEmpty()) {
        portString = defaultPortRange;
    }
    // generate address for each port in the range
    Set<InetAddress> addresses = new HashSet<>(Arrays.asList(InetAddress.getAllByName(host)));
    List<TransportAddress> transportAddresses = new ArrayList<>();
    int[] ports = new PortsRange(portString).ports();
    int limit = Math.min(ports.length, perAddressLimit);
    for (int i = 0; i < limit; i++) {
        for (InetAddress address : addresses) {
            transportAddresses.add(new TransportAddress(address, ports[i]));
        }
    }
    return transportAddresses.toArray(new TransportAddress[transportAddresses.size()]);
}
Also used : Matcher(java.util.regex.Matcher) TransportAddress(org.elasticsearch.common.transport.TransportAddress) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) PortsRange(org.elasticsearch.common.transport.PortsRange) HashSet(java.util.HashSet) IntHashSet(com.carrotsearch.hppc.IntHashSet)

Aggregations

PortsRange (org.elasticsearch.common.transport.PortsRange)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 IOException (java.io.IOException)2 InetSocketAddress (java.net.InetSocketAddress)2 ElasticsearchException (org.elasticsearch.ElasticsearchException)2 BoundTransportAddress (org.elasticsearch.common.transport.BoundTransportAddress)2 InetSocketTransportAddress (org.elasticsearch.common.transport.InetSocketTransportAddress)2 BindTransportException (org.elasticsearch.transport.BindTransportException)2 IntHashSet (com.carrotsearch.hppc.IntHashSet)1 StreamCorruptedException (java.io.StreamCorruptedException)1 BindException (java.net.BindException)1 InetAddress (java.net.InetAddress)1 UnknownHostException (java.net.UnknownHostException)1 CancelledKeyException (java.nio.channels.CancelledKeyException)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 Matcher (java.util.regex.Matcher)1 Server (org.eclipse.jetty.server.Server)1 LifeCycle (org.eclipse.jetty.util.component.LifeCycle)1