public static HttpPollConfig<Void> forMultiple() { return new HttpPollConfig<Void>(PollConfig.NO_SENSOR); }
public static <T> HttpPollConfig<T> forSensor(AttributeSensor<T> sensor) { return new HttpPollConfig<T>(sensor); }
protected void initialize() { checkState(getConfig(URL) != null ^ getConfig(URL_SENSOR) != null, "Must set exactly one of url or urlSensor: url=%s; urlSensor=%s", getConfig(URL), getConfig(URL_SENSOR)); checkState(getConfig(URL_SENSOR) != null || getConfig(URL_POST_PROCESSING) == null, "Must not set urlPostProcessing without urlSensor"); Object configValue = getConfig(URL); if (configValue != null) { url.set(configValue.toString()); } httpFeed = HttpFeed.builder() .entity(entity) .period(getConfig(PERIOD)) .baseUri(Suppliers.compose(Urls.stringToUriFunction(), AtomicReferences.supplier(url))) .poll(new HttpPollConfig<Double>(REQUEST_LATENCY_IN_SECONDS_MOST_RECENT) .onResult(MathFunctions.divide(HttpValueFunctions.latency(), 1000.0d)) .setOnException(null)) .suspended() .build(); if (getUniqueTag()==null) uniqueTag = JavaClassNames.simpleClassName(getClass())+":"+ (getConfig(URL)!=null ? getConfig(URL) : getConfig(URL_SENSOR)); }
@Override protected void connectSensors() { super.connectSensors(); ConfigToAttributes.apply(this); HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getHttpPort()); String nodeJsUrl = String.format("http://%s:%d", accessible.getHostText(), accessible.getPort()); if (isHttpMonitoringEnabled()) { LOG.info("Connecting to {}", nodeJsUrl); httpFeed = HttpFeed.builder() .entity(this) .baseUri(nodeJsUrl) .poll(new HttpPollConfig<Boolean>(SERVICE_UP) .suppressDuplicates(true) .suburl(getConfig(NodeJsWebAppService.SERVICE_UP_PATH)) .checkSuccess(Predicates.alwaysTrue()) .onSuccess(HttpValueFunctions.responseCodeEquals(200)) .setOnException(false)) .build(); } else { connectServiceUpIsRunning(); } WebAppServiceMethods.connectWebAppServerPolicies(this); }
@Override public void connectSensors() { super.connectSensors(); connectServiceUpIsRunning(); HostAndPort hostAndPort = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, sensors().get(DOCKER_REGISTRY_PORT)); sensors().set(Attributes.MAIN_URI, URI.create("https://" + hostAndPort + "/v2")); httpFeed = HttpFeed.builder() .entity(this) .period(Duration.seconds(3)) .baseUri(getAttribute(Attributes.MAIN_URI)) .poll(new HttpPollConfig<Boolean>(Attributes.SERVICE_UP) .onSuccess(Functions.constant(true)) .onFailureOrException(Functions.constant(false))) .poll(new HttpPollConfig<List<String>>(DOCKER_REGISTRY_CATALOG) .suburl("/_catalog") .onSuccess(Functionals.chain( HttpValueFunctions.jsonContents(), JsonFunctions.walk("repositories"), JsonFunctions.forEach(JsonFunctions.cast(String.class)))) .onFailureOrException(Functions.constant(Collections.<String>emptyList()))) .build(); }
private void connectAuthenticatedSensors() { hostsHttpFeed = HttpFeed.builder() .entity(this) .period(1000, TimeUnit.MILLISECONDS) .baseUri(String.format("%s/api/v1/hosts", ambariUri)) .credentials(usernamePasswordCredentials.getUserName(), usernamePasswordCredentials.getPassword()) .header(HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(usernamePasswordCredentials)) .poll(new HttpPollConfig<List<String>>(REGISTERED_HOSTS) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), getHosts())) .onFailureOrException(Functions.<List<String>>constant(ImmutableList.<String>of()))) .build(); clusterHttpFeed = HttpFeed.builder() .entity(this) .period(1000, TimeUnit.MILLISECONDS) .baseUri(String.format("%s/api/v1/clusters/%s/requests/%d", ambariUri, getConfig(AmbariCluster.CLUSTER_NAME), 1)) .credentials(usernamePasswordCredentials.getUserName(), usernamePasswordCredentials.getPassword()) .header(HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(usernamePasswordCredentials)) .poll(new HttpPollConfig<String>(CLUSTER_STATE) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), getRequestState())) .onFailureOrException(Functions.<String>constant(null))) .build(); }
@Test(groups = {"Integration"}) public void testPollsAndParsesHttpGetResponseWithSsl() throws Exception { httpService = new HttpService(PortRanges.fromString("9000+"), true).start(); URI baseUrl = new URI(httpService.getUrl()); assertEquals(baseUrl.getScheme(), "https", "baseUrl="+baseUrl); feed = HttpFeed.builder() .entity(entity) .baseUri(baseUrl) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .onSuccess(HttpValueFunctions.responseCode())) .poll(new HttpPollConfig<String>(SENSOR_STRING) .period(100) .onSuccess(HttpValueFunctions.stringContentsFunction())) .build(); EntityAsserts.assertAttributeEqualsEventually(entity, SENSOR_INT, 200); Asserts.succeedsEventually(new Runnable() { @Override public void run() { String val = entity.getAttribute(SENSOR_STRING); assertTrue(val != null && val.contains("Hello, World"), "val="+val); }}); }
@Test public void testPollsAndParsesHttpPostResponse() throws Exception { feed = HttpFeed.builder() .entity(entity) .baseUrl(baseUrl) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .method("post") .period(100) .onSuccess(HttpValueFunctions.responseCode())) .poll(new HttpPollConfig<String>(SENSOR_STRING) .method("post") .period(100) .onSuccess(HttpValueFunctions.stringContentsFunction())) .build(); assertSensorEventually(SENSOR_INT, 200, TIMEOUT_MS); assertSensorEventually(SENSOR_STRING, "{\"foo\":\"myfoo\"}", TIMEOUT_MS); }
@Test public void testPreemptiveBasicAuthFailsIfNoCredentials() throws Exception { try { feed = HttpFeed.builder() .entity(entity) .baseUrl(new URL("http://shouldNeverBeCalled.org")) .preemptiveBasicAuth(true) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .onSuccess(HttpValueFunctions.responseCode()) .onException(Functions.constant(-1))) .build(); Asserts.shouldHaveFailedPreviously(); } catch (IllegalArgumentException e) { Asserts.expectedFailureContains(e, "Must not enable preemptiveBasicAuth when there are no credentials"); } }
@Test public void testSetsConnectionTimeout() throws Exception { feed = HttpFeed.builder() .entity(entity) .baseUrl(baseUrl) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .connectionTimeout(Duration.TEN_SECONDS) .socketTimeout(Duration.TEN_SECONDS) .onSuccess(HttpValueFunctions.responseCode())) .build(); assertSensorEventually(SENSOR_INT, 200, TIMEOUT_MS); }
@Test public void testFailsIfUsernameNull() throws Exception { try { feed = HttpFeed.builder() .entity(entity) .baseUrl(new URL("http://shouldNeverBeCalled.org")) .credentials(null, "Pa55w0rd") .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .onSuccess(HttpValueFunctions.responseCode()) .onException(Functions.constant(-1))) .build(); Asserts.shouldHaveFailedPreviously(); } catch (IllegalArgumentException e) { Asserts.expectedFailureContainsIgnoreCase(e, "may not be null"); } }
@Test public void testPollsAndParsesHttpErrorResponseLocal() throws Exception { int unboundPort = Networking.nextAvailablePort(10000); feed = HttpFeed.builder() .entity(entity) .baseUri("http://localhost:" + unboundPort + "/path/should/not/exist") .poll(new HttpPollConfig<String>(SENSOR_STRING) .onSuccess(Functions.constant("success")) .onFailure(Functions.constant("failure")) .onException(Functions.constant("error"))) .build(); assertSensorEventually(SENSOR_STRING, "error", TIMEOUT_MS); }
protected void runPollsAndParsesHttpGetResponseWithBasicAuthentication(boolean preemptiveBasicAuth) throws Exception { final String username = "brooklyn"; final String password = "hunter2"; httpService = new HttpService(PortRanges.fromString("9000+")) .basicAuthentication(username, password) .start(); URI baseUrl = new URI(httpService.getUrl()); assertEquals(baseUrl.getScheme(), "http", "baseUrl="+baseUrl); feed = HttpFeed.builder() .entity(entity) .baseUri(baseUrl) .credentials(username, password) .preemptiveBasicAuth(preemptiveBasicAuth) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .onSuccess(HttpValueFunctions.responseCode())) .poll(new HttpPollConfig<String>(SENSOR_STRING) .period(100) .onSuccess(HttpValueFunctions.stringContentsFunction())) .build(); EntityAsserts.assertAttributeEqualsEventually(entity, SENSOR_INT, 200); Asserts.succeedsEventually(new Runnable() { @Override public void run() { String val = entity.getAttribute(SENSOR_STRING); assertTrue(val != null && val.contains("Hello, World"), "val="+val); }}); }
@Test public void testPreemptiveBasicAuthFailsIfUserContainsColon() throws Exception { try { feed = HttpFeed.builder() .entity(entity) .baseUrl(new URL("http://shouldNeverBeCalled.org")) .credentials("userWith:colon", "Pa55w0rd") .preemptiveBasicAuth(true) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .onSuccess(HttpValueFunctions.responseCode()) .onException(Functions.constant(-1))) .build(); Asserts.shouldHaveFailedPreviously(); } catch (IllegalArgumentException e) { Asserts.expectedFailureContains(e, "must not contain colon"); } }
protected void runPreemptiveBasicAuth(String username, String password) throws Exception { feed = HttpFeed.builder() .entity(entity) .baseUrl(server.getUrl("/")) .credentials(username, password) .preemptiveBasicAuth(true) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .onSuccess(HttpValueFunctions.responseCode()) .onException(Functions.constant(-1))) .build(); EntityAsserts.assertAttributeEqualsEventually(entity, SENSOR_INT, 200); RecordedRequest req = server.takeRequest(); String headerVal = req.getHeader("Authorization"); String expectedVal = getBasicAuthHeaderVal(username, password); assertEquals(headerVal, expectedVal); }
@Test public void testUsesFailureHandlerOn4xx() throws Exception { if (server != null) server.shutdown(); server = BetterMockWebServer.newInstanceLocalhost(); for (int i = 0; i < 100; i++) { server.enqueue(new MockResponse() .setResponseCode(401) .setBody("Unauthorised")); } server.play(); feed = HttpFeed.builder() .entity(entity) .baseUrl(server.getUrl("/")) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .onSuccess(HttpValueFunctions.responseCode()) .onFailure(HttpValueFunctions.responseCode())) .poll(new HttpPollConfig<String>(SENSOR_STRING) .period(100) .onSuccess(HttpValueFunctions.stringContentsFunction()) .onFailure(Functions.constant("Failed"))) .build(); assertSensorEventually(SENSOR_INT, 401, TIMEOUT_MS); assertSensorEventually(SENSOR_STRING, "Failed", TIMEOUT_MS); server.shutdown(); }
@Test public void testSetsConnectionTimeoutWhenServerDisconnects() throws Exception { if (server != null) server.shutdown(); server = BetterMockWebServer.newInstanceLocalhost(); for (int i = 0; i < 100; i++) { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); } server.play(); baseUrl = server.getUrl("/"); feed = HttpFeed.builder() .entity(entity) .baseUrl(baseUrl) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .connectionTimeout(Duration.TEN_SECONDS) .socketTimeout(Duration.TEN_SECONDS) .onSuccess(HttpValueFunctions.responseCode()) .onException(Functions.constant(-1))) .build(); assertSensorEventually(SENSOR_INT, -1, TIMEOUT_MS); }
@Override public void connectSensors() { super.connectSensors(); ConfigToAttributes.apply(this); // "up" is defined as returning a valid HTTP response from nginx (including a 404 etc) httpFeed = addFeed(HttpFeed.builder() .uniqueTag("nginx-poll") .entity(this) .period(getConfig(HTTP_POLL_PERIOD)) .baseUri(new UrlInferencer()) .poll(new HttpPollConfig<String>(SENSOR_STRING) .onResult(HttpValueFunctions.stringContentsFunction()) .setOnException("Failed") .suppressDuplicates(true)) .build()); }
@Test public void testUsesExceptionHandlerOn4xxAndNoFailureHandler() throws Exception { if (server != null) server.shutdown(); server = BetterMockWebServer.newInstanceLocalhost(); for (int i = 0; i < 100; i++) { server.enqueue(new MockResponse() .setResponseCode(401) .setBody("Unauthorised")); } server.play(); feed = HttpFeed.builder() .entity(entity) .baseUrl(server.getUrl("/")) .poll(new HttpPollConfig<Integer>(SENSOR_INT) .period(100) .onSuccess(HttpValueFunctions.responseCode()) .onException(Functions.constant(-1))) .build(); assertSensorEventually(SENSOR_INT, -1, TIMEOUT_MS); server.shutdown(); }
protected void connectSensors() { URI webConsoleUri = getManagementContext().getManagementNodeUri().orNull(); sensors().set(WEB_CONSOLE_URI, webConsoleUri); if (webConsoleUri != null) { httpFeed = HttpFeed.builder() .entity(this) .period(200) .baseUri(webConsoleUri) .credentialsIfNotNull(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD)) .poll(new HttpPollConfig<Boolean>(SERVICE_UP) .onSuccess(HttpValueFunctions.responseCodeEquals(200)) .setOnFailureOrException(false)) .build(); } else { sensors().set(SERVICE_UP, true); } }