This is an automated email from the ASF dual-hosted git repository.
cziegeler pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/felix-dev.git
The following commit(s) were added to refs/heads/master by this push:
new 7c0747c FELIX-6449 : Make all health checks immediate
7c0747c is described below
commit 7c0747c021b18d69ced515f740497606fb2dc219
Author: Carsten Ziegeler <[email protected]>
AuthorDate: Fri Aug 20 16:05:03 2021 +0200
FELIX-6449 : Make all health checks immediate
---
healthcheck/generalchecks/pom.xml | 50 ++++---
.../hc/generalchecks/BundlesStartedCheck.java | 20 +--
.../apache/felix/hc/generalchecks/CpuCheck.java | 2 +-
.../felix/hc/generalchecks/DiskSpaceCheck.java | 2 +-
.../hc/generalchecks/FrameworkStartCheck.java | 4 +-
.../felix/hc/generalchecks/HttpRequestsCheck.java | 147 +++++++++++----------
.../felix/hc/generalchecks/JmxAttributeCheck.java | 30 ++---
.../apache/felix/hc/generalchecks/MemoryCheck.java | 4 +-
.../hc/generalchecks/ScriptedHealthCheck.java | 14 +-
.../felix/hc/generalchecks/ServicesCheck.java | 2 +-
.../felix/hc/generalchecks/ThreadUsageCheck.java | 6 +-
11 files changed, 152 insertions(+), 129 deletions(-)
diff --git a/healthcheck/generalchecks/pom.xml
b/healthcheck/generalchecks/pom.xml
index 0660b58..7fac4ef 100644
--- a/healthcheck/generalchecks/pom.xml
+++ b/healthcheck/generalchecks/pom.xml
@@ -68,7 +68,7 @@
<plugin>
<groupId>biz.aQute.bnd</groupId>
<artifactId>bnd-maven-plugin</artifactId>
- <version>4.1.0</version>
+ <version>5.3.0</version>
<executions>
<execution>
<goals>
@@ -78,27 +78,27 @@
</executions>
</plugin>
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <configuration>
- <archive>
-
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
- </archive>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <version>4.1.0</version>
+ <groupId>biz.aQute.bnd</groupId>
+ <artifactId>bnd-baseline-maven-plugin</artifactId>
+ <version>5.3.0</version>
<executions>
<execution>
- <id>baseline</id>
+ <id>bnd-baseline</id>
<goals>
<goal>baseline</goal>
</goals>
</execution>
</executions>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <configuration>
+ <archive>
+
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
+ </archive>
+ </configuration>
+ </plugin>
</plugins>
<pluginManagement>
@@ -136,8 +136,26 @@
</dependency>
<dependency>
<groupId>org.osgi</groupId>
- <artifactId>osgi.annotation</artifactId>
- <version>6.0.1</version>
+ <artifactId>org.osgi.annotation.versioning</artifactId>
+ <version>1.1.1</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.annotation.bundle</artifactId>
+ <version>1.0.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.component.annotations</artifactId>
+ <version>1.4.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.metatype.annotations</artifactId>
+ <version>1.4.0</version>
<scope>provided</scope>
</dependency>
diff --git
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/BundlesStartedCheck.java
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/BundlesStartedCheck.java
index 60d6788..c33c49f 100644
---
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/BundlesStartedCheck.java
+++
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/BundlesStartedCheck.java
@@ -37,7 +37,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@HealthCheckService(name = BundlesStartedCheck.HC_NAME)
-@Component(configurationPolicy = ConfigurationPolicy.REQUIRE)
+@Component(configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true)
@Designate(ocd = BundlesStartedCheck.Config.class, factory = true)
public class BundlesStartedCheck implements HealthCheck {
@@ -62,7 +62,7 @@ public class BundlesStartedCheck implements HealthCheck {
@AttributeDefinition(name = "CRITICAL for inactive bundles",
description = "By default inactive bundles produce warnings, if this is set to
true inactive bundles produce a CRITICAL result")
boolean useCriticalForInactive() default false;
-
+
@AttributeDefinition
String webconsole_configurationFactory_nameHint() default "Bundles
started includes: {includesRegex} excludes: {excludesRegex}";
}
@@ -81,21 +81,21 @@ public class BundlesStartedCheck implements HealthCheck {
LOG.debug("Activated bundles started HC for includesRegex={}
excludesRegex={}% useCriticalForInactive={}", includesRegex, excludesRegex,
useCriticalForInactive);
}
-
+
@Override
public Result execute() {
FormattingResultLog log = new FormattingResultLog();
Bundle[] bundles = this.bundleContext.getBundles();
log.debug("Framwork has {} bundles in total", bundles.length);
-
+
int countExcluded = 0;
int relevantBundlesCount = 0;
int inctiveCount = 0;
for (Bundle bundle : bundles) {
String bundleSymbolicName = bundle.getSymbolicName();
int bundleState = bundle.getState();
-
+
if(!includesRegex.matcher(bundleSymbolicName).matches()) {
LOG.debug("Bundle {} not matched by {}", bundleSymbolicName,
includesRegex);
continue;
@@ -107,13 +107,13 @@ public class BundlesStartedCheck implements HealthCheck {
continue;
}
relevantBundlesCount++;
-
+
boolean bundleIsLogged = false;
if (bundleState != Bundle.ACTIVE) {
// support lazy activation
(https://www.osgi.org/developer/design/lazy-start/)
if (bundleState == Bundle.STARTING &&
isLazyActivation(bundle)) {
LOG.debug("Ignoring lazily activated bundle {}",
bundleSymbolicName);
- } else if (StringUtils.isNotBlank((String)
bundle.getHeaders().get(Constants.FRAGMENT_HOST))) {
+ } else if
(StringUtils.isNotBlank(bundle.getHeaders().get(Constants.FRAGMENT_HOST))) {
LOG.debug("Ignoring bundle fragment: {}",
bundleSymbolicName);
} else {
String msg = "Inactive bundle {} {}: {}";
@@ -132,7 +132,7 @@ public class BundlesStartedCheck implements HealthCheck {
log.debug("Bundle {} {}: {}", bundle.getBundleId(),
bundleSymbolicName, getStateLabel(bundleState));
}
}
-
+
String baseMsg = relevantBundlesCount+"
bundles"+(!includesRegex.pattern().equals(".*")?" for pattern
"+includesRegex.pattern(): "");
String excludedMsg = countExcluded > 0 ? " (" + countExcluded + "
excluded via pattern "+excludesRegex.pattern()+")" : "";
if (inctiveCount > 0) {
@@ -147,7 +147,7 @@ public class BundlesStartedCheck implements HealthCheck {
private static boolean isLazyActivation(Bundle b) {
return
Constants.ACTIVATION_LAZY.equals(b.getHeaders().get(Constants.BUNDLE_ACTIVATIONPOLICY));
}
-
+
private static String getStateLabel(int state) {
switch(state) {
case Bundle.UNINSTALLED: return "UNINSTALLED";
@@ -158,6 +158,6 @@ public class BundlesStartedCheck implements HealthCheck {
case Bundle.ACTIVE: return "ACTIVE";
default: return ""+state;
}
- }
+ }
}
diff --git
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/CpuCheck.java
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/CpuCheck.java
index 9353a61..798f103 100644
---
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/CpuCheck.java
+++
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/CpuCheck.java
@@ -42,7 +42,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@HealthCheckService(name = CpuCheck.HC_NAME)
-@Component(configurationPolicy = ConfigurationPolicy.REQUIRE)
+@Component(configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true)
@Designate(ocd = CpuCheck.Config.class, factory = false)
public class CpuCheck implements HealthCheck {
diff --git
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/DiskSpaceCheck.java
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/DiskSpaceCheck.java
index 89e049f..4967e7a 100644
---
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/DiskSpaceCheck.java
+++
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/DiskSpaceCheck.java
@@ -37,7 +37,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@HealthCheckService(name = DiskSpaceCheck.HC_NAME)
-@Component(configurationPolicy = ConfigurationPolicy.REQUIRE)
+@Component(configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true)
@Designate(ocd = DiskSpaceCheck.Config.class, factory = true)
public class DiskSpaceCheck implements HealthCheck {
diff --git
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/FrameworkStartCheck.java
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/FrameworkStartCheck.java
index 6f21eeb..dc773f6 100644
---
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/FrameworkStartCheck.java
+++
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/FrameworkStartCheck.java
@@ -48,7 +48,7 @@ public class FrameworkStartCheck implements HealthCheck {
public static final String PROP_START_LEVEL_BEGINNING =
"org.osgi.framework.startlevel.beginning";
-
+
@ObjectClassDefinition(name = "Health Check: " + HC_NAME, description =
"System ready that waits for the system bundle to be active")
public @interface Config {
@@ -100,7 +100,7 @@ public class FrameworkStartCheck implements HealthCheck {
}
return tStartLevel;
}
-
+
private String getBeginningStartLevel() {
String beginningStartLevel =
StringUtils.defaultIfBlank(bundleContext.getProperty(PROP_START_LEVEL_BEGINNING),
"<unknown>");
diff --git
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/HttpRequestsCheck.java
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/HttpRequestsCheck.java
index 9729f56..a8bf277 100644
---
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/HttpRequestsCheck.java
+++
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/HttpRequestsCheck.java
@@ -69,7 +69,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@HealthCheckService(name = HttpRequestsCheck.HC_NAME)
-@Component(configurationPolicy = ConfigurationPolicy.REQUIRE)
+@Component(configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true)
@Designate(ocd = HttpRequestsCheck.Config.class, factory = true)
public class HttpRequestsCheck implements HealthCheck {
@@ -103,20 +103,20 @@ public class HttpRequestsCheck implements HealthCheck {
"-X HEAD --data \"{....}\"
http://www.example.com/path/to/data.json => 303",
"--proxy proxyhost:2000 /path/example-timing-important.html => 200
&& TIME < 2000"
};
-
+
@AttributeDefinition(name = "Connect Timeout", description = "Default
connect timeout in ms. Can be overwritten per request with option
--connect-timeout (in sec)")
int connectTimeoutInMs() default 7000;
@AttributeDefinition(name = "Read Timeout", description = "Default
read timeout in ms. Can be overwritten with per request option -m or --max-time
(in sec)")
int readTimeoutInMs() default 7000;
-
+
@AttributeDefinition(name = "Status for failed request constraint",
description = "Status to fail with if the constraint check fails")
Result.Status statusForFailedContraint() default Result.Status.WARN;
@AttributeDefinition(name = "Run in parallel", description = "Run
requests in parallel (only active if more than one request spec is configured)")
boolean runInParallel() default true;
-
-
+
+
@AttributeDefinition
String webconsole_configurationFactory_nameHint() default "{hc.name}:
{requests}";
@@ -127,11 +127,11 @@ public class HttpRequestsCheck implements HealthCheck {
private int readTimeoutInMs;
private Result.Status statusForFailedContraint;
private boolean runInParallel;
-
+
private String defaultBaseUrl = null;
private FormattingResultLog configErrors;
-
+
@Activate
protected void activate(BundleContext bundleContext, Config config) {
this.requestSpecs = getRequestSpecs(config.requests());
@@ -141,7 +141,7 @@ public class HttpRequestsCheck implements HealthCheck {
this.runInParallel = config.runInParallel() && requestSpecs.size() > 1;
setupDefaultBaseUrl(bundleContext);
-
+
LOG.debug("Default BaseURL: {}", defaultBaseUrl);
LOG.debug("Activated Requests HC: {}", requestSpecs);
}
@@ -161,18 +161,18 @@ public class HttpRequestsCheck implements HealthCheck {
public Result execute() {
FormattingResultLog overallLog = new FormattingResultLog();
-
+
// take over config errors
for(ResultLog.Entry entry: configErrors) {
overallLog.add(entry);
}
-
+
// execute requests
Stream<RequestSpec> requestSpecsStream = runInParallel ?
requestSpecs.parallelStream() : requestSpecs.stream();
List<FormattingResultLog> logsForEachRequest = requestSpecsStream
.map(requestSpec -> requestSpec.check(defaultBaseUrl,
connectTimeoutInMs, readTimeoutInMs, statusForFailedContraint,
requestSpecs.size()>1))
.collect(Collectors.toList());
-
+
// aggregate logs never in parallel
logsForEachRequest.stream().forEach( l -> stream(l.spliterator(),
false).forEach(e -> overallLog.add(e)));
@@ -181,9 +181,9 @@ public class HttpRequestsCheck implements HealthCheck {
}
private List<RequestSpec> getRequestSpecs(String[] requestSpecStrArr) {
-
+
configErrors = new FormattingResultLog();
-
+
List<RequestSpec> requestSpecs = new ArrayList<RequestSpec>();
for(String requestSpecStr: requestSpecStrArr) {
try {
@@ -197,29 +197,29 @@ public class HttpRequestsCheck implements HealthCheck {
}
return requestSpecs;
}
-
+
static class RequestSpec {
-
+
private static final String HEADER_AUTHORIZATION = "Authorization";
-
+
String method = "GET";
String url;
Map<String,String> headers = new HashMap<String,String>();
String data = null;
-
+
String user;
-
+
Integer connectTimeoutInMs;
Integer readTimeoutInMs;
-
+
Proxy proxy;
-
+
List<ResponseCheck> responseChecks = new ArrayList<ResponseCheck>();
-
+
RequestSpec(String requestSpecStr) throws ParseException,
URISyntaxException {
-
+
String[] requestSpecBits = requestSpecStr.split(" *=> *", 2);
-
+
String requestInfo = requestSpecBits[0];
parseCurlLikeRequestInfo(requestInfo);
@@ -232,7 +232,7 @@ public class HttpRequestsCheck implements HealthCheck {
}
private void parseResponseAssertion(String responseAssertions) {
-
+
String[] responseAssertionArr = responseAssertions.split(" +&& +");
for(String clause: responseAssertionArr) {
if(isNumeric(clause)) {
@@ -271,9 +271,9 @@ public class HttpRequestsCheck implements HealthCheck {
options.addOption(null, "connect-timeout", true, "");
options.addOption("m", "max-time", true, "");
options.addOption("x", "proxy", true, "");
-
- String[] args = splitArgsRespectingQuotes(requestInfo);
-
+
+ String[] args = splitArgsRespectingQuotes(requestInfo);
+
CommandLine line = parser.parse(options, args);
if (line.hasOption("header")) {
@@ -295,7 +295,7 @@ public class HttpRequestsCheck implements HealthCheck {
byte[] encodedUserAndPw =
Base64.getEncoder().encode(userAndPw.getBytes());
headers.put(HEADER_AUTHORIZATION, "Basic "+new
String(encodedUserAndPw));
}
-
+
if (line.hasOption("connect-timeout")) {
connectTimeoutInMs =
Integer.valueOf(line.getOptionValue("connect-timeout")) * 1000;
}
@@ -341,12 +341,12 @@ public class HttpRequestsCheck implements HealthCheck {
}
public FormattingResultLog check(String defaultBaseUrl, int
connectTimeoutInMs, int readTimeoutInMs, Result.Status
statusForFailedContraint, boolean showTiming) {
-
+
FormattingResultLog log = new FormattingResultLog();
String urlWithUser = user!=null ? user + " @ " + url: url;
log.debug("Checking {}", urlWithUser);
log.debug(" configured headers {}", headers.keySet());
-
+
Response response = null;
try {
response = performRequest(defaultBaseUrl, urlWithUser,
connectTimeoutInMs, readTimeoutInMs, log);
@@ -354,7 +354,7 @@ public class HttpRequestsCheck implements HealthCheck {
// request generally failed
log.add(new ResultLog.Entry(statusForFailedContraint,
urlWithUser+": "+ e.getMessage(), e));
}
-
+
if(response != null) {
List<String> resultBits = new ArrayList<String>();
boolean hasFailed = false;
@@ -382,7 +382,7 @@ public class HttpRequestsCheck implements HealthCheck {
} else {
effectiveUrl = new URL(url);
}
-
+
conn = openConnection(connectTimeoutInMs, readTimeoutInMs,
effectiveUrl, log);
response = readResponse(conn, log);
@@ -400,16 +400,16 @@ public class HttpRequestsCheck implements HealthCheck {
conn = (HttpURLConnection) (proxy==null ?
effectiveUrl.openConnection() : effectiveUrl.openConnection(proxy));
conn.setInstanceFollowRedirects(false);
conn.setUseCaches(false);
-
+
int effectiveConnectTimeout = this.connectTimeoutInMs !=null ?
this.connectTimeoutInMs : defaultConnectTimeoutInMs;
int effectiveReadTimeout = this.readTimeoutInMs !=null ?
this.readTimeoutInMs : defaultReadTimeoutInMs;
log.debug("connectTimeout={}ms readTimeout={}ms",
effectiveConnectTimeout, effectiveReadTimeout);
- conn.setConnectTimeout(effectiveConnectTimeout);
+ conn.setConnectTimeout(effectiveConnectTimeout);
conn.setReadTimeout(effectiveReadTimeout);
- conn.setRequestMethod(method);
+ conn.setRequestMethod(method);
for(Entry<String,String> header: headers.entrySet()) {
- conn.setRequestProperty(header.getKey(), header.getValue());
+ conn.setRequestProperty(header.getKey(), header.getValue());
}
if(data != null) {
conn.setDoOutput(true);
@@ -423,14 +423,14 @@ public class HttpRequestsCheck implements HealthCheck {
}
private Response readResponse(HttpURLConnection conn,
FormattingResultLog log) throws IOException {
-
+
long startTime = System.currentTimeMillis();
-
+
int actualResponseCode = conn.getResponseCode();
String actualResponseMessage = conn.getResponseMessage();
log.debug("Result: {} {}", actualResponseCode,
actualResponseMessage);
Map<String, List<String>> responseHeaders = conn.getHeaderFields();
-
+
StringWriter responseEntityWriter = new StringWriter();
try (BufferedReader in = new BufferedReader(new
InputStreamReader(conn.getInputStream()))) {
String inputLine;
@@ -440,13 +440,13 @@ public class HttpRequestsCheck implements HealthCheck {
} catch(IOException e) {
log.debug("Could not get response entity: {}", e.getMessage());
}
-
+
long requestDurationInMs = System.currentTimeMillis() - startTime;
Response response = new Response(actualResponseCode,
actualResponseMessage, responseHeaders, responseEntityWriter.toString(),
requestDurationInMs);
-
+
return response;
}
-
+
}
static class Response {
@@ -455,7 +455,7 @@ public class HttpRequestsCheck implements HealthCheck {
final Map<String, List<String>> actualResponseHeaders;
final String actualResponseEntity;
final long requestDurationInMs;
-
+
public Response(int actualResponseCode, String actualResponseMessage,
Map<String, List<String>> actualResponseHeaders,
String actualResponseEntity, long requestDurationInMs) {
super();
@@ -466,31 +466,32 @@ public class HttpRequestsCheck implements HealthCheck {
this.requestDurationInMs = requestDurationInMs;
}
}
-
+
static interface ResponseCheck {
-
+
class ResponseCheckResult {
final boolean contraintFailed;
final String message;
-
+
ResponseCheckResult(boolean contraintFailed, String message) {
this.contraintFailed = contraintFailed;
this.message = message;
}
-
+
}
-
+
ResponseCheckResult checkResponse(Response response,
FormattingResultLog log);
}
static class ResponseCodeCheck implements ResponseCheck {
-
+
private final int expectedResponseCode;
-
+
public ResponseCodeCheck(int expectedResponseCode) {
this.expectedResponseCode = expectedResponseCode;
}
+ @Override
public ResponseCheckResult checkResponse(Response response,
FormattingResultLog log) {
if(expectedResponseCode != response.actualResponseCode) {
@@ -500,38 +501,40 @@ public class HttpRequestsCheck implements HealthCheck {
}
}
}
-
+
static class ResponseTimeCheck implements ResponseCheck {
final static String TIME = "TIME ";
-
+
private final String timeConstraint;
-
+
private final SimpleConstraintChecker simpleConstraintChecker = new
SimpleConstraintChecker();
-
+
public ResponseTimeCheck(String timeConstraint) {
this.timeConstraint = timeConstraint;
}
+ @Override
public ResponseCheckResult checkResponse(Response response,
FormattingResultLog log) {
log.debug("Checking request time [{}ms] for constraint [{}]",
response.requestDurationInMs, timeConstraint);
- if(!simpleConstraintChecker.check((Long)
response.requestDurationInMs, timeConstraint)) {
+ if(!simpleConstraintChecker.check(response.requestDurationInMs,
timeConstraint)) {
return new ResponseCheckResult(true, "time
["+response.requestDurationInMs + "ms] does not fulfil constraint
["+timeConstraint+"]");
} else {
return new ResponseCheckResult(false, "time
["+response.requestDurationInMs + "ms] fulfils constraint
["+timeConstraint+"]");
}
}
}
-
+
static class ResponseEntityRegExCheck implements ResponseCheck {
final static String MATCHES = "MATCHES ";
-
+
private final Pattern expectedResponseEntityRegEx;
-
+
public ResponseEntityRegExCheck(Pattern expectedResponseEntityRegEx) {
this.expectedResponseEntityRegEx = expectedResponseEntityRegEx;
}
-
+
+ @Override
public ResponseCheckResult checkResponse(Response response,
FormattingResultLog log) {
if(!expectedResponseEntityRegEx.matcher(response.actualResponseEntity).find()) {
return new ResponseCheckResult(true, "response does not match
["+expectedResponseEntityRegEx+']');
@@ -543,24 +546,25 @@ public class HttpRequestsCheck implements HealthCheck {
static class ResponseHeaderCheck implements ResponseCheck {
final static String HEADER = "HEADER ";
-
+
private final String headerName;
private final String headerConstraint;
-
+
private final SimpleConstraintChecker simpleConstraintChecker = new
SimpleConstraintChecker();
-
+
public ResponseHeaderCheck(String headerExpression) {
String[] headerCheckBits = headerExpression.split(" +", 2);
this.headerName = headerCheckBits[0];
this.headerConstraint = headerCheckBits[1];
}
-
+
+ @Override
public ResponseCheckResult checkResponse(Response response,
FormattingResultLog log) {
List<String> headerValues =
response.actualResponseHeaders.get(headerName);
String headerVal = headerValues!=null && !headerValues.isEmpty() ?
headerValues.get(0): null;
-
+
log.debug("Checking {} with value [{}] for constraint [{}]",
headerName, headerVal, headerConstraint);
if(!simpleConstraintChecker.check(headerVal, headerConstraint)) {
return new ResponseCheckResult(true, "header ["+headerName+"]
has value ["+headerVal+"] which does not fulfil constraint
["+headerConstraint+"]");
@@ -572,19 +576,20 @@ public class HttpRequestsCheck implements HealthCheck {
static class JsonPropertyCheck implements ResponseCheck {
final static String JSON = "JSON ";
-
+
private final String jsonPropertyPath;
private final String jsonPropertyConstraint;
-
+
private final SimpleConstraintChecker simpleConstraintChecker = new
SimpleConstraintChecker();
-
+
public JsonPropertyCheck(String jsonExpression) {
String[] jsonCheckBits = jsonExpression.split(" +", 2);
this.jsonPropertyPath = jsonCheckBits[0];
this.jsonPropertyConstraint = jsonCheckBits[1];
}
-
+
+ @Override
public ResponseCheckResult checkResponse(Response response,
FormattingResultLog log) {
JSONParser jsonParser;
@@ -595,9 +600,9 @@ public class HttpRequestsCheck implements HealthCheck {
}
Object propertyVal = getJsonProperty(jsonParser, jsonPropertyPath);
-
+
log.debug("JSON property [{}] has value [{}]", jsonPropertyPath,
propertyVal);
-
+
log.debug("Checking [{}] with value [{}] for constraint [{}]",
jsonPropertyPath, propertyVal, jsonPropertyConstraint);
if(!simpleConstraintChecker.check(propertyVal,
jsonPropertyConstraint)) {
return new ResponseCheckResult(true, "json
["+jsonPropertyPath+"] has value ["+propertyVal+"] which does not fulfil
constraint ["+jsonPropertyConstraint+"]");
@@ -639,5 +644,5 @@ public class HttpRequestsCheck implements HealthCheck {
return currentObject;
}
}
-
+
}
diff --git
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/JmxAttributeCheck.java
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/JmxAttributeCheck.java
index ba545bc..5acd11f 100644
---
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/JmxAttributeCheck.java
+++
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/JmxAttributeCheck.java
@@ -41,7 +41,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** {@link HealthCheck} that checks one (or multiple) JMX attribute(s). */
-@Component(service = HealthCheck.class, configurationPolicy =
ConfigurationPolicy.REQUIRE)
+@Component(service = HealthCheck.class, configurationPolicy =
ConfigurationPolicy.REQUIRE, immediate = true)
@Designate(ocd = JmxAttributeCheck.Config.class, factory = true)
public class JmxAttributeCheck implements HealthCheck {
@@ -66,24 +66,24 @@ public class JmxAttributeCheck implements HealthCheck {
@AttributeDefinition(name = "Attribute Name", description = "The name
of the MBean attribute to check against the constraint.")
String attribute_name() default "";
-
+
@AttributeDefinition(name = "Attribute Constraint", description =
"Constraint on the MBean attribute value. If simple value, uses equals. For
strings constraints like 'CONTAINS mystr', 'STARTS_WITH mystr' or 'ENDS_WITH
mystr' can be used, for numbers constraints like '> 4', '= 7', '< 9' or
'between 3 and 7' work.")
String attribute_value_constraint() default "";
@AttributeDefinition(name = "Status for failed constraint",
description = "Status to fail with if the constraint check fails")
Result.Status statusForFailedContraint() default Result.Status.WARN;
-
+
@AttributeDefinition
String webconsole_configurationFactory_nameHint() default "JMX MBean
{mbean.name} Attribute '{attribute.name}' constraint:
{attribute.value.constraint}";
}
private List<AttributeConstraintConfig> attributeConstraintConfigs;
-
+
@Activate
protected void activate(final Config config, final Map<String,Object>
rawConfig) {
statusForFailedContraint = config.statusForFailedContraint();
attributeConstraintConfigs = AttributeConstraintConfig.load(config,
rawConfig);
-
+
if(LOG.isDebugEnabled()) {
LOG.debug("Activated JMX Attribute HC with
statusForFailedContraint={} and attribute constraint config(s):",
statusForFailedContraint);
for (AttributeConstraintConfig attributeConstraintConfig :
attributeConstraintConfigs) {
@@ -125,10 +125,10 @@ public class JmxAttributeCheck implements HealthCheck {
resultLog.healthCheckError("JMX attribute check failed: {}",
attributeConstraintConfig, e);
}
}
-
-
+
+
private static class AttributeConstraintConfig {
-
+
public static final String PROP_MBEAN = "mbean";
public static final String PROP_ATTRIBUTE = "attribute";
@@ -137,7 +137,7 @@ public class JmxAttributeCheck implements HealthCheck {
private static List<AttributeConstraintConfig> load(final Config
config, final Map<String, Object> rawConfig) {
List<AttributeConstraintConfig> attributeConstraintConfigs = new
ArrayList<AttributeConstraintConfig>();
-
+
// first attribute via metatype
attributeConstraintConfigs.add(new
AttributeConstraintConfig(config.mbean_name(),
config.attribute_name(),config.attribute_value_constraint()));
@@ -153,16 +153,16 @@ public class JmxAttributeCheck implements HealthCheck {
private static String getAttributePropName(int attributeCounter) {
return PROP_ATTRIBUTE + attributeCounter + SUFFIX_NAME;
}
-
+
private static boolean hasConfig(Map<String,Object> rawConfig, int
attributeCounter) {
return
rawConfig.containsKey(getAttributePropName(attributeCounter));
}
-
+
final String mbeanName;
-
+
final String attributeName;
final String attributeValueConstraint;
-
+
public AttributeConstraintConfig(String mbeanName, String
attributeName, String attributeValueConstraint) {
this.mbeanName = mbeanName;
this.attributeName = attributeName;
@@ -180,10 +180,10 @@ public class JmxAttributeCheck implements HealthCheck {
throw new IllegalArgumentException("Invalid JmxAttributeCheck
config for property "+mbeanName+" -> "+propNameAttribute+": "+toString());
}
}
-
+
@Override
public String toString() {
return "JMX attribute "+mbeanName+" -> '"+attributeName+"':
Constraint: "+attributeValueConstraint;
- };
+ }
}
}
diff --git
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/MemoryCheck.java
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/MemoryCheck.java
index 0c57f12..a7b55bc 100644
---
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/MemoryCheck.java
+++
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/MemoryCheck.java
@@ -34,7 +34,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@HealthCheckService(name = MemoryCheck.HC_NAME)
-@Component(configurationPolicy = ConfigurationPolicy.REQUIRE)
+@Component(configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true)
@Designate(ocd = MemoryCheck.Config.class, factory = false)
public class MemoryCheck implements HealthCheck {
@@ -81,7 +81,7 @@ public class MemoryCheck implements HealthCheck {
long usedMemory = currentlyAllocatedByJVM - freeMemory;
log.debug("Used memory: {}", bytesHumanReadable(usedMemory));
long maxMemoryAvailableToJVM = runtime.maxMemory();
-
+
double memoryUsedPercentage = ((double) usedMemory /
maxMemoryAvailableToJVM * 100d);
Result.Status status =
diff --git
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ScriptedHealthCheck.java
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ScriptedHealthCheck.java
index 49a7bb6..73f0868 100644
---
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ScriptedHealthCheck.java
+++
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ScriptedHealthCheck.java
@@ -38,7 +38,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** {@link HealthCheck} that runs an arbitrary script. */
-@Component(service = HealthCheck.class, configurationPolicy =
ConfigurationPolicy.REQUIRE)
+@Component(service = HealthCheck.class, configurationPolicy =
ConfigurationPolicy.REQUIRE, immediate = true)
@Designate(ocd = ScriptedHealthCheck.Config.class, factory = true)
public class ScriptedHealthCheck implements HealthCheck {
@@ -67,7 +67,7 @@ public class ScriptedHealthCheck implements HealthCheck {
@AttributeDefinition(name = "Script", description = "The script itself
(either use 'script' or 'scriptUrl').")
String script() default "log.info('ok'); log.warn('not so good');
log.critical('bad') // minimal example";
-
+
@AttributeDefinition(name = "Script Url", description = "Url to the
script to be used as alternative source (either use 'script' or 'scriptUrl').")
String scriptUrl() default "";
@@ -78,9 +78,9 @@ public class ScriptedHealthCheck implements HealthCheck {
private String language;
private String script;
private String scriptUrl;
-
+
private BundleContext bundleContext;
-
+
@Reference(policyOption = ReferencePolicyOption.GREEDY)
private ScriptEnginesTracker scriptEnginesTracker;
@@ -92,7 +92,7 @@ public class ScriptedHealthCheck implements HealthCheck {
this.language = config.language().toLowerCase();
this.script = config.script();
this.scriptUrl = config.scriptUrl();
-
+
if(StringUtils.isNotBlank(script) &&
StringUtils.isNotBlank(scriptUrl)) {
LOG.info("Both 'script' and 'scriptUrl' (=()) are configured,
ignoring 'scriptUrl'", scriptUrl);
scriptUrl = null;
@@ -105,8 +105,8 @@ public class ScriptedHealthCheck implements HealthCheck {
@Override
public Result execute() {
FormattingResultLog log = new FormattingResultLog();
-
-
+
+
boolean urlIsUsed = StringUtils.isBlank(script);
String scriptToExecute = urlIsUsed ?
scriptHelper.getFileContents(scriptUrl): script;
log.info("Executing script {} ({} lines)...", (urlIsUsed?scriptUrl:"
as configured"), scriptToExecute.split("\n").length);
diff --git
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ServicesCheck.java
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ServicesCheck.java
index efb8598..1406e74 100644
---
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ServicesCheck.java
+++
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ServicesCheck.java
@@ -53,7 +53,7 @@ import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@Component(configurationPolicy = ConfigurationPolicy.REQUIRE)
+@Component(configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true)
@HealthCheckService(name = ServicesCheck.HC_NAME, tags = {
ServicesCheck.HC_DEFAULT_TAG })
@Designate(ocd = ServicesCheck.Config.class, factory = true)
public class ServicesCheck implements HealthCheck {
diff --git
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ThreadUsageCheck.java
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ThreadUsageCheck.java
index 3827147..35c10f7 100644
---
a/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ThreadUsageCheck.java
+++
b/healthcheck/generalchecks/src/main/java/org/apache/felix/hc/generalchecks/ThreadUsageCheck.java
@@ -41,7 +41,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@HealthCheckService(name = ThreadUsageCheck.HC_NAME)
-@Component(configurationPolicy = ConfigurationPolicy.REQUIRE)
+@Component(configurationPolicy = ConfigurationPolicy.REQUIRE, immediate = true)
@Designate(ocd = ThreadUsageCheck.Config.class, factory = false)
public class ThreadUsageCheck implements HealthCheck {
@@ -94,11 +94,11 @@ public class ThreadUsageCheck implements HealthCheck {
for (int i = 0; i < threadTimeInfos.size(); i++) {
ThreadTimeInfo threadInfo = threadTimeInfos.get(i);
- float cpuTimePercentage = ((float) threadInfo.getCpuTime() /
((float) samplePeriodInMs * 1000000)) * 100f;
+ float cpuTimePercentage = (threadInfo.getCpuTime() / ((float)
samplePeriodInMs * 1000000)) * 100f;
totalCpuTimePercentage += cpuTimePercentage;
String msg = String.format("%4.1f", cpuTimePercentage) + "%
used by thread \"" + threadInfo.name + "\"";
-
+
// usually just shows the 3 busiest threads. For the case more
threads take more than 15% CPU time, up to 10 threads are shown.
// use hcDebug=true to show all threads
if (i < 3 || (i < 10 && cpuTimePercentage > 15)) {