Adding health reports to microservices

duration 20 minutes

Prerequisites:

Explore how to report and check the health of a microservice with MicroProfile Health.

What you’ll learn

You will learn how to use MicroProfile Health to report the health status of microservices and take appropriate actions based on this report.

MicroProfile Health allows services to report their health, and it publishes the overall health status to a defined endpoint. A service reports UP if it is available and reports DOWN if it is unavailable. MicroProfile Health reports an individual service status at the endpoint and indicates the overall status as UP if all the services are UP. A service orchestrator can then use the health statuses to make decisions.

A service checks its own health by performing necessary self-checks and then reports its overall status by implementing the API provided by MicroProfile Health. A self-check can be a check on anything that the service needs, such as a dependency, a successful connection to an endpoint, a system property, a database connection, or the availability of required resources. MicroProfile offers checks for startup, liveness, and readiness.

You will add startup, liveness, and readiness checks to the system and inventory services, that are provided for you, and implement what is necessary to report health status by using MicroProfile Health.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-microprofile-health.git
cd guide-microprofile-health

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Before you begin, make sure you have all the necessary prerequisites.

Try what you’ll build

The finish directory in the root of this guide contains the finished application. Give it a try before you proceed.

To try out the application, first go to the finish directory and run the following Maven goal to build the application and deploy it to Open Liberty:

cd finish
mvn liberty:run

After you see the following message, your application server is ready:

The defaultServer server is ready to run a smarter planet.

The system and inventory services can be found at the following URLs:

Visit the http://localhost:9080/health URL to see the overall health status of the application, as well as the aggregated data of the startup, liveness and readiness checks. Three checks show the state of the system service, and the other three checks show the state of the inventory service. As you might expect, all services are in the UP state, and the overall health status of the application is in the UP state.

Access the /health/started endpoint by visiting the http://localhost:9080/health/started URL to view the data from the startup health checks. You can also access the /health/live endpoint by visiting the http://localhost:9080/health/live URL to view the data from the liveness health checks. Similarly, access the /health/ready endpoint by visiting the http://localhost:9080/health/ready URL to view the data from the readiness health checks.

After you are finished checking out the application, stop the Open Liberty server by pressing CTRL+C in the command-line session where you ran the server. Alternatively, you can run the liberty:stop goal from the finish directory in another shell session:

mvn liberty:stop

Adding health checks to microservices

Navigate to the start directory to begin.

When you run Open Liberty in development mode, known as dev mode, the server listens for file changes and automatically recompiles and deploys your updates whenever you save a new change. Run the following goal to start Open Liberty in dev mode:

mvn liberty:dev

After you see the following message, your application server in dev mode is ready:

**************************************************************
*    Liberty is running in dev mode.

Dev mode holds your command-line session to listen for file changes. Open another command-line session to continue, or open the project in your editor.

A health report will be generated automatically for all services that enable MicroProfile Health. The mpHealth feature has already been enabled for you in the src/main/liberty/config/server.xml file.

All services must provide an implementation of the HealthCheck interface, which is used to verify their health. MicroProfile Health offers health checks for startup, liveness, and readiness. A startup check allows applications to define startup probes that are used for initial verification of the application before the Liveness probe takes over. For example, a startup check might check which applications require additional startup time on their first initialization. A liveness check allows third-party services to determine whether a microservice is running. If the liveness check fails, the application can be terminated. For example, a liveness check might fail if the application runs out of memory. A readiness check allows third-party services, such as Kubernetes, to determine whether a microservice is ready to process requests. For example, a readiness check might check dependencies, such as database connections.

server.xml

 1<server description="Sample Liberty server">
 2
 3  <featureManager>
 4    <feature>restfulWS-3.0</feature>
 5    <feature>jsonb-2.0</feature>
 6    <feature>jsonp-2.0</feature>
 7    <feature>cdi-3.0</feature>
 8    <feature>mpConfig-3.0</feature>
 9    <feature>mpRestClient-3.0</feature>
10    <!-- tag::mpHealth[] -->
11    <feature>mpHealth-4.0</feature>
12    <!-- end::mpHealth[] -->
13  </featureManager>
14
15  <variable name="default.http.port" defaultValue="9080"/>
16  <variable name="default.https.port" defaultValue="9443"/>
17
18  <httpEndpoint host="*" httpPort="${default.http.port}"
19    httpsPort="${default.https.port}" id="defaultHttpEndpoint"/>
20
21  <webApplication location="guide-microprofile-health.war" contextRoot="/"/>
22</server>

Adding health checks to the system service

Create the SystemStartupCheck class.
src/main/java/io/openliberty/guides/system/SystemStartupCheck.java

SystemStartupCheck.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13// tag::SystemStartupCheck[]
14package io.openliberty.guides.system;
15
16import java.lang.management.ManagementFactory;
17import com.sun.management.OperatingSystemMXBean;
18import jakarta.enterprise.context.ApplicationScoped;
19import org.eclipse.microprofile.health.Startup;
20import org.eclipse.microprofile.health.HealthCheck;
21import org.eclipse.microprofile.health.HealthCheckResponse;
22
23// tag::Startup[]
24@Startup
25// end::Startup[]
26@ApplicationScoped
27public class SystemStartupCheck implements HealthCheck {
28
29    @Override
30    public HealthCheckResponse call() {
31        OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean)
32        ManagementFactory.getOperatingSystemMXBean();
33        double cpuUsed = bean.getSystemCpuLoad();
34        String cpuUsage = String.valueOf(cpuUsed);
35        return HealthCheckResponse.named(SystemResource.class
36                                            .getSimpleName() + " Startup Check")
37                                            .status(cpuUsed < 0.95).build();
38    }
39}
40
41// end::SystemStartupCheck[]

The @Startup annotation indicates that this class is a startup health check procedure. In this case, you are checking the cpu usage. If more than 95% of the cpu is being used, a status of DOWN is returned.

Create the SystemLivenessCheck class.
src/main/java/io/openliberty/guides/system/SystemLivenessCheck.java

SystemLivenessCheck.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13// tag::SystemLivenessCheck[]
14package io.openliberty.guides.system;
15
16import java.lang.management.ManagementFactory;
17import java.lang.management.MemoryMXBean;
18
19import jakarta.enterprise.context.ApplicationScoped;
20import org.eclipse.microprofile.health.Liveness;
21import org.eclipse.microprofile.health.HealthCheck;
22import org.eclipse.microprofile.health.HealthCheckResponse;
23
24// tag::Liveness[]
25@Liveness
26// end::Liveness[]
27@ApplicationScoped
28public class SystemLivenessCheck implements HealthCheck {
29
30  @Override
31  public HealthCheckResponse call() {
32    MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
33    long memUsed = memBean.getHeapMemoryUsage().getUsed();
34    long memMax = memBean.getHeapMemoryUsage().getMax();
35
36    return HealthCheckResponse.named(
37      SystemResource.class.getSimpleName() + " Liveness Check")
38                              .status(memUsed < memMax * 0.9).build();
39  }
40}
41// end::SystemLivenessCheck[]

The @Liveness annotation indicates that this class is a liveness health check procedure. In this case, you are checking the heap memory usage. If more than 90% of the maximum memory is being used, a status of DOWN is returned.

Create the SystemReadinessCheck class.
src/main/java/io/openliberty/guides/system/SystemReadinessCheck.java

SystemReadinessCheck.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13// tag::SystemReadinessCheck[]
14package io.openliberty.guides.system;
15
16import jakarta.enterprise.context.ApplicationScoped;
17import org.eclipse.microprofile.health.Readiness;
18import org.eclipse.microprofile.health.HealthCheck;
19import org.eclipse.microprofile.health.HealthCheckResponse;
20
21// tag::Readiness[]
22@Readiness
23// end::Readiness[]
24// tag::ApplicationScoped[]
25@ApplicationScoped
26// end::ApplicationScoped[]
27public class SystemReadinessCheck implements HealthCheck {
28
29  private static final String READINESS_CHECK = SystemResource.class.getSimpleName()
30                                               + " Readiness Check";
31  @Override
32// tag::healthCheckResponse[]
33  public HealthCheckResponse call() {
34    // tag::defaultServer[]
35    if (!System.getProperty("wlp.server.name").equals("defaultServer")) {
36    // end::defaultServer[]
37      // tag::HealthCheckResponse-DOWN[]
38      // tag::HealthCheckResponse-named[]
39      return HealthCheckResponse.down(READINESS_CHECK);
40      // end::HealthCheckResponse-named[]
41      // end::HealthCheckResponse-DOWN[]
42    }
43    // tag::HealthCheckResponse-UP[]
44    return HealthCheckResponse.up(READINESS_CHECK);
45    // end::HealthCheckResponse-UP[]
46  }
47// end::healthCheckResponse[]
48}
49// end::SystemReadinessCheck[]

The @Readiness annotation indicates that this class is a readiness health check procedure. By pairing this annotation with the ApplicationScoped context from the Contexts and Dependency Injections API, the bean is discovered automatically when the http://localhost:9080/health endpoint receives a request.

The call() method is used to return the health status of a particular service. In this case, you are checking if the server name is defaultServer and returning UP if it is, and DOWN otherwise. This example is a very simple implementation of the call() method. In a real environment, you would orchestrate more meaningful health checks.

Adding health checks to the inventory service

Create the InventoryStartupCheck class.
src/main/java/io/openliberty/guides/inventory/InventoryStartupCheck.java

InventoryStartupCheck.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13// tag::InventoryStartupCheck[]
14package io.openliberty.guides.inventory;
15
16import java.lang.management.ManagementFactory;
17import com.sun.management.OperatingSystemMXBean;
18import jakarta.enterprise.context.ApplicationScoped;
19import org.eclipse.microprofile.health.Startup;
20import org.eclipse.microprofile.health.HealthCheck;
21import org.eclipse.microprofile.health.HealthCheckResponse;
22
23// tag::Startup[]
24@Startup
25// end::Startup[]
26@ApplicationScoped
27public class InventoryStartupCheck implements HealthCheck {
28
29    @Override
30    public HealthCheckResponse call() {
31        OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean)
32        ManagementFactory.getOperatingSystemMXBean();
33        double cpuUsed = bean.getSystemCpuLoad();
34        String cpuUsage = String.valueOf(cpuUsed);
35        return HealthCheckResponse.named(InventoryResource.class
36                                            .getSimpleName() + " Startup Check")
37                                            .status(cpuUsed < 0.95).build();
38    }
39}
40
41// end::InventoryStartupCheck[]

This startup check verifies that the cpu usage is below 95%. If more than 95% of the cpu is being used, a status of DOWN is returned.

Create the InventoryLivenessCheck class.
src/main/java/io/openliberty/guides/inventory/InventoryLivenessCheck.java

InventoryLivenessCheck.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13// tag::InventoryLivenessCheck[]
14package io.openliberty.guides.inventory;
15
16import jakarta.enterprise.context.ApplicationScoped;
17
18import java.lang.management.MemoryMXBean;
19import java.lang.management.ManagementFactory;
20
21import org.eclipse.microprofile.health.Liveness;
22
23import org.eclipse.microprofile.health.HealthCheck;
24import org.eclipse.microprofile.health.HealthCheckResponse;
25
26@Liveness
27@ApplicationScoped
28public class InventoryLivenessCheck implements HealthCheck {
29  @Override
30  public HealthCheckResponse call() {
31      MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
32      long memUsed = memBean.getHeapMemoryUsage().getUsed();
33      long memMax = memBean.getHeapMemoryUsage().getMax();
34
35      return HealthCheckResponse.named(
36        InventoryResource.class.getSimpleName() + " Liveness Check")
37                                .status(memUsed < memMax * 0.9).build();
38  }
39}
40// end::InventoryLivenessCheck[]

As with the system liveness check, you are checking the heap memory usage. If more than 90% of the maximum memory is being used, a DOWN status is returned.

Create the InventoryReadinessCheck class.
src/main/java/io/openliberty/guides/inventory/InventoryReadinessCheck.java

InventoryReadinessCheck.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2018, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13// tag::InventoryReadinessCheck[]
14package io.openliberty.guides.inventory;
15
16import jakarta.enterprise.context.ApplicationScoped;
17import jakarta.inject.Inject;
18import jakarta.ws.rs.client.Client;
19import jakarta.ws.rs.client.ClientBuilder;
20import jakarta.ws.rs.core.MediaType;
21import jakarta.ws.rs.core.Response;
22import org.eclipse.microprofile.health.Readiness;
23import org.eclipse.microprofile.health.HealthCheck;
24import org.eclipse.microprofile.health.HealthCheckResponse;
25
26@Readiness
27@ApplicationScoped
28public class InventoryReadinessCheck implements HealthCheck {
29
30  private static final String READINESS_CHECK = InventoryResource.class.getSimpleName()
31                                               + " Readiness Check";
32  @Inject
33  // tag::inventoryConfig[]
34  InventoryConfig config;
35  // end::inventoryConfig[]
36
37  // tag::isHealthy[]
38  public boolean isHealthy() {
39    if (config.isInMaintenance()) {
40      return false;
41    }
42    try {
43      String url = InventoryUtils.buildUrl("http", "localhost", config.getPortNumber(),
44          "/system/properties");
45      Client client = ClientBuilder.newClient();
46      // tag::getRequest[]
47      Response response = client.target(url).request(MediaType.APPLICATION_JSON).get();
48      // end::getRequest[]
49      if (response.getStatus() != 200) {
50        return false;
51      }
52      return true;
53    } catch (Exception e) {
54      return false;
55    }
56  }
57  // end::isHealthy[]
58
59  @Override
60  public HealthCheckResponse call() {
61    if (!isHealthy()) {
62      return HealthCheckResponse
63          .down(READINESS_CHECK);
64    }
65    return HealthCheckResponse
66        .up(READINESS_CHECK);
67  }
68
69}
70// end::InventoryReadinessCheck[]

In the isHealthy() method, you report the inventory service as not ready if the service is in maintenance or if its dependant service is unavailable.

For simplicity, the custom io_openliberty_guides_inventory_inMaintenance MicroProfile Config property, which is defined in the resources/CustomConfigSource.json file, indicates whether the service is in maintenance. This file was already created for you.

Moreover, the readiness health check procedure makes an HTTP GET request to the system service and checks its status. If the request is successful, the inventory service is healthy and ready because its dependant service is available. Otherwise, the inventory service is not ready and an unhealthy readiness status is returned.

If you are curious about the injected inventoryConfig object or if you want to learn more about MicroProfile Config, see Configuring microservices.

CustomConfigSource.json

1{
2    "config_ordinal":700,
3    "io_openliberty_guides_inventory_inMaintenance":false
4}

Running the application

You started the Open Liberty server in dev mode at the beginning of the guide, so all the changes were automatically picked up.

While the server is running, navigate to the http://localhost:9080/health URL to find the aggregated startup, liveness, and readiness health reports on the two services.

You can also navigate to the http://localhost:9080/health/started URL to view the startup health report, to the http://localhost:9080/health/live URL to view the liveness health report or the http://localhost:9080/health/ready URL to view the readiness health report.

Put the inventory service in maintenance by setting the io_openliberty_guides_inventory_inMaintenance property to true in the CustomConfigSource.json file.

Replace the CustomConfigSource.json file.
resources/CustomConfigSource.json

CustomConfigSource.json

1{
2    "config_ordinal":700,
3    "io_openliberty_guides_inventory_inMaintenance":true
4}

Because this configuration file is picked up dynamically, simply refresh the http://localhost:9080/health URL to see that the state of the inventory service changed to DOWN. The overall state of the application also changed to DOWN as a result. Go to the http://localhost:9080/inventory/systems URL to verify that the inventory service is indeed in maintenance. Set the io_openliberty_guides_inventory_inMaintenance property back to false after you are done.

Testing health checks

You will implement several test methods to validate the health of the system and inventory services.

Create the HealthIT class.
src/test/java/it/io/openliberty/guides/health/HealthIT.java

HealthIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13// tag::HealthIT[]
 14package it.io.openliberty.guides.health;
 15
 16import static org.junit.jupiter.api.Assertions.assertEquals;
 17
 18import java.beans.Transient;
 19import java.util.HashMap;
 20
 21import jakarta.json.JsonArray;
 22
 23import org.junit.jupiter.api.AfterEach;
 24import org.junit.jupiter.api.BeforeEach;
 25import org.junit.jupiter.api.Test;
 26
 27public class HealthIT {
 28
 29  private JsonArray servicesStates;
 30  private static HashMap<String, String> endpointData;
 31
 32  private String HEALTH_ENDPOINT = "health";
 33  private String READINESS_ENDPOINT = "health/ready";
 34  private String LIVENES_ENDPOINT = "health/live";
 35  private String STARTUP_ENDPOINT = "health/started";
 36
 37  @BeforeEach
 38  public void setup() {
 39    endpointData = new HashMap<String, String>();
 40  }
 41
 42  @Test
 43  // tag::testStartup[]
 44  public void testStartup() {
 45    endpointData.put("InventoryResource Startup Check", "UP");
 46    endpointData.put("SystemResource Startup Check", "UP");
 47
 48    servicesStates = HealthITUtil.connectToHealthEnpoint(200, STARTUP_ENDPOINT);
 49    checkStates(endpointData, servicesStates);
 50  }
 51  // end::testStartup[]
 52
 53  @Test
 54  // tag::testLiveness[]
 55  public void testLiveness() {
 56    endpointData.put("SystemResource Liveness Check", "UP");
 57    endpointData.put("InventoryResource Liveness Check", "UP");
 58
 59    servicesStates = HealthITUtil.connectToHealthEnpoint(200, LIVENES_ENDPOINT);
 60    checkStates(endpointData, servicesStates);
 61  }
 62  // end::testLiveness[]
 63
 64  @Test
 65  // tag::testReadiness[]
 66  public void testReadiness() {
 67    endpointData.put("SystemResource Readiness Check", "UP");
 68    endpointData.put("InventoryResource Readiness Check", "UP");
 69
 70    servicesStates = HealthITUtil.connectToHealthEnpoint(200, READINESS_ENDPOINT);
 71    checkStates(endpointData, servicesStates);
 72  }
 73  // end::testReadiness[]
 74
 75  @Test
 76  // tag::testHealth[]
 77  public void testHealth() {
 78    endpointData.put("SystemResource Startup Check", "UP");
 79    endpointData.put("SystemResource Liveness Check", "UP");
 80    endpointData.put("SystemResource Readiness Check", "UP");
 81    endpointData.put("InventoryResource Startup Check", "UP");
 82    endpointData.put("InventoryResource Liveness Check", "UP");
 83    endpointData.put("InventoryResource Readiness Check", "UP");
 84
 85    servicesStates = HealthITUtil.connectToHealthEnpoint(200, HEALTH_ENDPOINT);
 86    checkStates(endpointData, servicesStates);
 87
 88    endpointData.put("InventoryResource Readiness Check", "DOWN");
 89    HealthITUtil.changeInventoryProperty(HealthITUtil.INV_MAINTENANCE_FALSE,
 90        HealthITUtil.INV_MAINTENANCE_TRUE);
 91    servicesStates = HealthITUtil.connectToHealthEnpoint(503, HEALTH_ENDPOINT);
 92    checkStates(endpointData, servicesStates);
 93  }
 94  // end::testHealth[]
 95
 96  private void checkStates(HashMap<String, String> testData, JsonArray servStates) {
 97    testData.forEach((service, expectedState) -> {
 98      assertEquals(expectedState, HealthITUtil.getActualState(service, servStates),
 99          "The state of " + service + " service is not matching.");
100    });
101  }
102
103  @AfterEach
104  public void teardown() {
105    HealthITUtil.cleanUp();
106  }
107
108}
109// end::HealthIT[]

Let’s break down the test cases:

  • The testStartup() test case compares the generated health report for the startup checks with the actual status of the services.

  • The testLiveness() test case compares the generated health report for the liveness checks with the actual status of the services.

  • The testReadiness() test case compares the generated health report for the readiness checks with the actual status of the services.

  • The testHealth() test case compares the generated health report with the actual status of the services. This test also puts the inventory service in maintenance by setting the io_openliberty_guides_inventory_inMaintenance property to true and comparing the generated health report with the actual status of the services.

A few more tests were included to verify the basic functionality of the system and inventory services. They can be found under the src/test/java/it/io/openliberty/guides/inventory/InventoryEndpointIT.java and src/test/java/it/io/openliberty/guides/system/SystemEndpointIT.java files. If a test failure occurs, then you might have introduced a bug into the code. These tests run automatically as a part of the integration test suite.

CustomConfigSource.json

1{
2    "config_ordinal":700,
3    "io_openliberty_guides_inventory_inMaintenance":false
4}

InventoryEndpointIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2017, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License v1.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-v10.html
  8 *
  9 * Contributors:
 10 *     IBM Corporation - Initial implementation
 11 *******************************************************************************/
 12// end::copyright[]
 13// tag::testClass[]
 14package it.io.openliberty.guides.inventory;
 15
 16import static org.junit.jupiter.api.Assertions.assertEquals;
 17import static org.junit.jupiter.api.Assertions.assertTrue;
 18
 19import jakarta.json.JsonArray;
 20import jakarta.json.JsonObject;
 21import jakarta.ws.rs.client.Client;
 22import jakarta.ws.rs.client.ClientBuilder;
 23import jakarta.ws.rs.core.MediaType;
 24import jakarta.ws.rs.core.Response;
 25
 26import org.junit.jupiter.api.AfterEach;
 27import org.junit.jupiter.api.BeforeAll;
 28import org.junit.jupiter.api.BeforeEach;
 29import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
 30import org.junit.jupiter.api.Order;
 31import org.junit.jupiter.api.Test;
 32import org.junit.jupiter.api.TestMethodOrder;
 33
 34@TestMethodOrder(OrderAnnotation.class)
 35public class InventoryEndpointIT {
 36
 37  private static String port;
 38  private static String baseUrl;
 39
 40  private Client client;
 41
 42  private final String SYSTEM_PROPERTIES = "system/properties";
 43  private final String INVENTORY_SYSTEMS = "inventory/systems";
 44
 45  @BeforeAll
 46  public static void oneTimeSetup() {
 47    port = System.getProperty("default.http.port");
 48    baseUrl = "http://localhost:" + port + "/";
 49  }
 50
 51  @BeforeEach
 52  public void setup() {
 53    client = ClientBuilder.newClient();
 54  }
 55
 56  @AfterEach
 57  public void teardown() {
 58    client.close();
 59  }
 60
 61  // tag::tests[]
 62  @Test
 63  @Order(1)
 64  // tag::testHostRegistration[]
 65  public void testHostRegistration() {
 66    this.visitLocalhost();
 67
 68    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
 69    this.assertResponse(baseUrl, response);
 70
 71    JsonObject obj = response.readEntity(JsonObject.class);
 72
 73    JsonArray systems = obj.getJsonArray("systems");
 74
 75    boolean localhostExists = false;
 76    for (int n = 0; n < systems.size(); n++) {
 77      localhostExists = systems.getJsonObject(n).get("hostname").toString()
 78          .contains("localhost");
 79      if (localhostExists) {
 80        break;
 81      }
 82    }
 83    assertTrue(localhostExists, "A host was registered, but it was not localhost");
 84
 85    response.close();
 86  }
 87  // end::testHostRegistration[]
 88
 89  @Test
 90  @Order(2)
 91  // tag::testSystemPropertiesMatch[]
 92  public void testSystemPropertiesMatch() {
 93    Response invResponse = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
 94    Response sysResponse = this.getResponse(baseUrl + SYSTEM_PROPERTIES);
 95
 96    this.assertResponse(baseUrl, invResponse);
 97    this.assertResponse(baseUrl, sysResponse);
 98
 99    JsonObject jsonFromInventory = (JsonObject) invResponse.readEntity(JsonObject.class)
100                                                           .getJsonArray("systems")
101                                                           .getJsonObject(0)
102                                                           .get("properties");
103
104    JsonObject jsonFromSystem = sysResponse.readEntity(JsonObject.class);
105
106    String osNameFromInventory = jsonFromInventory.getString("os.name");
107    String osNameFromSystem = jsonFromSystem.getString("os.name");
108    this.assertProperty("os.name", "localhost", osNameFromSystem,
109                        osNameFromInventory);
110
111    String userNameFromInventory = jsonFromInventory.getString("user.name");
112    String userNameFromSystem = jsonFromSystem.getString("user.name");
113    this.assertProperty("user.name", "localhost", userNameFromSystem,
114                        userNameFromInventory);
115
116    invResponse.close();
117    sysResponse.close();
118  }
119  // end::testSystemPropertiesMatch[]
120
121  @Test
122  @Order(3)
123  // tag::testUnknownHost[]
124  public void testUnknownHost() {
125    Response response = this.getResponse(baseUrl + INVENTORY_SYSTEMS);
126    this.assertResponse(baseUrl, response);
127
128    Response badResponse = client.target(baseUrl + INVENTORY_SYSTEMS + "/"
129        + "badhostname").request(MediaType.APPLICATION_JSON).get();
130
131    String obj = badResponse.readEntity(String.class);
132
133    boolean isError = obj.contains("error");
134    assertTrue(isError,
135        "badhostname is not a valid host but it didn't raise an error");
136
137    response.close();
138    badResponse.close();
139  }
140
141  // end::testUnknownHost[]
142  // end::tests[]
143  // tag::helpers[]
144  // tag::javadoc[]
145  /**
146   * <p>
147   * Returns response information from the specified URL.
148   * </p>
149   *
150   * @param url
151   *          - target URL.
152   * @return Response object with the response from the specified URL.
153   */
154  // end::javadoc[]
155  private Response getResponse(String url) {
156    return client.target(url).request().get();
157  }
158
159  // tag::javadoc[]
160  /**
161   * <p>
162   * Asserts that the given URL has the correct response code of 200.
163   * </p>
164   *
165   * @param url
166   *          - target URL.
167   * @param response
168   *          - response received from the target URL.
169   */
170  // end::javadoc[]
171  private void assertResponse(String url, Response response) {
172    assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
173  }
174
175  // tag::javadoc[]
176  /**
177   * Asserts that the specified JVM system property is equivalent in both the
178   * system and inventory services.
179   *
180   * @param propertyName
181   *          - name of the system property to check.
182   * @param hostname
183   *          - name of JVM's host.
184   * @param expected
185   *          - expected name.
186   * @param actual
187   *          - actual name.
188   */
189  // end::javadoc[]
190  private void assertProperty(String propertyName, String hostname,
191      String expected, String actual) {
192    assertEquals(expected, actual, "JVM system property [" + propertyName + "] "
193        + "in the system service does not match the one stored in "
194        + "the inventory service for " + hostname);
195  }
196
197  // tag::javadoc[]
198  /**
199   * Makes a simple GET request to inventory/localhost.
200   */
201  // end::javadoc[]
202  private void visitLocalhost() {
203    Response response = this.getResponse(baseUrl + SYSTEM_PROPERTIES);
204    this.assertResponse(baseUrl, response);
205    response.close();
206
207    Response targetResponse = client.target(baseUrl + INVENTORY_SYSTEMS
208        + "/localhost").request().get();
209    targetResponse.close();
210  }
211  // end::helpers[]
212}
213// end::testClass[]

SystemEndpointIT.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License v1.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-v10.html
 8 *
 9 * Contributors:
10 *     IBM Corporation - Initial implementation
11 *******************************************************************************/
12// end::copyright[]
13package it.io.openliberty.guides.system;
14
15import static org.junit.jupiter.api.Assertions.assertEquals;
16
17import jakarta.json.JsonObject;
18import jakarta.ws.rs.client.Client;
19import jakarta.ws.rs.client.ClientBuilder;
20import jakarta.ws.rs.client.WebTarget;
21import jakarta.ws.rs.core.Response;
22
23import org.junit.jupiter.api.Test;
24
25public class SystemEndpointIT {
26
27  @Test
28  public void testGetProperties() {
29    String port = System.getProperty("default.http.port");
30    String url = "http://localhost:" + port + "/";
31
32    Client client = ClientBuilder.newClient();
33
34    WebTarget target = client.target(url + "system/properties");
35    Response response = target.request().get();
36
37    assertEquals(200, response.getStatus(), "Incorrect response code from " + url);
38
39    JsonObject obj = response.readEntity(JsonObject.class);
40
41    assertEquals(System.getProperty("os.name"), obj.getString("os.name"),
42        "The system property for the local and remote JVM should match");
43
44    response.close();
45    client.close();
46  }
47}

Running the tests

Because you started Open Liberty in dev mode, you can run the tests by pressing the enter/return key from the command-line session where you started dev mode.

You see the following output:

[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running it.io.openliberty.guides.health.HealthIT
[INFO] [WARNING ] CWMMH0052W: The class io.openliberty.microprofile.health30.impl.HealthCheck30ResponseImpl implementing HealthCheckResponse in the guide-microprofile-health application in module guide-microprofile-health.war, reported a DOWN status with data Optional[{}].
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.706 s - in it.io.openliberty.guides.health.HealthIT
[INFO] Running it.io.openliberty.guides.system.SystemEndpointIT
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 s - in it.io.openliberty.guides.system.SystemEndpointIT
[INFO] Running it.io.openliberty.guides.inventory.InventoryEndpointIT
[INFO] [WARNING ] Interceptor for {http://client.inventory.guides.openliberty.io/}SystemClient has thrown exception, unwinding now
[INFO] Could not send Message.
[INFO] [err] The specified host is unknown.
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.171 s - in it.io.openliberty.guides.inventory.InventoryEndpointIT
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0

The warning messages are expected. The first warning results from a request to a service that is under maintenance. This request is made in the testHealth() test from the InventoryEndpointIT integration test. The second warning and error results from a request to a bad or an unknown hostname. This request is made in the testUnknownHost() test from the InventoryEndpointIT integration test.

The tests might fail if your system CPU or memory use is high. The status of the system is DOWN if the CPU usage is over 95%, or the memory usage is over 90%.

To see whether the tests detect a failure, manually change the configuration of io_openliberty_guides_inventory_inMaintenance from false to true in the resources/CustomConfigSource.json file. Rerun the tests to see a test failure occur. The test failure occurs because the initial status of the inventory service is DOWN.

When you are done checking out the service, exit dev mode by pressing CTRL+C in the command-line session where you ran the server, or by typing q and then pressing the enter/return key.

Great work! You’re done!

You just learned how to add health checks to report the states of microservices by using MicroProfile Health in Open Liberty. Then, you wrote tests to validate the generated health report.

Feel free to try one of the related MicroProfile guides. They demonstrate additional technologies that you can learn and expand on top of what you built here.

Guide Attribution

Adding health reports to microservices by Open Liberty is licensed under CC BY-ND 4.0

Copied to clipboard
Copy code block
Copy file contents

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star