mozilla-iam / mozilla-aws-cli

DEPRECATED. A command line tool to allow users to log into AWS with their federated identity using Single Sign On and obtain ephemeral API keys. This is no longer in use in Mozilla SSO/IAM, as of September 15th, 2023.
Mozilla Public License 2.0
20 stars 8 forks source link

Nicer shutdown #228

Open klahnakoski opened 4 years ago

klahnakoski commented 4 years ago

mozilla-aws-cli ungracefully exits the process when a browser calls /shutdown, which makes it difficult to work with inside a larger application. A clean shutdown (without exit()) would make using mozilla-aws-cli as yet-another-library easier.

Here is some suggested code

@app.route("/shutdown", methods=["GET"])
def handle_shutdown():
    try:
        return Response(b"", 200)
    finally:
        try:
            Log.note("server shutdown")
            server.shutdown()
        except Exception as cause:
            Log.error("can not shutdown listener", cause=cause)

class ServerThread(threading.Thread):

    def __init__(self, app):
        threading.Thread.__init__(self)
        self.srv = make_server('127.0.0.1', port, app)
        self.ctx = app.app_context()
        self.ctx.push()

    def run(self):
        self.srv.serve_forever()

    def shutdown(self):
        self.srv.shutdown()

def listen(login_):
    global server, login

    login = login_
    server = ServerThread(app)
    server.start()

    os.environ["WERKZEUG_RUN_MAIN"] = "true"
    logging.getLogger("werkzeug").setLevel(logging.ERROR)

    return port