List of usage examples for com.google.common.net HostAndPort getPort
public int getPort()
From source file:org.jclouds.sshj.SshjSshClient.java
public SshjSshClient(BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket, LoginCredentials loginCredentials, int timeout) { this.user = checkNotNull(loginCredentials, "loginCredentials").getUser(); this.host = checkNotNull(socket, "socket").getHostText(); checkArgument(socket.getPort() > 0, "ssh port must be greater then zero" + socket.getPort()); checkArgument(loginCredentials.getPassword() != null || loginCredentials.getPrivateKey() != null, "you must specify a password or a key"); this.backoffLimitedRetryHandler = checkNotNull(backoffLimitedRetryHandler, "backoffLimitedRetryHandler"); if (loginCredentials.getPrivateKey() == null) { this.toString = String.format("%s:pw[%s]@%s:%d", loginCredentials.getUser(), base16().lowerCase().encode(md5().hashString(loginCredentials.getPassword(), UTF_8).asBytes()), host, socket.getPort()); } else {//from www . jav a 2s . c o m String fingerPrint = fingerprintPrivateKey(loginCredentials.getPrivateKey()); String sha1 = sha1PrivateKey(loginCredentials.getPrivateKey()); this.toString = String.format("%s:rsa[fingerprint(%s),sha1(%s)]@%s:%d", loginCredentials.getUser(), fingerPrint, sha1, host, socket.getPort()); } sshClientConnection = SSHClientConnection.builder() .hostAndPort(HostAndPort.fromParts(host, socket.getPort())).loginCredentials(loginCredentials) .connectTimeout(timeout).sessionTimeout(timeout).build(); }
From source file:brooklyn.networking.portforwarding.PortForwarderIptables.java
protected boolean systemCreatePortForwarding(HostAndPort publicSide, HostAndPort targetSide, Cidr cidr) { checkNotNull(publicSide, "publicSide"); checkArgument(publicSide.getHostText().equals(forwarderIp), "publicSide %s should match forwarderIp %s", publicSide, forwarderIp);/*w w w . jav a 2s .c o m*/ checkNotNull(targetSide, "targetSide"); try { List<String> commands = ImmutableList.of( sudo(String.format( "/sbin/iptables -t nat -I PREROUTING -p tcp --dport %s -j DNAT --to-destination %s:%s", publicSide.getPort(), targetSide.getHostText(), targetSide.getPort())), sudo("/sbin/iptables -t nat -I POSTROUTING -j MASQUERADE"), IptablesCommands.saveIptablesRules()); // note save already wrapped in sudo int result = forwarderMachine.execScript("port-forwarding " + publicSide + "->" + targetSide, commands); boolean opened = systemOpenFirewall(publicSide.getHostText(), publicSide.getPort(), publicSide.getPort(), Protocol.TCP, cidr); // targetPort doesn't need to be opened - assuming both on internal network, and already opened if (result != 0) { log.error("Failed creating port forwarding rule on {}: {} -> {}", new Object[] { this, publicSide, targetSide }); // it might already be created, so don't crash and burn too hard! return false; } if (!opened) { log.error("Failed opening forwarding port on {}: {} -> {}", new Object[] { this, publicSide, targetSide }); // it might already be created, so don't crash and burn too hard! return false; } } catch (Exception e) { log.error("Failed creating port forwarding rule on {}: {} -> {}", new Object[] { this, publicSide, targetSide }); // it might already be created, so don't crash and burn too hard! return false; } return true; }
From source file:io.brooklyn.ambari.server.AmbariServerImpl.java
@Override protected void connectSensors() { super.connectSensors(); connectServiceUpIsRunning();//from w w w . j a v a 2 s . c o m HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getAttribute(HTTP_PORT)); ambariUri = String.format("http://%s:%d", hp.getHostText(), hp.getPort()); setAttribute(Attributes.MAIN_URI, URI.create(ambariUri)); sensors().set(AmbariServer.USERNAME, USERNAME); usernamePasswordCredentials = new UsernamePasswordCredentials(USERNAME, getAttribute(AmbariServer.PASSWORD) == null ? INITIAL_PASSWORD : getAttribute(AmbariServer.PASSWORD)); restAdapter = new RestAdapter.Builder().setEndpoint(ambariUri) .setRequestInterceptor(new AmbariRequestInterceptor(usernamePasswordCredentials)) .setLogLevel(RestAdapter.LogLevel.FULL).build(); serviceUpHttpFeed = HttpFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS).baseUri(ambariUri) .poll(new HttpPollConfig<Boolean>(URL_REACHABLE) .onSuccess(HttpValueFunctions.responseCodeEquals(200)) .onFailureOrException(Functions.constant(false))) .build(); enrichers().add(Enrichers.builder().updatingMap(Attributes.SERVICE_NOT_UP_INDICATORS).from(URL_REACHABLE) .computing(Functionals.ifNotEquals(true).value("URL not reachable")).build()); connectAuthenticatedSensors(); }
From source file:brooklyn.entity.monitoring.zabbix.ZabbixFeed.java
@Override protected void preStart() { final Supplier<URI> baseUriProvider = getConfig(BASE_URI_PROVIDER); final Function<? super EntityLocal, String> uniqueHostnameGenerator = getConfig(UNIQUE_HOSTNAME_GENERATOR); final Integer groupId = getConfig(GROUP_ID); final Integer templateId = getConfig(TEMPLATE_ID); final Set<ZabbixPollConfig<?>> polls = getConfig(POLLS); log.info("starting zabbix feed for {}", entity); // TODO if supplier returns null, we may wish to defer initialization until url available? // TODO for https should we really trust all? final HttpClient httpClient = HttpTool.httpClientBuilder().trustAll() .clientConnectionManager(new ThreadSafeClientConnManager()) .reuseStrategy(new NoConnectionReuseStrategy()).uri(baseUriProvider.get()).build(); // Registration job, calls Zabbix host.create API final Callable<HttpToolResponse> registerJob = new Callable<HttpToolResponse>() { @Override/* ww w . j av a 2 s . c o m*/ public HttpToolResponse call() throws Exception { if (!registered.get()) { // Find the first machine, if available Optional<Location> location = Iterables.tryFind(entity.getLocations(), Predicates.instanceOf(MachineLocation.class)); if (!location.isPresent()) { return null; // Do nothing until location is present } MachineLocation machine = (MachineLocation) location.get(); String host = uniqueHostnameGenerator.apply(entity); // Select address and port using port-forwarding if available String address = entity.getAttribute(Attributes.ADDRESS); Integer port = entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_PORT); if (machine instanceof SupportsPortForwarding) { Cidr management = entity.getConfig(BrooklynAccessUtils.MANAGEMENT_ACCESS_CIDR); HostAndPort forwarded = ((SupportsPortForwarding) machine).getSocketEndpointFor(management, port); address = forwarded.getHostText(); port = forwarded.getPort(); } // Fill in the JSON template and POST it byte[] body = JSON_HOST_CREATE .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{host}}", host).replace("{{ip}}", address) .replace("{{port}}", Integer.toString(port)) .replace("{{groupId}}", Integer.toString(groupId)) .replace("{{templateId}}", Integer.toString(templateId)) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } return null; } }; // The handler for the registration job PollHandler<? super HttpToolResponse> registrationHandler = new PollHandler<HttpToolResponse>() { @Override public void onSuccess(HttpToolResponse val) { if (registered.get() || val == null) { return; // Skip if we are registered already or no data from job } JsonObject response = HttpValueFunctions.jsonContents().apply(val).getAsJsonObject(); if (response.has("error")) { // Parse the JSON error object and log the message JsonObject error = response.get("error").getAsJsonObject(); String message = error.get("message").getAsString(); String data = error.get("data").getAsString(); log.warn("zabbix failed registering host - {}: {}", message, data); } else if (response.has("result")) { // Parse the JSON result object and save the hostId JsonObject result = response.get("result").getAsJsonObject(); String hostId = result.get("hostids").getAsJsonArray().get(0).getAsString(); // Update the registered status if not set if (registered.compareAndSet(false, true)) { entity.setAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID, hostId); log.info("zabbix registered host as id {}", hostId); } } else { throw new IllegalStateException(String .format("zabbix host registration returned invalid result: %s", response.toString())); } } @Override public boolean checkSuccess(HttpToolResponse val) { return (val.getResponseCode() == 200); } @Override public void onFailure(HttpToolResponse val) { log.warn("zabbix sever returned failure code: {}", val.getResponseCode()); } @Override public void onException(Exception exception) { log.warn("zabbix exception registering host", exception); } @Override public String toString() { return super.toString() + "[" + getDescription() + "]"; } @Override public String getDescription() { return "Zabbix rest poll"; } }; // Schedule registration attempt once per second getPoller().scheduleAtFixedRate(registerJob, registrationHandler, 1000l); // TODO make configurable // Create a polling job for each Zabbix metric for (final ZabbixPollConfig<?> config : polls) { Callable<HttpToolResponse> pollJob = new Callable<HttpToolResponse>() { @Override public HttpToolResponse call() throws Exception { if (registered.get()) { if (log.isTraceEnabled()) log.trace("zabbix polling {} for {}", entity, config); byte[] body = JSON_ITEM_GET .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{hostId}}", entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID)) .replace("{{itemKey}}", config.getItemKey()) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } else { throw new IllegalStateException("zabbix agent not yet registered"); } } }; // Schedule the Zabbix polling job AttributePollHandler<? super HttpToolResponse> pollHandler = new AttributePollHandler<HttpToolResponse>( config, entity, this); long minPeriod = Integer.MAX_VALUE; // TODO make configurable if (config.getPeriod() > 0) minPeriod = Math.min(minPeriod, config.getPeriod()); getPoller().scheduleAtFixedRate(pollJob, pollHandler, minPeriod); } }
From source file:org.apache.brooklyn.entity.monitoring.zabbix.ZabbixFeed.java
@Override protected void preStart() { final Supplier<URI> baseUriProvider = getConfig(BASE_URI_PROVIDER); final Function<? super EntityLocal, String> uniqueHostnameGenerator = getConfig(UNIQUE_HOSTNAME_GENERATOR); final Integer groupId = getConfig(GROUP_ID); final Integer templateId = getConfig(TEMPLATE_ID); final Set<ZabbixPollConfig<?>> polls = getConfig(POLLS); log.info("starting zabbix feed for {}", entity); // TODO if supplier returns null, we may wish to defer initialization until url available? // TODO for https should we really trust all? final HttpClient httpClient = HttpTool.httpClientBuilder().trustAll() .clientConnectionManager(new ThreadSafeClientConnManager()) .reuseStrategy(new NoConnectionReuseStrategy()).uri(baseUriProvider.get()).build(); // Registration job, calls Zabbix host.create API final Callable<HttpToolResponse> registerJob = new Callable<HttpToolResponse>() { @Override/* w w w. ja va2 s . c o m*/ public HttpToolResponse call() throws Exception { if (!registered.get()) { // Find the first machine, if available Optional<Location> location = Iterables.tryFind(entity.getLocations(), Predicates.instanceOf(MachineLocation.class)); if (!location.isPresent()) { return null; // Do nothing until location is present } MachineLocation machine = (MachineLocation) location.get(); String host = uniqueHostnameGenerator.apply(entity); // Select address and port using port-forwarding if available String address = entity.getAttribute(Attributes.ADDRESS); Integer port = entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_PORT); if (machine instanceof SupportsPortForwarding) { Cidr management = entity.getConfig(BrooklynAccessUtils.MANAGEMENT_ACCESS_CIDR); HostAndPort forwarded = ((SupportsPortForwarding) machine).getSocketEndpointFor(management, port); address = forwarded.getHostText(); port = forwarded.getPort(); } // Fill in the JSON template and POST it byte[] body = JSON_HOST_CREATE .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{host}}", host).replace("{{ip}}", address) .replace("{{port}}", Integer.toString(port)) .replace("{{groupId}}", Integer.toString(groupId)) .replace("{{templateId}}", Integer.toString(templateId)) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } return null; } }; // The handler for the registration job PollHandler<? super HttpToolResponse> registrationHandler = new PollHandler<HttpToolResponse>() { @Override public void onSuccess(HttpToolResponse val) { if (registered.get() || val == null) { return; // Skip if we are registered already or no data from job } JsonObject response = HttpValueFunctions.jsonContents().apply(val).getAsJsonObject(); if (response.has("error")) { // Parse the JSON error object and log the message JsonObject error = response.get("error").getAsJsonObject(); String message = error.get("message").getAsString(); String data = error.get("data").getAsString(); log.warn("zabbix failed registering host - {}: {}", message, data); } else if (response.has("result")) { // Parse the JSON result object and save the hostId JsonObject result = response.get("result").getAsJsonObject(); String hostId = result.get("hostids").getAsJsonArray().get(0).getAsString(); // Update the registered status if not set if (registered.compareAndSet(false, true)) { entity.sensors().set(ZabbixMonitored.ZABBIX_AGENT_HOSTID, hostId); log.info("zabbix registered host as id {}", hostId); } } else { throw new IllegalStateException(String .format("zabbix host registration returned invalid result: %s", response.toString())); } } @Override public boolean checkSuccess(HttpToolResponse val) { return (val.getResponseCode() == 200); } @Override public void onFailure(HttpToolResponse val) { log.warn("zabbix sever returned failure code: {}", val.getResponseCode()); } @Override public void onException(Exception exception) { log.warn("zabbix exception registering host", exception); } @Override public String toString() { return super.toString() + "[" + getDescription() + "]"; } @Override public String getDescription() { return "Zabbix rest poll"; } }; // Schedule registration attempt once per second getPoller().scheduleAtFixedRate(registerJob, registrationHandler, 1000l); // TODO make configurable // Create a polling job for each Zabbix metric for (final ZabbixPollConfig<?> config : polls) { Callable<HttpToolResponse> pollJob = new Callable<HttpToolResponse>() { @Override public HttpToolResponse call() throws Exception { if (registered.get()) { if (log.isTraceEnabled()) log.trace("zabbix polling {} for {}", entity, config); byte[] body = JSON_ITEM_GET .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{hostId}}", entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID)) .replace("{{itemKey}}", config.getItemKey()) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } else { throw new IllegalStateException("zabbix agent not yet registered"); } } }; // Schedule the Zabbix polling job AttributePollHandler<? super HttpToolResponse> pollHandler = new AttributePollHandler<HttpToolResponse>( config, entity, this); long minPeriod = Integer.MAX_VALUE; // TODO make configurable if (config.getPeriod() > 0) minPeriod = Math.min(minPeriod, config.getPeriod()); getPoller().scheduleAtFixedRate(pollJob, pollHandler, minPeriod); } }
From source file:brooklyn.entity.mesos.task.marathon.MarathonTaskImpl.java
public Integer getSshPort() { String sensorValue = sensors().get(DockerAttributes.DOCKER_MAPPED_SSH_PORT); if (sensorValue != null) { HostAndPort target = HostAndPort.fromString(sensorValue); return target.getPort(); } else {//from w w w .ja va 2s .c o m Integer sshPort = getRunningEntity().config().get(SshMachineLocation.SSH_PORT); return Optional.fromNullable(sshPort).or(22); } }
From source file:org.excalibur.core.ssh.jsch.JschSshClient.java
public JschSshClient(HostAndPort socket, LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector, BackoffLimitedRetryHandler backoffLimitedRetryHandler) { this.host = checkNotNull(socket, "host").getHostText(); this.user = checkNotNull(loginCredentials, "credentials for %s", host).getUser(); checkArgument(socket.getPort() > 0, "ssh port must be greater than zero" + socket.getPort()); checkArgument(socket.getPort() < 65535, "ssh port must be less than 65535" + socket.getPort()); this.backoffLimitedRetryHandler = checkNotNull(backoffLimitedRetryHandler, "backoffLimitedRetryHandler"); connection = SshConnection.builder().hostAndPort(socket).loginCredentials(loginCredentials) .connectionTimeout(timeout).agentConnector(agentConnector).build(); checkNotNull(connection);/* w ww . ja v a2 s .c o m*/ }
From source file:com.yahoo.omid.tsoclient.TSOClientImpl.java
@Override public void nodeChanged() throws Exception { LOG.debug("CurrentTSO ZNode changed"); HostAndPort hp = getCurrentTSOHostAndPortFoundInZK(); setTSOAddress(hp.getHostText(), hp.getPort()); fsm.sendEvent(new ErrorEvent(new NewTSOException())); }
From source file:org.wso2.mb.platform.tests.clustering.DifferentRateSubscriberTestCase.java
/** * Runs a receiver and a consumer that publishes messages with a delay. * * @param destinationName The destination name * @param consumerDelay The delay in which the consumer sends messages * @param publisherDelay The delay in which the publisher received messages * @param consumerBrokerAddress The amqp connection string for consumer * @param publisherBrokerAddress The amqp connection string for publisher * @param messageCount Number of message to send and receive * @throws org.wso2.mb.integration.common.clients.exceptions.AndesClientConfigurationException * @throws NamingException//from w w w . jav a 2s . co m * @throws JMSException * @throws IOException */ private void runDifferentRateSubscriberTestCase(String destinationName, long consumerDelay, long publisherDelay, long messageCount, HostAndPort consumerBrokerAddress, HostAndPort publisherBrokerAddress) throws AndesClientConfigurationException, NamingException, JMSException, IOException, AndesClientException, DataAccessUtilException, InterruptedException { // Number of messages expected long expectedCount = messageCount; // Number of messages send long sendCount = messageCount; long printDivider = 10L; // Creating a consumer client configuration AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration( consumerBrokerAddress.getHostText(), consumerBrokerAddress.getPort(), ExchangeType.QUEUE, destinationName); consumerConfig.setMaximumMessagesToReceived(expectedCount * 2); consumerConfig.setPrintsPerMessageCount(expectedCount / printDivider); consumerConfig.setRunningDelay(consumerDelay); // Creating a publisher client configuration AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration( publisherBrokerAddress.getHostText(), publisherBrokerAddress.getPort(), ExchangeType.QUEUE, destinationName); publisherConfig.setNumberOfMessagesToSend(sendCount); publisherConfig.setPrintsPerMessageCount(sendCount / printDivider); publisherConfig.setRunningDelay(publisherDelay); // Creating client AndesClient consumerClient = new AndesClient(consumerConfig, true); consumerClient.startClient(); AndesClient publisherClient = new AndesClient(publisherConfig, true); publisherClient.startClient(); AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME); // Wait until consumers are closed Thread.sleep(AndesClientConstants.DEFAULT_RUN_TIME); // Evaluating Assert.assertEquals(publisherClient.getSentMessageCount(), sendCount, "Message sending failed."); Assert.assertEquals(consumerClient.getReceivedMessageCount(), expectedCount, "Message receiving failed."); // Evaluate messages left in database Assert.assertEquals(dataAccessUtil.getMessageCountForQueue(destinationName), 0, "Messages left in database"); // Evaluate slots left in database Assert.assertEquals(dataAccessUtil.getAssignedSlotCountForQueue(destinationName), 0, "Slots left in database"); }
From source file:org.hillview.dataset.remoting.HillviewServer.java
public HillviewServer(final HostAndPort listenAddress, final IDataSet initialDataset) throws IOException { this.initialDataset = initialDataset; this.listenAddress = listenAddress; this.memoizedCommands = new MemoizedResults(); this.server = NettyServerBuilder .forAddress(new InetSocketAddress(listenAddress.getHost(), listenAddress.getPort())) .executor(executorService).workerEventLoopGroup(workerElg).bossEventLoopGroup(bossElg) .addService(this).maxMessageSize(MAX_MESSAGE_SIZE).build().start(); this.dataSets = CacheBuilder.<Integer, IDataSet>newBuilder() .expireAfterAccess(EXPIRE_TIME_IN_HOURS, TimeUnit.HOURS) .removalListener((RemovalListener<Integer, IDataSet>) removalNotification -> HillviewLogger.instance .info("Removing reference to dataset", "{0}: {1}", removalNotification.getKey(), removalNotification.getValue().toString())) .build();/*from w w w . ja v a2 s . c o m*/ this.toUnsubscribe = CacheBuilder.<UUID, Boolean>newBuilder() .expireAfterAccess(EXPIRE_TIME_IN_HOURS, TimeUnit.HOURS).build(); }