Skip to content

Commit

Permalink
Handle sigterm for api process (#266)
Browse files Browse the repository at this point in the history
* Handle sigterm for api process

* Review feedback
  • Loading branch information
mdemare authored Jan 10, 2024
1 parent 9ca98a0 commit f18a75b
Showing 1 changed file with 29 additions and 4 deletions.
33 changes: 29 additions & 4 deletions src/nl/surf/eduhub_rio_mapper/api.clj
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,20 @@
[java.net MalformedURLException URL]
[org.eclipse.jetty.server HttpConnectionFactory]))

(def server-stopping (atom false))

(def nr-active-requests (atom 0))

(defn wrap-server-status [app]
(fn [req]
(if @server-stopping
{:status http-status/service-unavailable :body "Server stopping"}
(try
(swap! nr-active-requests inc)
(app req)
(finally
(swap! nr-active-requests dec))))))

(defn wrap-job-enqueuer
[app enqueue-fn]
(fn with-job-enqueuer [req]
Expand Down Expand Up @@ -214,14 +228,25 @@
(wrap-json-response)
(wrap-logging)
(wrap-trace-context)
(defaults/wrap-defaults defaults/api-defaults))))
(defaults/wrap-defaults defaults/api-defaults)
(wrap-server-status))))

(defn shutdown-handler []
;; All subsequent requests will get a 503 error
(reset! server-stopping true)
;; Wait until all pending requests have been completed
(loop []
(when (< 0 @nr-active-requests)
(Thread/sleep 500)
(recur))))

(defn serve-api
[{{:keys [^Integer port host]} :api-config :as config}]
(.addShutdownHook (Runtime/getRuntime) (new Thread ^Runnable shutdown-handler))
(jetty/run-jetty (make-app config)
{:host host
:port port
:join? true
{:host host
:port port
:join? true
;; Configure Jetty to not send server version
:configurator (fn [jetty]
(doseq [connector (.getConnectors jetty)]
Expand Down

0 comments on commit f18a75b

Please sign in to comment.