Adding Commit Info to your Micronaut Application

Expose the exact version of code that your application is running.

Authors: Sergio del Amo

Micronaut Version: 1.0.0.M2

1 Getting Started

In this guide we are going to add git commit info to your Micronaut build artifacts and running application. There are many benefits of keeping your commit info handy:

  • Commit info is encapsulated within the built artifacts

  • Fast authoritative means of identifying what specific code is running in an environment

  • This solution doesn’t rely on external tracking mechanisms

  • Transparency and reproducibility when investigating issues

1.1 What you will need

To complete this guide, you will need the following:

  • Some time on your hands

  • A decent text editor or IDE

  • JDK 1.8 or greater installed with JAVA_HOME configured appropriately

1.2 Solution

We recommend you to follow the instructions in the next sections and create the app step by step. However, you can go right to the completed example.

or

Then, cd into the complete folder which you will find in the root project of the downloaded/cloned project.

2 Writing the App

Create a Kotlin Micronaut app using the Micronaut Command Line Interface.

mn create-app example.micronaut.complete --features=kotlin

The previous command createas a micronaut app with the default package example.micronaut in a folder named complete.

Due to the --features kotlin flag, it generates a Kotlin Micronaut app and it uses Gradle build system. However, you could use other build tool such as Maven or other programming languages such as Java or Groovy.

If you are using Java or Kotlin and IntelliJ IDEA make sure you have enabled annotation processing.

annotationprocessorsintellij

Kotlin, Kapt and IntelliJ

As of this writing IntelliJ’s built-in compiler does not directly support Kapt and annotation processing. You must instead configure Intellij to run Gradle (or Maven) compilation as a build step before running your tests or application class.

First edit the run configuration for tests or for the application and select "Run Gradle task" as a build step:

Intellij Settings

Then add the classes task as task to execute for the application or for tests the testClasses task:

Intellij Settings

Now whenever you run tests or the application Micronaut classes will be generated at compilation time.

Read Micronaut Kotlin section to learn more.

Alternatively, you can delegate IntelliJ build/run actions to gradle completely:

delegatetogradle

3 Management

Inspired by Spring Boot and Grails, the Micronaut management dependency adds support for monitoring of your application via endpoints: special URIs that return details about the health and state of your application.

To use the management features described in this section, add the dependency on your classpath. For example, in build.gradle

build.gradle
dependencies {
...
..
    compile "io.micronaut:management"
}

4 Info endpoint

The info endpoint returns static information from the state of the application. The info exposed can be provided by any number of "info sources".

Enable the info endpoint:

src/main/resources/application.yml
endpoints:
    info:
        enabled: true
        sensitive: false

5 Gradle Git Properties Plugin

If a git.properties file is available on the classpath, the GitInfoSource will expose the values in that file under the git key. Generating of a git.properties file will need to be configured as part of your build; for example, you may choose to use the Gradle Git Properties plugin.

Modify build.gradle file to add the Gradle plugin:

build.gradle
buildscript {
    repositories {
        ...
        ..
    }
    dependencies {
    ..
    .
        classpath "gradle.plugin.com.gorylenko.gradle-git-properties:gradle-git-properties:1.4.21"
    }
}
...
..
.
apply plugin: "com.gorylenko.gradle-git-properties"

6 Test Info endpoint

Speck is a Kotlin Specification Framework for the JVM.

To use Spek modify build.gradle file as described in the Spek documentation:

build.gradle
buildscript {
    repositories {
      ...
      ..
    }
    dependencies {
      ...
      ..
        classpath 'org.junit.platform:junit-platform-gradle-plugin:1.2.0'
    }
}
...
..
.
apply plugin: 'org.junit.platform.gradle.plugin'

junitPlatform {
    filters {
        engines {
            include 'spek'
        }
    }
}

repositories {
  ...
  ..
    maven { url "https://jcenter.bintray.com" }
}

dependencies {
...
..
    testCompile "org.jetbrains.spek:spek-api:1.1.5"
    testRuntime "org.jetbrains.spek:spek-junit-platform-engine:1.1.5"
    testCompile 'org.jetbrains.kotlin:kotlin-test:1.1.0'
}
...
..

    test {
        useJUnitPlatform()
    }

Create a test which verifies that when you do a GET request to /info you get a payload such as:

{
  "git": {
    "dirty": "true",
    "commit": {
      "id": "7368906193527fbf2b45f1ed5b08c56631f5b155",
      "describe": "7368906-dirty",
      "time": "1527429126",
      "message": {
        "short": "Initial version",
        "full": "Initial version"
      },
      "user": {
        "name": "sdelamo",
        "email": "sergio.delamo@softamo.com"
      }
    },
    "branch": "master"
  }
}

Create a Spock feature method to verify the behaviour:

src/test/kotlin/example/micronaut/InfoSpec.kt
package example.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.HttpClient
import io.micronaut.runtime.server.EmbeddedServer
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.on
import kotlin.test.assertEquals
import kotlin.test.assertNotNull

class HomeControllerSpec: Spek({
    describe("info endpoint") {
        var embeddedServer : EmbeddedServer = ApplicationContext.run(EmbeddedServer::class.java) (1)
        var client : HttpClient  = HttpClient.create(embeddedServer.url) (2)
        on("test git commit info appears in JSON") {
            val request: HttpRequest<Any> = HttpRequest.GET("/info") (3)
            var rsp = client.toBlocking().exchange(request, Map::class.java)

            assertEquals(rsp.status(), HttpStatus.OK)

            val json : Map<String, Any> = rsp.body() as Map<String, Any>(4)

            assertNotNull(json["git"])

            val mapCommit = (json["git"] as Map<String, Any>)["commit"] as Map<String, Object>
            assertNotNull(mapCommit)
            assertNotNull(mapCommit["message"])
            assertNotNull(mapCommit["time"])
            assertNotNull(mapCommit["id"])
            assertNotNull(mapCommit["user"])
            assertNotNull((json["git"] as Map<String, Any>)["branch"])

        }
        afterGroup {
            client.close()
            embeddedServer.close()
        }

    }
})
1 To run the application from a unit test you can use the EmbeddedServer interface
2 Register a RxClient bean in the application context and point it to the embedded server URL. The EmbeddedServer interface provides the URL of the server under test which runs on a random port.
3 Creating HTTP Requests is easy thanks to Micronaut’s fluid API.
4 Use .body() to retrieve the parsed payload.

7 Testing the Application

To run the tests:

$ ./gradlew test
$ open build/reports/tests/test/index.html

8 Running the Application

To run the application use the ./gradlew run command which will start the application on a random port.