diff --git a/README.md b/README.md index e2aa87a..8f49513 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,129 @@ # healthchecks -tiny healthcheck library for akka-http with Kubernetes liveness/readiness support +[![Build Status](https://travis-ci.org/everpeace/healthchecks.svg?branch=master)](https://travis-ci.org/everpeace/healthchecks) +[![Bintray](https://img.shields.io/bintray/v/everpeace/maven/healthchecks.svg)](https://bintray.com/everpeace/maven/healthchecks/_latestVersion) +[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) + +tiny healthcheck library for akka-http with [Kubernetes liveness/readiness probe][k8sprobe] support. + +## Installation +You need to activate [sbt-bintray](https://github.com/sbt/sbt-bintray) plugin first. And then, You will add it to your build by including these lines in your sbt file. Please refer to download badge above for the latest version. + +```scala +resolvers += Resolver.bintrayRepo("everpeace","maven") + +libraryDependencies += "com.github.everpeace" %% "healthchecks-core" % + +// when you want kubernetes liveness/readiness probe support. +libraryDependencies += "com.github.everpeace" %% "healthchecks-k8s-probes" % +``` + +## Getting Started +### Simple healthcheck endpoint +All you need to give is just health check function returning cats `ValidationNel[String, Unit]`. + +```scala + import akka.actor.ActorSystem + import akka.stream.ActorMaterializer + import akka.http.scaladsl.Http + import akka.http.scaladsl.model.HttpRequest + import cats.syntax.validated._ + import scala.concurrent.Future + import scala.util.Random + + implicit val system = ActorSystem() + implicit val materializer = ActorMaterializer() + implicit val ec = system.dispatcher + + import com.github.everpeace.healthchecks._ + import com.github.everpeace.healthchecks.route._ + + // defining sync/async healthchecks + val simple = healthCheck(name = "simple") { + if (Random.nextBoolean()) healthy else "Unlucky!".invalidNel + } + + val simpleAsync = asyncHealthCheck("simpleAsync") { + Future { + if (Random.nextBoolean()) healthy else "Unlucky!".invalidNel + } + } + + // start web server listening "localhost:8888/health" + val serverBinding = Http().bindAndHandle( + handler = HealthCheckRoutes.health(simple, simpleAsync), + interface = "localhost", + port = 8888 + ) + + val response = Http().singleRequest(HttpRequest(uri = "http://localhost:8888/health")) + + // response body would be an json object similar to below. + // Please see com.github.everpeace.healthchecks.HealthRoutesTest for various response patterns. + // { + // "status": "healthy", + // "check_results": [ + // { "name": "simple", "severity": "Fatal", "status": "healthy", "messages": [] }, + // { "name": "simpleAsync", "severity": "Fatal", "status": "healthy", "messages": [] } + // ] + // } +``` + +### Kubernetes liveness/readiness probe endpoints +It supports to setup kubernetes liveness/readiness probe really easily like this. You con configure probe paths and binding setting by typesafe config (i.e. application.conf). Please refer [reference.conf](k8s-probes/src/main/resources/reference.conf) for details. + +```scala + import akka.actor.ActorSystem + import akka.stream.ActorMaterializer + import scala.concurrent.Future + + implicit val system = ActorSystem() + implicit val materializer = ActorMaterializer() + implicit val ec = system.dispatcher + + import com.github.everpeace.healthchecks._ + import com.github.everpeace.healthchecks.k8s._ + + // by default, listening localhost:9999 + // and probe paths are + // /k8s/liveness_probe + // /k8s/readiness_probe + val probeBinding = bindAndHandleProbes( + readinessProbe(healthCheck(name = "readiness_check")(healthy)), + livenessProbe(asyncHealthCheck(name = "liveness_check")(Future(healthy))) + ) +``` + +Then you can set kubernetes liveness/readiness probe in the kubernetes manifest like below: + +```yaml +... + livenessProbe: + httpGet: + path: /k8s/liveness_probe + port: 9999 + initialDelaySeconds: 3 + periodSeconds: 3 + readinessProbe: + httpGet: + path: /k8s/readiness_probe + port: 9999 + initialDelaySeconds: 3 + periodSeconds: 3 +... +``` + +## Contribution policy ## + +Contributions via GitHub pull requests are gladly accepted from their original author. Along with any pull requests, please state that the contribution is your original work and that you license the work to the project under the project's open source license. Whether or not you state this explicitly, by submitting any copyrighted material via pull request, email, or other means you agree to license the material under the project's open source license and warrant that you have the legal authority to do so. + +Please make sure to follow these conventions: +- For each contribution there must be a ticket (GitHub issue) with a short descriptive name, e.g. "Respect host/port configuration setting" +- Work should happen in a branch named "ISSUE-DESCRIPTION", e.g. "32-respect-host-and-port" +- Before a PR can be merged, all commits must be squashed into one with its message made up from the ticket name and the ticket id, e.g. "Respect host/port configuration setting (closes #32)" + +## License +This code is open source software licensed under MIT License. + +Please note that part of codes in the repository were originally written by [timeoutdigital](https://github.com/timeoutdigital). Copyright credit presents on relevant sources. + +[k8sprobe]: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/ "Kubernetes liveness/readiness probe" \ No newline at end of file diff --git a/core/src/main/scala/com/github/everpeace/healthchecks/HealthCheck.scala b/core/src/main/scala/com/github/everpeace/healthchecks/HealthCheck.scala index 40fccda..9c937ba 100644 --- a/core/src/main/scala/com/github/everpeace/healthchecks/HealthCheck.scala +++ b/core/src/main/scala/com/github/everpeace/healthchecks/HealthCheck.scala @@ -19,6 +19,13 @@ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/* + * The original source code were written by https://github.com/timeoutdigital. + * Original source code are distributed with MIT License. + * Please see: https://github.com/timeoutdigital/akka-http-healthchecks + * The codes are modified from original one by Shingo Omura. + */ + package com.github.everpeace.healthchecks import cats.syntax.validated._ diff --git a/core/src/main/scala/com/github/everpeace/healthchecks/package.scala b/core/src/main/scala/com/github/everpeace/healthchecks/package.scala index 163dc5a..35fe0a1 100644 --- a/core/src/main/scala/com/github/everpeace/healthchecks/package.scala +++ b/core/src/main/scala/com/github/everpeace/healthchecks/package.scala @@ -19,6 +19,13 @@ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/* + * The original source code were written by https://github.com/timeoutdigital. + * Original source code are distributed with MIT License. + * Please see: https://github.com/timeoutdigital/akka-http-healthchecks + * The codes are modified from original one by Shingo Omura. + */ + package com.github.everpeace import cats.data.ValidatedNel diff --git a/core/src/main/scala/com/github/everpeace/healthchecks/route/HealthCheckRoutes.scala b/core/src/main/scala/com/github/everpeace/healthchecks/route/HealthCheckRoutes.scala index f882b20..433b973 100644 --- a/core/src/main/scala/com/github/everpeace/healthchecks/route/HealthCheckRoutes.scala +++ b/core/src/main/scala/com/github/everpeace/healthchecks/route/HealthCheckRoutes.scala @@ -19,11 +19,19 @@ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/* + * The original source code were written by https://github.com/timeoutdigital. + * Original source code are distributed with MIT License. + * Please see: https://github.com/timeoutdigital/akka-http-healthchecks + * The codes are modified from original one by Shingo Omura. + */ + package com.github.everpeace.healthchecks.route import akka.http.scaladsl.model.StatusCodes._ import akka.http.scaladsl.server.Directives._ -import akka.http.scaladsl.server.PathMatchers +import akka.http.scaladsl.server.{PathMatchers, Route} +import akka.http.scaladsl.server.directives.PathDirectives import cats.data.Validated.{Invalid, Valid} import com.github.everpeace.healthchecks.{HealthCheck, HealthCheckResult} import de.heikoseeberger.akkahttpcirce.CirceSupport._ @@ -42,9 +50,9 @@ object HealthCheckRoutes extends DecorateAsScala { messages: List[String]) @JsonCodec case class ResponseJson(status: String, check_results: List[HealthCheckResultJson]) - def status(s: Boolean) = if (s) "healthy" else "unhealthy" - def statusCode(s: Boolean) = if (s) OK else InternalServerError - def toResultJson(check: HealthCheck, result: HealthCheckResult) = + private def status(s: Boolean) = if (s) "healthy" else "unhealthy" + private def statusCode(s: Boolean) = if (s) OK else InternalServerError + private def toResultJson(check: HealthCheck, result: HealthCheckResult) = HealthCheckResultJson( check.name, check.severity.toString, @@ -56,19 +64,25 @@ object HealthCheckRoutes extends DecorateAsScala { ) def health( - checks: List[HealthCheck], - pathString: String = "health" + checks: HealthCheck* + )(implicit + ec: ExecutionContext + ): Route = health("health", checks.toList) + + def health( + path: String, + checks: List[HealthCheck] )(implicit ec: ExecutionContext - ) = { - require(checks.nonEmpty, "checks must not empty.") + ): Route = { + require(checks.toList.nonEmpty, "checks must not empty.") require( checks.toList.map(_.name).toSet.size == checks.toList.length, s"HealthCheck name should be unique (given HealthCheck names = [${checks.toList.map(_.name).mkString(",")}])." ) val rootSlashRemoved = - if (pathString.startsWith("/")) pathString.substring(1) else pathString - path(PathMatchers.separateOnSlashes(rootSlashRemoved)) { + if (path.startsWith("/")) path.substring(1) else path + PathDirectives.path(PathMatchers.separateOnSlashes(rootSlashRemoved)) { get { complete { Future diff --git a/core/src/test/scala/com/github/everpeace/healthchecks/HealthCheckRoutesTest.scala b/core/src/test/scala/com/github/everpeace/healthchecks/HealthCheckRoutesTest.scala index faa9a1b..d654065 100644 --- a/core/src/test/scala/com/github/everpeace/healthchecks/HealthCheckRoutesTest.scala +++ b/core/src/test/scala/com/github/everpeace/healthchecks/HealthCheckRoutesTest.scala @@ -19,6 +19,13 @@ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/* + * The original source code were written by https://github.com/timeoutdigital. + * Original source code are distributed with MIT License. + * Please see: https://github.com/timeoutdigital/akka-http-healthchecks + * The codes are modified from original one by Shingo Omura. + */ + package com.github.everpeace.healthchecks import akka.http.scaladsl.model.StatusCodes._ @@ -36,13 +43,15 @@ class HealthRoutesTest describe("HealthCheck route") { it("should raise exception when no healthcheck is given.") { val exception = the[IllegalArgumentException] thrownBy HealthCheckRoutes - .health(List()) + .health() exception.getMessage shouldEqual "requirement failed: checks must not empty." } it("should raise exception when given healthchecks have same names") { - val exception = the[IllegalArgumentException] thrownBy HealthCheckRoutes - .health(List(healthCheck("test")(healthy), healthCheck("test")(healthy))) + val exception = the[IllegalArgumentException] thrownBy HealthCheckRoutes.health( + healthCheck("test")(healthy), + healthCheck("test")(healthy) + ) exception.getMessage shouldEqual "requirement failed: HealthCheck name should be unique (given HealthCheck names = [test,test])." } @@ -50,7 +59,7 @@ class HealthRoutesTest val ok1 = healthCheck("test1")(healthy) val ok2 = healthCheck("test2")(healthy) - Get("/health") ~> HealthCheckRoutes.health(List(ok1, ok2)) ~> check { + Get("/health") ~> HealthCheckRoutes.health(ok1, ok2) ~> check { status shouldEqual OK responseAs[String] shouldEqual """ @@ -71,7 +80,7 @@ class HealthRoutesTest val failedButNonFatal = healthCheck("test2", Severity.NonFatal)(unhealthy("error")) - Get("/health") ~> HealthCheckRoutes.health(List(ok1, failedButNonFatal)) ~> check { + Get("/health") ~> HealthCheckRoutes.health(ok1, failedButNonFatal) ~> check { status shouldEqual OK responseAs[String] shouldEqual """ @@ -93,7 +102,7 @@ class HealthRoutesTest healthCheck("test2", Severity.NonFatal)(unhealthy("error")) val failedFatal = healthCheck("test3")(throw new Exception("exception")) - Get("/health") ~> HealthCheckRoutes.health(List(ok, failedButNonFatal, failedFatal)) ~> check { + Get("/health") ~> HealthCheckRoutes.health(ok, failedButNonFatal, failedFatal) ~> check { status shouldEqual InternalServerError responseAs[String] shouldEqual """ diff --git a/k8s-probes/src/main/scala/com/github/everpeace/healthchecks/k8s/K8sProbe.scala b/k8s-probes/src/main/scala/com/github/everpeace/healthchecks/k8s/K8sProbe.scala index 931aacc..017e88e 100644 --- a/k8s-probes/src/main/scala/com/github/everpeace/healthchecks/k8s/K8sProbe.scala +++ b/k8s-probes/src/main/scala/com/github/everpeace/healthchecks/k8s/K8sProbe.scala @@ -32,7 +32,7 @@ sealed abstract class K8sProbe protected ( val ec: ExecutionContext) { require(checks.nonEmpty, "checks must not be empty.") - def toRoute = HealthCheckRoutes.health(checks, path)(ec) + def toRoute = HealthCheckRoutes.health(path, checks)(ec) } case class LivenessProbe protected (