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

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

Introduction

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

Prototype

public static HostAndPort fromParts(String host, int port) 

Source Link

Document

Build a HostAndPort instance from separate host and port values.

Usage

From source file:brooklyn.networking.cloudstack.portforwarding.CloudstackPortForwarder.java

@Override
public HostAndPort openPortForwarding(HasNetworkAddresses targetVm, int targetPort,
        Optional<Integer> optionalPublicPort, Protocol protocol, Cidr accessingCidr) {
    Preconditions.checkNotNull(client);/*  www .  j a va  2  s .  co  m*/
    final String ipAddress = String.valueOf(targetVm.getPrivateAddresses().toArray()[0]);
    Maybe<VirtualMachine> vm = client.findVmByIp(ipAddress);
    Boolean useVpc = subnetTier.getConfig(USE_VPC);
    String publicIpId = subnetTier.getConfig(PUBLIC_IP_ID);

    if (vm.isAbsentOrNull()) {
        Map<VirtualMachine, List<String>> vmIpMapping = client.getVmIps();
        log.error("Could not find any VMs with Ip Address {}; contenders: {}", ipAddress, vmIpMapping);
        return null;
    }
    NIC nic = Iterables.find(vm.get().getNICs(), new Predicate<NIC>() {
        @Override
        public boolean apply(NIC input) {
            return (input == null) ? false : ipAddress.equals(input.getIPAddress());
        }
    });
    String networkId = nic.getNetworkId();

    Maybe<String> vpcId;
    if (useVpc) {
        vpcId = client.findVpcIdFromNetworkId(networkId);

        if (vpcId.isAbsent()) {
            log.error(
                    "Could not find associated VPCs with Network: {}; continuing without opening port-forwarding",
                    networkId);
            return null;
        }
    } else {
        vpcId = Maybe.absent("use-vpc not enabled");
    }

    try {
        synchronized (mutex) {
            Maybe<PublicIPAddress> allocatedPublicIpAddressId = client
                    .findPublicIpAddressByVmId(vm.get().getId());
            PublicIPAddress publicIpAddress;

            if (allocatedPublicIpAddressId.isPresent()) {
                publicIpAddress = allocatedPublicIpAddressId.get();
            } else if (Strings.isNonBlank(publicIpId)) {
                publicIpAddress = client.getCloudstackGlobalClient().getAddressApi()
                        .getPublicIPAddress(publicIpId);
                if (publicIpAddress == null) {
                    throw new IllegalStateException("No public-ip found with id " + publicIpAddress);
                }
            } else if (useVpc) {
                publicIpAddress = client.createIpAddressForVpc(vpcId.get());
            } else {
                publicIpAddress = client.createIpAddressForNetwork(networkId);
            }

            int publicPort;
            if (optionalPublicPort.isPresent()) {
                publicPort = optionalPublicPort.get();
            } else {
                PortForwardManager pfw = getPortForwardManager();
                publicPort = pfw.acquirePublicPort(publicIpAddress.getId());
            }

            log.info(format("Opening port:%s on vm:%s with IP:%s", targetPort, vm.get().getId(),
                    publicIpAddress.getIPAddress()));
            String jobid = client.createPortForwardRule(networkId, publicIpAddress.getId(),
                    PortForwardingRule.Protocol.TCP, publicPort, vm.get().getId(), targetPort);
            client.waitForJobSuccess(jobid);
            log.debug("Enabled port-forwarding on {}", publicIpAddress.getIPAddress() + ":" + publicPort);
            return HostAndPort.fromParts(publicIpAddress.getIPAddress(), publicPort);
        }
    } catch (Exception e) {
        log.error("Failed creating port forwarding rule on " + this + " to " + targetPort + "; continuing", e);
        // it might already be created, so don't crash and burn too hard!
        return null;
    }
}

From source file:org.jclouds.virtualbox.functions.MastersLoadingCache.java

@Override
public synchronized Master get(Image key) throws ExecutionException {
    // check if we have loaded this machine before
    if (masters.containsKey(key.getId())) {
        return masters.get(key.getId());
    }/*from www  . j a v  a  2  s .c  o  m*/
    checkState(!key.getId().contains(VIRTUALBOX_NODE_NAME_SEPARATOR),
            "master image names cannot contain \"" + VIRTUALBOX_NODE_NAME_SEPARATOR + "\"");
    String vmName = VIRTUALBOX_IMAGE_PREFIX + key.getId();
    IMachine masterMachine;
    Master master;
    // ready the preseed file server
    PreseedCfgServer server = new PreseedCfgServer();
    try {
        // try and find a master machine in vbox
        masterMachine = manager.get().getVBox().findMachine(vmName);
        master = Master.builder().machine(masterMachine).build();
    } catch (VBoxException e) {
        if (machineNotFoundException(e)) {
            // machine was not found try to build one from a yaml file
            YamlImage currentImage = checkNotNull(imageMapping.get(key.getId()), "currentImage");
            URI preseedServer;
            try {
                preseedServer = new URI(preconfigurationUrl);
                if (!socketTester
                        .apply(HostAndPort.fromParts(preseedServer.getHost(), preseedServer.getPort()))) {
                    server.start(preconfigurationUrl, currentImage.preseed_cfg);
                }
            } catch (URISyntaxException e1) {
                logger.error("Cannot start the preseed server", e);
                throw e;
            }

            MasterSpec masterSpec = buildMasterSpecFromYaml(currentImage, vmName);
            masterMachine = masterCreatorAndInstaller.apply(masterSpec);
            master = Master.builder().machine(masterMachine).spec(masterSpec).build();
        } else {
            logger.error("Problem during master creation", e);
            throw e;
        }
    } finally {
        server.stop();
    }

    masters.put(key.getId(), master);
    return master;
}

From source file:org.apache.beam.runners.fnexecution.control.DockerJobBundleFactory.java

private static ServerFactory getServerFactory() {
    switch (getPlatform()) {
    case LINUX://from ww  w .j av  a2  s .  c  o  m
        return ServerFactory.createDefault();
    case MAC:
        // NOTE: Deployment on Macs is intended for local development. As of 18.03, Docker-for-Mac
        // does not implement host networking (--networking=host is effectively a no-op). Instead,
        // we use a special DNS entry that points to the host:
        // https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds
        // The special hostname has historically changed between versions, so this is subject to
        // breakages and will likely only support the latest version at any time.
        return ServerFactory.createWithUrlFactory(
                (host, port) -> HostAndPort.fromParts(DOCKER_FOR_MAC_HOST, port).toString());
    default:
        LOG.warn("Unknown Docker platform. Falling back to default server factory");
        return ServerFactory.createDefault();
    }
}

From source file:org.apache.hadoop.hbase.rsgroup.RSGroupAdminEndpoint.java

@Override
public void moveServers(RpcController controller, MoveServersRequest request,
        RpcCallback<MoveServersResponse> done) {
    RSGroupAdminProtos.MoveServersResponse response = null;
    try {//from   ww w  .j av a  2  s .c o  m
        RSGroupAdminProtos.MoveServersResponse.Builder builder = RSGroupAdminProtos.MoveServersResponse
                .newBuilder();
        Set<HostAndPort> hostPorts = Sets.newHashSet();
        for (HBaseProtos.ServerName el : request.getServersList()) {
            hostPorts.add(HostAndPort.fromParts(el.getHostName(), el.getPort()));
        }
        groupAdminServer.moveServers(hostPorts, request.getTargetGroup());
        response = builder.build();
    } catch (IOException e) {
        ResponseConverter.setControllerException(controller, e);
    }
    done.run(response);
}

From source file:org.kududb.client.ProtobufHelper.java

/**
 * Convert a {@link org.kududb.Common.HostPortPB} to {@link com.google.common.net.HostAndPort}.
 * @param hostPortPB The fully initialized HostPortPB object. Must have both host and port
 *                   specified.// w w w . j  ava2s . com
 * @return An initialized initialized HostAndPort object.
 */
public static HostAndPort hostAndPortFromPB(Common.HostPortPB hostPortPB) {
    return HostAndPort.fromParts(hostPortPB.getHost(), hostPortPB.getPort());
}

From source file:org.springframework.xd.ec2.cloud.AWSInstanceChecker.java

/**
 * Verfies that the EC2 instance is running.  Also verfies ssh service is running
 * @param instanceParam The instance to be monitored.
 * @return  RunningInstance object./*from www  . j  a v  a2s .  com*/
 */
public RunningInstance checkAWSInstance(RunningInstance instanceParam) {
    Assert.notNull(instanceParam, "instanceParam can not be null");
    Predicate<RunningInstance> runningTester = retry(new InstanceStateRunning(client), 180, 1,
            TimeUnit.SECONDS);

    LOGGER.info("*******Verifying EC2 Instance*******");
    LOGGER.info(String.format("Awaiting instance to run"));

    if (!runningTester.apply(instanceParam))
        throw new DeployTimeoutException("timeout waiting for instance to run: " + instanceParam.getId());

    RunningInstance instance = AWSInstanceProvisioner.findInstanceById(client, instanceParam.getId());
    SocketOpen socketOpen = computeService.getContext().utils().injector().getInstance(SocketOpen.class);
    Predicate<HostAndPort> socketTester = retry(socketOpen, 300, 1, TimeUnit.SECONDS);
    LOGGER.info(String.format("Awaiting ssh service to start"));
    if (!socketTester.apply(HostAndPort.fromParts(instance.getIpAddress(), 22)))
        throw new DeployTimeoutException("timeout waiting for ssh to start: " + instance.getIpAddress());

    LOGGER.info(String.format("ssh service started%n"));
    return instance;
}

From source file:org.spring.springxdcloudInstaller.MainApp.java

static RunningInstance blockAdminInstanceRunning(EC2Client client, RunningInstance instance)
        throws TimeoutException {
    // create utilities that wait for the instance to finish
    RetryablePredicate<RunningInstance> runningTester = new RetryablePredicate<RunningInstance>(
            new InstanceStateRunning(client), 180, 5, TimeUnit.SECONDS);

    System.out.printf("%d: %s awaiting instance to run %n", System.currentTimeMillis(), instance.getId());
    if (!runningTester.apply(instance))
        throw new TimeoutException("timeout waiting for instance to run: " + instance.getId());

    instance = findInstanceById(client, instance.getId());

    RetryablePredicate<HostAndPort> socketTester = new RetryablePredicate<HostAndPort>(
            new InetSocketAddressConnect(), 300, 1, TimeUnit.SECONDS);
    System.out.printf("%d: %s awaiting ssh service to start%n", System.currentTimeMillis(),
            instance.getIpAddress());//from  ww w  .j  av  a2  s .  c om
    if (!socketTester.apply(HostAndPort.fromParts(instance.getIpAddress(), 22)))
        throw new TimeoutException("timeout waiting for ssh to start: " + instance.getIpAddress());

    System.out.printf("%d: %s ssh service started%n", System.currentTimeMillis(), instance.getIpAddress());

    System.out.printf("%d: %s awaiting Redis service to start%n", System.currentTimeMillis(),
            instance.getIpAddress());
    if (!socketTester.apply(HostAndPort.fromParts(instance.getIpAddress(), 6379)))
        throw new TimeoutException("timeout waiting for http to start: " + instance.getIpAddress());

    System.out.printf("%d: %s http service started%n", System.currentTimeMillis(), instance.getIpAddress());
    System.out.printf("instance %s ready%n", instance.getId());
    System.out.printf("ip address: %s%n", instance.getIpAddress());
    System.out.printf("dns name: %s%n", instance.getDnsName());
    return instance;
}

From source file:com.pingcap.tikv.PDClient.java

private void updateLeader(GetMembersResponse resp) {
    String leaderUrlStr = "URL Not Set";
    try {//from   ww  w  . ja  v  a2  s.c o  m
        long ts = System.nanoTime();
        synchronized (this) {
            // Lock for not flooding during pd error
            if (leaderWrapper != null && leaderWrapper.getCreateTime() > ts)
                return;

            if (resp == null) {
                resp = getMembers();
                if (resp == null)
                    return;
            }
            Member leader = resp.getLeader();
            List<String> leaderUrls = leader.getClientUrlsList();
            if (leaderUrls.isEmpty())
                return;
            leaderUrlStr = leaderUrls.get(0);
            // TODO: Why not strip protocol info on server side since grpc does not need it
            URL tURL = new URL(leaderUrlStr);
            HostAndPort newLeader = HostAndPort.fromParts(tURL.getHost(), tURL.getPort());
            if (leaderWrapper != null && newLeader.equals(leaderWrapper.getLeaderInfo())) {
                return;
            }

            // switch leader
            ManagedChannel clientChannel = getManagedChannel(newLeader);
            leaderWrapper = new LeaderWrapper(newLeader, PDGrpc.newBlockingStub(clientChannel),
                    PDGrpc.newStub(clientChannel), clientChannel, System.nanoTime());
            logger.info("Switched to new leader: %s", newLeader.toString());
        }
    } catch (MalformedURLException e) {
        logger.error("Client URL is not valid: %s", leaderUrlStr, e);
    } catch (Exception e) {
        logger.error("Error updating leader.", e);
    }
}

From source file:org.apache.accumulo.server.rpc.TServerUtils.java

/**
 * Create a NonBlockingServer with a custom thread pool that can dynamically resize itself.
 *///w  w w  .j av a  2 s.  c o  m
public static ServerAddress createNonBlockingServer(HostAndPort address, TProcessor processor,
        TProtocolFactory protocolFactory, final String serverName, String threadName, final int numThreads,
        final int numSTThreads, long timeBetweenThreadChecks, long maxMessageSize) throws TTransportException {

    final TNonblockingServerSocket transport = new TNonblockingServerSocket(
            new InetSocketAddress(address.getHostText(), address.getPort()));
    final CustomNonBlockingServer.Args options = new CustomNonBlockingServer.Args(transport);

    options.protocolFactory(protocolFactory);
    options.transportFactory(ThriftUtil.transportFactory(maxMessageSize));
    options.maxReadBufferBytes = maxMessageSize;
    options.stopTimeoutVal(5);

    // Create our own very special thread pool.
    ThreadPoolExecutor pool = createSelfResizingThreadPool(serverName, numThreads, numSTThreads,
            timeBetweenThreadChecks);

    options.executorService(pool);
    options.processorFactory(new TProcessorFactory(processor));

    if (address.getPort() == 0) {
        address = HostAndPort.fromParts(address.getHostText(), transport.getPort());
    }

    return new ServerAddress(new CustomNonBlockingServer(options), address);
}

From source file:org.excalibur.aqmp.handler.InstanceConfigurationHandler.java

private boolean startExcaliburApplication(VirtualMachine remoteHost, RemoteTask task,
        LoginCredentials loginCredentials) {
    LOG.debug("Starting the excalibur application");

    HeartbeatSender heartbeatSender = new HeartbeatSender(remoteHost.getConfiguration().getPublicIpAddress());

    try {//w ww  .  j  a va 2s  . c  o  m
        String text = IOUtils2.readLines(ClassUtils.getDefaultClassLoader().getResourceAsStream(
                "org/excalibur/service/deployment/resource/script/05-excalibur-script.script"));

        ScriptStatement script = new ScriptStatement().setStatement(text).setName("excalibur");
        ScriptStatementProcessor.assignVariableValues(remoteHost, script);

        String username = task.getUsername();
        HostAndPort host = HostAndPort.fromParts(remoteHost.getConfiguration().getPublicIpAddress(), 22);
        final StringBuilder output = new StringBuilder();

        final SshClient client = SshClientFactory.defaultSshClientFactory().create(host, loginCredentials);
        client.connect();

        final OnlineChannel shell = client.shell();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(shell.getOutput()));

        String home = String.format("/home/%s/excalibur", username);
        String sh = String.format("%s/excalibur.sh", home);
        client.connect();

        client.put(sh, script.getStatement());

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        String line = reader.readLine();
                        if (line == null) {
                            break;
                        }

                        output.append(line).append(Strings2.NEW_LINE);
                    } catch (IOException exception) {
                        LOG.warn("Error on reading the shell's output. Error message [{}]",
                                exception.getMessage());
                    }
                }
            }
        });

        t.start();

        shell.write(String.format("cd %s\n", home));
        shell.write(String.format("chmod +x %s/*.sh\n", home));
        shell.write("pwd\n");
        shell.write(String.format("nohup %s &\n", sh));
        shell.write(String.format("tail -f %s/nohup.out\n", home));

        heartbeatSender.setHeartbeat(30);

        long now = System.currentTimeMillis();
        long waitMaximumTwoMinutes = now + 2 * 1000 * 60;

        while (heartbeatSender.getLastActivityTime() < 1
                && System.currentTimeMillis() < waitMaximumTwoMinutes) {
            org.excalibur.core.util.ThreadUtils.sleep(TimeUnit.SECONDS.toMillis(40));
        }

        shell.close();
        client.disconnect();
        reader.close();
        heartbeatSender.shutdown();

        LOG.debug("Executed the script to start excalibur. The output is [{}]", output);
    } catch (IOException e) {
        LOG.error(">Error on creating the script to start excalibur.", e.getMessage(), e);
    }

    LOG.debug("Is excalibur running? [{}]", heartbeatSender.getLastActivityTime() > 0);

    return heartbeatSender.getLastActivityTime() > 0;
}