You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Main.scala 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package de.codingchallenge
  2. import akka.Done
  3. import akka.http.scaladsl.Http
  4. import akka.http.scaladsl.model.{HttpResponse}
  5. import akka.http.scaladsl.model.StatusCodes.InternalServerError
  6. import akka.http.scaladsl.server.Directives.{
  7. complete,
  8. extractUri
  9. }
  10. import akka.http.scaladsl.server._
  11. import akka.stream.ActorMaterializer
  12. import akka.actor.{ActorSystem, CoordinatedShutdown}
  13. import com.typesafe.scalalogging.LazyLogging
  14. import scala.util.{Failure, Success}
  15. import fr.davit.akka.http.prometheus.scaladsl.server.HttpMetricsRoute._
  16. import fr.davit.akka.http.prometheus.scaladsl.server.HttpMetricsDirectives._
  17. import io.prometheus.client.hotspot.DefaultExports
  18. object Main extends App with DependencyInjectionModule with LazyLogging {
  19. implicit lazy val actorSystem = ActorSystem("system")
  20. implicit lazy val actorMaterializer = ActorMaterializer()
  21. implicit lazy val executionContext = actorSystem.dispatcher
  22. logbackReconfigurator.configureLogging()
  23. akkaConfigurator.configure()
  24. DefaultExports.initialize()
  25. val (host, port) = (environment.hostIP, environment.hostPort)
  26. val bindingFuture =
  27. Http().bindAndHandle(handleExceptions()(withMetrics(httpMetricsExports) {
  28. routes.routes
  29. }), host, port)
  30. Http().bindAndHandle(routes.rejectRoute.withMetricsHandler, host, port + 1)
  31. def handleExceptions(): (Route) => Route = (route: Route) => {
  32. val exceptionHandler: ExceptionHandler = ExceptionHandler {
  33. case e: Exception =>
  34. extractUri { uri =>
  35. logger.error("error in route processing for request "+uri.toString , e)
  36. complete(HttpResponse(InternalServerError, entity = "There was an internal server error, please try again later."))
  37. }
  38. }
  39. akka.http.scaladsl.server.Directives.handleExceptions(exceptionHandler) {
  40. route
  41. }
  42. }
  43. bindingFuture.onComplete {
  44. case Success(_) =>
  45. println(s"Server for started at localhost:9080")
  46. case Failure(cause) =>
  47. println(s"Server failed to start", cause)
  48. }
  49. CoordinatedShutdown(actorSystem).addTask(
  50. CoordinatedShutdown.PhaseBeforeServiceUnbind, "http_shutdown") { () =>
  51. routes.shutdown()
  52. logger.info(s"Server is Shuting down, cause (external signal), wait 4.8 Seconds to complete requests")
  53. Thread.sleep(4800)
  54. logger.info(s"Going down")
  55. bindingFuture.flatMap(_.unbind).flatMap { _ =>
  56. Http().shutdownAllConnectionPools
  57. }.map { _ =>
  58. Done
  59. }
  60. }
  61. }