Using Prometheus with Spring Boot

For monitoring and alerting, we use Prometheus. To scrape input, Prometheus requires the different services to expose an endpoint with a specific format. This is a quick intro to getting this endpoint to work with Spring Boot.

TL; DR:

Include Prometheus dependencies using Gradle:

compile 'io.prometheus:simpleclient_spring_boot:0.0.21'
compile 'io.prometheus:simpleclient_servlet:0.0.21'
compile 'io.prometheus:simpleclient_hotspot:0.0.21'

Annotate main class with @EnablePrometheusEndpoint (and optionally @EnableSpringBootMetricsCollector).

Optionally change path using endpoints.prometheus.path="some-valid-path".

Also, there is a running code example over at GitHub.

Now for a more detailed discussion…

Getting a Prometheus endpoint in Spring Boot

The simplest way to enable this endpoint in Spring Boot is utilizing the @EnablePrometheusEndpoint-annotation. Any version >= 0.0.18 (I think) should work with this annotation.

Note: This new endpoint will bind to the management port if this is enabled, not the default application port (which is great – you typically want to hide this from your users).

Firstly, however, we have to include the required packages. For Gradle, this means:

compile 'io.prometheus:simpleclient_spring_boot:0.0.21'
compile 'io.prometheus:simpleclient_servlet:0.0.21'
compile 'io.prometheus:simpleclient_hotspot:0.0.21'

After these dependencies are available, it’s simply a matter of adding the annotation to your main application class, and the endpoint will be available at /prometheus:

package hello;

import io.prometheus.client.spring.boot.EnablePrometheusEndpoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnablePrometheusEndpoint
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

When you start the application and navigate to /prometheus, this is what you get:


Yup, that’s right, nothing. Not really that exciting, but at least it’s a start (i.e., 200 OK!).

But what about the metrics?

I’m glad you asked. Prometheus supplies a few default metrics which we can just include using @EnableSpringBootMetricsCollector. The new main application class now looks like this:

package hello;

import io.prometheus.client.spring.boot.EnablePrometheusEndpoint;
import io.prometheus.client.spring.boot.EnableSpringBootMetricsCollector;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnablePrometheusEndpoint
@EnableSpringBootMetricsCollector
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Navigating to /prometheus now produces:

# HELP mem mem
# TYPE mem gauge
mem 427446.0
# HELP mem_free mem_free
# TYPE mem_free gauge
mem_free 159748.0
# HELP processors processors
# TYPE processors gauge
processors 8.0
# HELP instance_uptime instance_uptime
# TYPE instance_uptime gauge
instance_uptime 13715.0
# HELP uptime uptime
# TYPE uptime gauge
uptime 16324.0
# HELP systemload_average systemload_average
# TYPE systemload_average gauge
systemload_average 1.83984375
# HELP heap_committed heap_committed
# TYPE heap_committed gauge
heap_committed 374272.0
# HELP heap_init heap_init
# TYPE heap_init gauge
heap_init 262144.0
# HELP heap_used heap_used
# TYPE heap_used gauge
heap_used 214523.0
# HELP heap heap
# TYPE heap gauge
heap 3728384.0
# HELP nonheap_committed nonheap_committed
# TYPE nonheap_committed gauge
nonheap_committed 54528.0
# HELP nonheap_init nonheap_init
# TYPE nonheap_init gauge
nonheap_init 2496.0
# HELP nonheap_used nonheap_used
# TYPE nonheap_used gauge
nonheap_used 53175.0
# HELP nonheap nonheap
# TYPE nonheap gauge
nonheap 0.0
# HELP threads_peak threads_peak
# TYPE threads_peak gauge
threads_peak 37.0
# HELP threads_daemon threads_daemon
# TYPE threads_daemon gauge
threads_daemon 3.0
# HELP threads_totalStarted threads_totalStarted
# TYPE threads_totalStarted gauge
threads_totalStarted 43.0
# HELP threads threads
# TYPE threads gauge
threads 37.0
# HELP classes classes
# TYPE classes gauge
classes 6597.0
# HELP classes_loaded classes_loaded
# TYPE classes_loaded gauge
classes_loaded 6597.0
# HELP classes_unloaded classes_unloaded
# TYPE classes_unloaded gauge
classes_unloaded 0.0
# HELP gc_ps_scavenge_count gc_ps_scavenge_count
# TYPE gc_ps_scavenge_count gauge
gc_ps_scavenge_count 7.0
# HELP gc_ps_scavenge_time gc_ps_scavenge_time
# TYPE gc_ps_scavenge_time gauge
gc_ps_scavenge_time 60.0
# HELP gc_ps_marksweep_count gc_ps_marksweep_count
# TYPE gc_ps_marksweep_count gauge
gc_ps_marksweep_count 1.0
# HELP gc_ps_marksweep_time gc_ps_marksweep_time
# TYPE gc_ps_marksweep_time gauge
gc_ps_marksweep_time 35.0

Adding your own collectors

Adding collectors are straight forward. Say I want to add a Counter collector, counting the total number of different messages I receive and their processing status, I could add the following to the class handling the messages:

private static final Counter messages = Counter.build()
            .name("application_messages_received")
            .labelNames("messageType", "processingStatus")
            .help("Handling status of the different messages received").register();
...
public void handleMyMessage(MessageType message) {
    // Do logic
    String processingResult = businessLogic(message);
    messages.labels(message.getClass().getSimpleName(), processingResult).inc();
}

This will report the new Counter with type and help on /prometheus.

For more detailed (and possibly proper) use, please refer to Prometheus documentation.

Configuring the Prometheus endpoint

The enpoint exposed by Prometheus is encapsulated in a bean called prometheus. Using the ordinary Spring Boot’s configuration settings, you can override most of what you find interesting.

What we required was a way to change the path of the endpoint, and this works with the following configuration:

endpoints:
  prometheus:
    path: "prometheus-metrics"

This simply changes the endpoint url to /prometheus-metrics.

Note: It is also possible to change the path by changing endpoints.prometheus.id. However, this changes the bean ID, and does not allow for any other values than characters and underscore. Thus, it would not be possible to change the id to prometheus-metrics, as this contains a dash. Furthermore, this smells bad in my opinion.

But I want to see working code!

Great! Have a look at this git repository.

Acknowledgements

I first ran across a two part blog post on using Spring Boot and Prometheus. Thank you Raymond Lee.

Furthermore, this Stack Overflow question got me reading about @EnablePrometheusEndpoint.

BizTalk – Decide on XPath xs:boolean

The Task

I have a xs:boolean node in my XML-message that I wish to run a decide on.

The Solution

First of all, read up on XPath; it’s actually quite simple, and knowing the basics will help you understand what you are doing.

In your solution and orchestration you will need the following:

  • A schema for the message in the solution
  • A message in the orchestration
  • A decide shape in the orchestration

Then let us say we have a message “Kickoff” with a schema which defines messages similar to this:

<kickoff>
  <firstTask>true</firstTask>
  <secondTask>false</secondTask>
</kickoff>

In this schema, the type of both firstTask and secondTask is xs:boolean.

The first thing to do is to copy the XPath of the node in the schema you are interested in. In Visual Studio 2012 you can do this by:

  1. Opening the schema (e.g., Kickoff.xsd)
  2. Navigating to the node you are interested in (e.g., firstTask)
  3. In the Properties window (alt + enter) copy the “Instance XPath” value
XPath in properties window

Example of Instance XPath on a schema in Visual Studio 2012

In BizTalk we have the xpath() method. This takes two parameters; (1) a message defined in your orchestration and (2) a string representing the XPath you wish to select.

The Conclusion (TL;DR)

So, in the orchestration, double click the Decide shape’s IF-part, and write the following expression:

System.Convert.ToBoolean(xpath(Kickoff, "string(<your XPath>)"))

Replace “Kickoff” with your message name and “” with, well, your XPath (the one you copied).

The magic consist in first getting to the node (the actual XPath), secondly getting the value of that node (string()), and thirdly to convert the value to a boolean which the decide can use.

Post Scriptum

Perhaps you know enough about XPath to know there is a boolean() also, but notice that I used string(). The fact is that as long as the node is present, the boolean() returns True. Always. Thanks to this blog post for enlightening me.

Anyway, the magic here is to convert the result of xpath() to a bool using the System.Convert.ToBoolean().

EPiServer – VirtualPathProvider and URL Encoding

Recently I needed to create a Web API controller for a list of employees to be used in an integration for a new web page. The list of people should contain the usual; names, phone numbers, offices, departments, etc. But it should also include a picture of the employee, encoded as a base64 string to be stored in another database. The only thing out of the ordinary was that this controller should be running within EPiServer 6 R2, and were to fetch all the data from the running process using Pages and VPP-folders.

The implementation of the actual Web API controller was rather trivial, and I decided to use an extension method to create the DTO from a given employee page:

public static class PersonPageToPersonDTO
{
    public static PersonDTO ToDTO(this PageData personPage)
    {
        /* implementation goes here */
    }
}

After having implemented both the extension method and the Web API controller and tested that it actually worked, being very pleased with myself I moved the code over to our test environment. There, the BizTalk integration connected to the controller and transferred all the information, pictures included, and put it in database somewhere. It was then I discovered that only about ten percent of the images were actually being exposed through the Web API controller, and I to start testing and debugging.

What annoyed me was that the code I used to fetch the image was trivial, and I could not see why it didn’t work. The code which caused my confusion, altered to simplify debugging, was:

var isEmpty = string.IsNullOrEmpty(picturePath);
var exists = HostingEnvironment.VirtualPathProvider.FileExists(picturePath);
if (!isEmpty && exists)
    return picturePath;

The picturePath being examined actually existed. If I navigated to the URL, it showed me the image, but when I used the HostingProvider.VirtualPathProvider.FileExists(picturePath), it returned false, and calls to HostingProvider.VirtualPathProvider.GetFile(picturePath) returnes null.

Skip ahead three hours and it turned out that the path to the images which were not being loaded were URL encoded string, and thus the VirtualPathProvider were not able to map them.

Therefore; when using the HostingProvider.VirtualPathProvider, always use URL decoded strings.