diff --git a/doc/pods.md b/doc/pods.md index 7adabb00..4f4ab051 100644 --- a/doc/pods.md +++ b/doc/pods.md @@ -178,6 +178,12 @@ message related to the request with `id` `1d17f8fe-4f70-48bf-b6a9-dc004e52d056`. Now you know most there is to know about the pod protocol! +#### shutdown + +When babashka is about to exit, it sends a `{"op" "shutdown"}` message and waits +for the pod process to end. This gives the pod a chance to clean up resources +before it exits. + #### out and err Pods may send messages with an `out` and `err` string value. Babashka prints diff --git a/src/babashka/impl/pods.clj b/src/babashka/impl/pods.clj index 937f9d24..902bf0b0 100644 --- a/src/babashka/impl/pods.clj +++ b/src/babashka/impl/pods.clj @@ -75,6 +75,9 @@ (binding [*out* @sci/err] (prn e)))))) +(defn next-id [] + (str (java.util.UUID/randomUUID))) + (defn invoke [pod pod-var args async?] (let [stream (:stdin pod) format (:format pod) @@ -82,7 +85,7 @@ write-fn (case format :edn pr-str :json cheshire/generate-string) - id (str (java.util.UUID/randomUUID)) + id (next-id) chan (async/chan) _ (swap! chans assoc id chan) _ (write stream {"id" id @@ -105,8 +108,13 @@ stdin (.getOutputStream p) stdout (.getInputStream p) stdout (java.io.PushbackInputStream. stdout) - _ (add-shutdown-hook! #(.destroy p)) - _ (write stdin {"op" "describe"}) + _ (add-shutdown-hook! + (fn [] + (write stdin {"op" "shutdown" + "id" (next-id)}) + (.waitFor p))) + _ (write stdin {"op" "describe" + "id" (next-id)}) reply (read stdout) format (-> (get reply "format") bytes->string keyword) pod {:process p diff --git a/test-resources/pod.clj b/test-resources/pod.clj index 31f3647e..48824283 100644 --- a/test-resources/pod.clj +++ b/test-resources/pod.clj @@ -111,7 +111,8 @@ (write {"status" ["done"] "id" id}))) - (recur))))))))) + (recur)) + :shutdown (System/exit 0)))))))) (let [cli-args (set *command-line-args*)] (if (contains? cli-args "--run-as-pod")