From b1dd32b72b17d448925f4dc308b89d66105f09d6 Mon Sep 17 00:00:00 2001 From: "Alex Ellis (OpenFaaS Ltd)" Date: Thu, 25 May 2023 11:39:02 +0100 Subject: [PATCH] Drain connections for python3-http When used with OpenFaaS Standard/Enterprise, the python3-http template's handler will now ignore SIGTERM allowing the watchdog and Kubernetes to handle the shutdown. When there are ongoing requests, these will be processed before exiting. When there are no ongoing requests, the function will exit immediately. Tested with OpenFaaS Standard a long running sleep function which went into a Terminating status. The function continued to execute its sleep for the whole duration, whilst the new replica came online and was ready in the meantime. This is the same approach tested for the golang-http templates. Signed-off-by: Alex Ellis (OpenFaaS Ltd) --- template/python3-http/index.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/template/python3-http/index.py b/template/python3-http/index.py index 5d2f33b..a3aa000 100644 --- a/template/python3-http/index.py +++ b/template/python3-http/index.py @@ -2,11 +2,20 @@ from flask import Flask, request, jsonify from waitress import serve import os +import sys + +import signal from function import handler app = Flask(__name__) +def SignalHandler(SignalNumber, Frame): + timeout = os.getenv("write_timeout") + + sys.stderr.write('Function got SIGTERM, draining for up to: {}\n'.format(timeout)) + sys.stderr.flush() + class Event: def __init__(self): self.body = request.get_data() @@ -66,4 +75,7 @@ def call_handler(path): return resp if __name__ == '__main__': + + signal.signal(signal.SIGTERM, SignalHandler) + serve(app, host='0.0.0.0', port=5000)