Example usage for com.google.common.net HostAndPort getHostText

List of usage examples for com.google.common.net HostAndPort getHostText

Introduction

In this page you can find the example usage for com.google.common.net HostAndPort getHostText.

Prototype

public String getHostText() 

Source Link

Document

Returns the portion of this HostAndPort instance that should represent the hostname or IPv4/IPv6 literal.

Usage

From source file:org.apache.omid.tso.client.TSOClient.java

@Override
public void nodeChanged() throws Exception {

    String tsoInfo = getCurrentTSOInfoFoundInZK(zkCurrentTsoPath);
    // TSO info includes the new TSO host:port address and epoch
    String[] currentTSOAndEpochArray = tsoInfo.split("#");
    HostAndPort hp = HostAndPort.fromString(currentTSOAndEpochArray[0]);
    setTSOAddress(hp.getHostText(), hp.getPort());
    epoch = Long.parseLong(currentTSOAndEpochArray[1]);
    LOG.info("CurrentTSO ZNode changed. New TSO Host & Port {}/Epoch {}", hp, getEpoch());
    if (currentChannel != null && currentChannel.isConnected()) {
        LOG.info("\tClosing channel with previous TSO {}", currentChannel);
        currentChannel.close();/*from   w w  w.j av a  2  s .  c  om*/
    }

}

From source file:org.sfs.SfsSingletonServer.java

protected Observable<HttpServer> createHttpServer(VertxContext<Server> vertxContext, HostAndPort hostAndPort,
        int verticleMaxHeaderSize, Router router) {
    ObservableFuture<HttpServer> handler = RxHelper.observableFuture();
    HttpServerOptions httpServerOptions = new HttpServerOptions().setMaxHeaderSize(verticleMaxHeaderSize)
            .setCompressionSupported(false).setUsePooledBuffers(true).setAcceptBacklog(10000)
            .setReuseAddress(true).setHandle100ContinueAutomatically(true);
    vertxContext.vertx().createHttpServer(httpServerOptions).requestHandler(router::accept)
            .listen(hostAndPort.getPort(), hostAndPort.getHostText(), handler.toHandler());
    return handler;
}

From source file:org.apache.beam.runners.dataflow.worker.windmill.GrpcWindmillServer.java

private synchronized void initializeWindmillService(Set<HostAndPort> endpoints) throws IOException {
    LOG.info("Initializing Streaming Engine GRPC client for endpoints: {}", endpoints);
    this.stubList.clear();
    this.syncStubList.clear();
    this.endpoints = ImmutableSet.<HostAndPort>copyOf(endpoints);
    for (HostAndPort endpoint : this.endpoints) {
        if ("localhost".equals(endpoint.getHostText())) {
            initializeLocalHost(endpoint.getPort());
        } else {//from w  ww  .j av  a 2s.  c o m
            CallCredentials creds = MoreCallCredentials
                    .from(new VendoredCredentialsAdapter(options.getGcpCredential()));
            this.stubList.add(CloudWindmillServiceV1Alpha1Grpc.newStub(remoteChannel(endpoint))
                    .withCallCredentials(creds));
            this.syncStubList.add(CloudWindmillServiceV1Alpha1Grpc.newBlockingStub(remoteChannel(endpoint))
                    .withCallCredentials(creds));
        }
    }
}

From source file:org.apache.beam.runners.dataflow.worker.windmill.GrpcWindmillServer.java

private Channel remoteChannel(HostAndPort endpoint) throws IOException {
    return NettyChannelBuilder.forAddress(endpoint.getHostText(), endpoint.getPort())
            .maxInboundMessageSize(java.lang.Integer.MAX_VALUE).negotiationType(NegotiationType.TLS)
            // Set ciphers(null) to not use GCM, which is disabled for Dataflow
            // due to it being horribly slow.
            .sslContext(GrpcSslContexts.forClient().ciphers(null).build()).build();
}

From source file:org.apache.omid.tso.client.TSOClient.java

private TSOClient(OmidClientConfiguration omidConf) throws IOException {

    // Start client with Nb of active threads = 3 as maximum.
    int tsoExecutorThreads = omidConf.getExecutorThreads();

    factory = new NioClientSocketChannelFactory(
            Executors/*from  w w w  .j  a  v a  2s  .c o m*/
                    .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("tsoclient-boss-%d").build()),
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setNameFormat("tsoclient-worker-%d").build()),
            tsoExecutorThreads);
    // Create the bootstrap
    bootstrap = new ClientBootstrap(factory);

    requestTimeoutInMs = omidConf.getRequestTimeoutInMs();
    requestMaxRetries = omidConf.getRequestMaxRetries();
    tsoReconnectionDelayInSecs = omidConf.getReconnectionDelayInSecs();

    LOG.info("Connecting to TSO...");
    HostAndPort hp;
    switch (omidConf.getConnectionType()) {
    case HA:
        zkClient = ZKUtils.initZKClient(omidConf.getConnectionString(), omidConf.getZkNamespace(),
                omidConf.getZkConnectionTimeoutInSecs());
        zkCurrentTsoPath = omidConf.getZkCurrentTsoPath();
        configureCurrentTSOServerZNodeCache(zkCurrentTsoPath);
        String tsoInfo = getCurrentTSOInfoFoundInZK(zkCurrentTsoPath);
        // TSO info includes the new TSO host:port address and epoch
        String[] currentTSOAndEpochArray = tsoInfo.split("#");
        hp = HostAndPort.fromString(currentTSOAndEpochArray[0]);
        setTSOAddress(hp.getHostText(), hp.getPort());
        epoch = Long.parseLong(currentTSOAndEpochArray[1]);
        LOG.info("\t* Current TSO host:port found in ZK: {} Epoch {}", hp, getEpoch());
        break;
    case DIRECT:
    default:
        hp = HostAndPort.fromString(omidConf.getConnectionString());
        setTSOAddress(hp.getHostText(), hp.getPort());
        LOG.info("\t* TSO host:port {} will be connected directly", hp);
        break;
    }

    fsmExecutor = Executors
            .newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat("tsofsm-%d").build());
    fsm = new StateMachine.FsmImpl(fsmExecutor);
    fsm.setInitState(new DisconnectedState(fsm));

    ChannelPipeline pipeline = bootstrap.getPipeline();
    pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(8 * 1024, 0, 4, 0, 4));
    pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
    pipeline.addLast("protobufdecoder", new ProtobufDecoder(TSOProto.Response.getDefaultInstance()));
    pipeline.addLast("protobufencoder", new ProtobufEncoder());
    pipeline.addLast("handler", new Handler(fsm));

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("reuseAddress", true);
    bootstrap.setOption("connectTimeoutMillis", 100);
}

From source file:net.myrrix.client.ClientRecommender.java

/**
 * @param replica host and port of replica to connect to
 * @param path URL to access (relative to context root)
 * @param method HTTP method to use/*w ww  . j a v  a2s .c om*/
 * @param doOutput if true, will need to write data into the request body
 * @param chunkedStreaming if true, use chunked streaming to accommodate a large upload, if possible
 * @param requestProperties additional request key/value pairs or {@code null} for none
 */
private HttpURLConnection buildConnectionToReplica(HostAndPort replica, String path, String method,
        boolean doOutput, boolean chunkedStreaming, Map<String, String> requestProperties) throws IOException {
    String contextPath = config.getContextPath();
    if (contextPath != null) {
        path = '/' + contextPath + path;
    }
    String protocol = config.isSecure() ? "https" : "http";
    URL url;
    try {
        url = new URL(protocol, replica.getHostText(), replica.getPort(), path);
    } catch (MalformedURLException mue) {
        // can't happen
        throw new IllegalStateException(mue);
    }
    log.debug("{} {}", method, url);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoInput(true);
    connection.setDoOutput(doOutput);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty(HttpHeaders.ACCEPT, DESIRED_RESPONSE_CONTENT_TYPE);
    if (closeConnection) {
        connection.setRequestProperty(HttpHeaders.CONNECTION, "close");
    }
    if (chunkedStreaming) {
        if (needAuthentication) {
            // Must buffer in memory if using authentication since it won't handle the authorization challenge
            log.debug("Authentication is enabled, so ingest data must be buffered in memory");
        } else {
            connection.setChunkedStreamingMode(0); // Use default buffer size
        }
    }
    if (requestProperties != null) {
        for (Map.Entry<String, String> entry : requestProperties.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    return connection;
}

From source file:io.airlift.jmx.JmxAgent.java

@Inject
public JmxAgent(JmxConfig config) throws IOException {
    // first, see if the jmx agent is already started (e.g., via command line properties passed to the jvm)
    HostAndPort address = getRunningAgentAddress(config.getRmiRegistryPort(), config.getRmiServerPort());
    if (address != null) {
        log.info("JMX agent already running and listening on %s", address);
    } else {//www .  j  a  va  2s. co  m
        // otherwise, start it manually
        int registryPort;
        if (config.getRmiRegistryPort() == null) {
            registryPort = NetUtils.findUnusedPort();
        } else {
            registryPort = config.getRmiRegistryPort();
        }

        int serverPort = 0;
        if (config.getRmiServerPort() != null) {
            serverPort = config.getRmiServerPort();
        }

        // This is somewhat of a hack, but the jmx agent in Oracle/OpenJDK doesn't
        // have a programmatic API for starting it and controlling its parameters
        System.setProperty("com.sun.management.jmxremote", "true");
        System.setProperty("com.sun.management.jmxremote.port", Integer.toString(registryPort));
        System.setProperty("com.sun.management.jmxremote.rmi.port", Integer.toString(serverPort));
        System.setProperty("com.sun.management.jmxremote.authenticate", "false");
        System.setProperty("com.sun.management.jmxremote.ssl", "false");

        try {
            Agent.startAgent();
        } catch (Exception e) {
            throw Throwables.propagate(e);
        }

        try {
            // This is how the jdk jmx agent constructs its url
            JMXServiceURL url = new JMXServiceURL("rmi", null, registryPort);
            address = HostAndPort.fromParts(url.getHost(), url.getPort());
        } catch (MalformedURLException e) {
            // should not happen...
            throw new AssertionError(e);
        }

        log.info("JMX agent started and listening on %s", address);
    }

    this.url = new JMXServiceURL(String.format("service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi",
            address.getHostText(), address.getPort()));
}

From source file:brooklyn.location.jclouds.JcloudsLocation.java

protected SshMachineLocation createTemporarySshMachineLocation(HostAndPort hostAndPort, LoginCredentials creds,
        ConfigBag config) {//from w w  w.j av  a  2  s  .  co m
    Optional<String> initialPassword = creds.getOptionalPassword();
    Optional<String> initialPrivateKey = creds.getOptionalPrivateKey();
    String initialUser = creds.getUser();

    Map<String, Object> sshProps = Maps.newLinkedHashMap(config.getAllConfig());
    sshProps.put("user", initialUser);
    sshProps.put("address", hostAndPort.getHostText());
    sshProps.put("port", hostAndPort.getPort());
    if (initialPassword.isPresent())
        sshProps.put("password", initialPassword.get());
    if (initialPrivateKey.isPresent())
        sshProps.put("privateKeyData", initialPrivateKey.get());
    if (initialPrivateKey.isPresent())
        sshProps.put("privateKeyData", initialPrivateKey.get());

    if (isManaged()) {
        return getManagementContext().getLocationManager().createLocation(sshProps, SshMachineLocation.class);
    } else {
        return new SshMachineLocation(sshProps);
    }
}

From source file:brooklyn.location.jclouds.JcloudsLocation.java

private String getPublicHostnameAws(HostAndPort sshHostAndPort, ConfigBag setup) {
    SshMachineLocation sshLocByIp = null;
    try {/* w ww .  j  a  v  a 2  s .  c  o m*/
        ConfigBag sshConfig = extractSshConfig(setup, new ConfigBag());

        // TODO messy way to get an SSH session
        if (isManaged()) {
            sshLocByIp = getManagementContext().getLocationManager()
                    .createLocation(LocationSpec.create(SshMachineLocation.class)
                            .configure("address", sshHostAndPort.getHostText())
                            .configure("port", sshHostAndPort.getPort()).configure("user", getUser(setup))
                            .configure(sshConfig.getAllConfig()));
        } else {
            MutableMap<Object, Object> locationProps = MutableMap.builder()
                    .put("address", sshHostAndPort.getHostText()).put("port", sshHostAndPort.getPort())
                    .put("user", getUser(setup)).putAll(sshConfig.getAllConfig()).build();
            sshLocByIp = new SshMachineLocation(locationProps);
        }

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ByteArrayOutputStream errStream = new ByteArrayOutputStream();
        int exitcode = sshLocByIp.execCommands(MutableMap.of("out", outStream, "err", errStream),
                "get public AWS hostname", ImmutableList.of(BashCommands.INSTALL_CURL,
                        "echo `curl --silent --retry 20 http://169.254.169.254/latest/meta-data/public-hostname`; exit"));
        String outString = new String(outStream.toByteArray());
        String[] outLines = outString.split("\n");
        for (String line : outLines) {
            if (line.startsWith("ec2-"))
                return line.trim();
        }
        throw new IllegalStateException(
                "Could not obtain aws-ec2 hostname for vm " + sshHostAndPort + "; exitcode=" + exitcode
                        + "; stdout=" + outString + "; stderr=" + new String(errStream.toByteArray()));
    } finally {
        Streams.closeQuietly(sshLocByIp);
    }
}

From source file:org.apache.brooklyn.location.jclouds.DefaultConnectivityResolver.java

/**
 * Combines the given resolve options with the customiser's configuration to determine the
 * best address and credential pair for management. In particular, if the resolve options
 * allow it will check that the credential is actually valid for the address.
 *///from   w  ww . j a v  a  2  s  .c  o  m
@Override
public ManagementAddressResolveResult resolve(JcloudsLocation location, NodeMetadata node, ConfigBag config,
        ConnectivityResolverOptions options) {
    LOG.debug("{} resolving management parameters for {}, node={}, config={}, options={}",
            new Object[] { this, location, node, config, options });
    final Stopwatch timer = Stopwatch.createStarted();
    // Should only be null in tests.
    final Entity contextEntity = getContextEntity(config);
    if (shouldPublishNetworks() && !options.isRebinding() && contextEntity != null) {
        publishNetworks(node, contextEntity);
    }
    HostAndPort hapChoice = null;
    LoginCredentials credChoice = null;

    final Iterable<HostAndPort> managementCandidates = getManagementCandidates(location, node, config, options);
    Iterable<LoginCredentials> credentialCandidates = Collections.emptyList();
    if (!Iterables.isEmpty(managementCandidates)) {
        credentialCandidates = getCredentialCandidates(location, node, options, config);

        // Try each pair of address and credential until one succeeds.
        if (shouldCheckCredentials() && options.pollForReachableAddresses()) {
            for (HostAndPort hap : managementCandidates) {
                for (LoginCredentials cred : credentialCandidates) {
                    LOG.trace("Testing host={} with credential={}", hap, cred);
                    if (checkCredential(location, hap, cred, config, options.isWindows())) {
                        hapChoice = hap;
                        credChoice = cred;
                        break;
                    }
                }
                if (hapChoice != null)
                    break;
            }
        } else if (shouldCheckCredentials()) {
            LOG.debug("{} set on {} but pollForFirstReachableAddress={}",
                    new Object[] { CHECK_CREDENTIALS.getName(), this, options.pollForReachableAddresses() });
        }
    }

    if (hapChoice == null) {
        LOG.trace("Choosing first management candidate given node={} and mode={}", node, getNetworkMode());
        hapChoice = Iterables.getFirst(managementCandidates, null);
    }
    if (hapChoice == null) {
        LOG.trace("Choosing first address of node={} in mode={}", node, getNetworkMode());
        final Iterator<String> hit = getResolvableAddressesWithMode(node).iterator();
        if (hit.hasNext())
            HostAndPort.fromHost(hit.next());
    }

    if (hapChoice == null) {
        LOG.error("None of the addresses of node {} are reachable in mode {}",
                new Object[] { node, getNetworkMode() });
        throw new IllegalStateException(
                "Could not determine management address for node: " + node + " in mode: " + getNetworkMode());
    }

    if (credChoice == null) {
        credChoice = Iterables.getFirst(credentialCandidates, null);
        if (credChoice == null) {
            throw new IllegalStateException("No credentials configured for " + location);
        }
    }

    if (contextEntity != null) {
        contextEntity.sensors().set(Attributes.ADDRESS, hapChoice.getHostText());
    }

    // Treat AWS as a special case because the DNS fully qualified hostname in AWS is
    // (normally?!) a good way to refer to the VM from both inside and outside of the region.
    if (!isNetworkModeSet() && !options.isWindows()) {
        final boolean lookupAwsHostname = Boolean.TRUE
                .equals(config.get(JcloudsLocationConfig.LOOKUP_AWS_HOSTNAME));
        String provider = config.get(JcloudsLocationConfig.CLOUD_PROVIDER);
        if (provider == null) {
            provider = location.getProvider();
        }
        if (options.waitForConnectable() && "aws-ec2".equals(provider) && lookupAwsHostname) {
            // getHostnameAws sshes to the machine and curls 169.254.169.254/latest/meta-data/public-hostname.
            try {
                LOG.debug("Resolving AWS hostname of {}", location);
                String result = location.getHostnameAws(hapChoice, credChoice, config);
                hapChoice = HostAndPort.fromParts(result, hapChoice.getPort());
                LOG.debug("Resolved AWS hostname of {}: {}", location, result);
            } catch (Exception e) {
                LOG.debug("Failed to resolve AWS hostname of " + location, e);
            }
        }
    }

    ManagementAddressResolveResult result = new ManagementAddressResolveResult(hapChoice, credChoice);
    LOG.debug("{} resolved management parameters for {} in {}: {}",
            new Object[] { this, location, Duration.of(timer), result });
    return result;
}