diff --git a/src/oeffisearch.nim b/src/oeffisearch.nim index 0fdd721..29fe560 100644 --- a/src/oeffisearch.nim +++ b/src/oeffisearch.nim @@ -1,4 +1,4 @@ -import json, tables, os, httpcore, asynchttpserver, asyncdispatch, uri, strutils +import json, tables, os, httpcore, asynchttpserver, asyncdispatch, uri, strutils, posix import types, endpoints/[suggestions, journeys, moreJourneys, refreshJourney] when not defined(release): @@ -7,6 +7,15 @@ when not defined(release): var endpoints {.threadvar.}: Table[string, proc(data: JsonNode): Future[JsonNode] {.gcsafe.}] +proc removePidFile() = + if getEnv("PID_FILE") != "": + removeFile(getEnv("PID_FILE")) + +proc CtrlCHook() {.noconv.} = + echo "Ctrl+C fired! \nStopping Server now!" + removePidFile() + quit() + proc handleRequest(req: Request) {.async,gcsafe.} = var resp = NimHttpResponse( code: Http404, @@ -39,16 +48,16 @@ proc handleRequest(req: Request) {.async,gcsafe.} = await req.respond(resp.code, resp.msg, resp.headers) proc main() = - endpoints = initTable[string, proc(data: JsonNode): Future[JsonNode] {.gcsafe.}]() + setControlCHook(CtrlCHook) - endpoints[$HttpGet & "/suggestions"] = suggestionsEndpoint - endpoints[$HttpGet & "/journeys"] = journeysEndpoint - endpoints[$HttpGet & "/moreJourneys"] = moreJourneysEndpoint - endpoints[$HttpGet & "/refreshJourney"] = refreshJourneyEndpoint + onSignal(SIGTERM): + echo "Got SIGTERM! \nStopping Server now!" + removePidFile() + quit() if getEnv("CACHE_PATH") == "": echo "CACHE_PATH not set! Bye...." - quit() + quit(1) else: discard existsOrCreateDir(getEnv("CACHE_PATH")) @@ -56,6 +65,21 @@ proc main() = if getEnv("PORT") != "": port = parseInt(getEnv("PORT")) + if getEnv("PID_FILE") != "": + try: + writeFile(getEnv("PID_FILE"), $getpid()) + except: + echo "Can't write pid file!" + quit(1) + + + endpoints = initTable[string, proc(data: JsonNode): Future[JsonNode] {.gcsafe.}]() + + endpoints[$HttpGet & "/suggestions"] = suggestionsEndpoint + endpoints[$HttpGet & "/journeys"] = journeysEndpoint + endpoints[$HttpGet & "/moreJourneys"] = moreJourneysEndpoint + endpoints[$HttpGet & "/refreshJourney"] = refreshJourneyEndpoint + let server = newAsyncHttpServer() when not defined(release):