ctucx.git: oeffisearch

[nimlang] fast and simple tripplanner

commit 105867be584af6f5db1c2ef7be0391760622c83d
parent a03e08b99bca66ddc7adfe3884da5a2907f9f0fd
Author: Leah Thein <leah@toaster.fritz.box>
Date: Sat, 5 Dec 2020 08:37:32 +0100

remove pidfile on exit, handle SIGTERM/ctrl+c
1 file changed, 31 insertions(+), 7 deletions(-)
M
src/oeffisearch.nim
|
38
+++++++++++++++++++++++++++++++-------
diff --git 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):