All Products
Search
Document Center

Function Compute:Lifecycle hooks for function instances

Last Updated:Aug 05, 2024

This topic describes how to implement lifecycle hooks for function instances in a custom runtime.

Background

After you configure a lifecycle hook for a function instance, Function Compute invokes the hook when the corresponding instance lifecycle event occurs. You can configure Initializer and PreStop hooks for a function instance. For more information, see Configure instance lifecycles.

The billing rules for lifecycle hooks of function instances are the same as the billing rules for common invocation requests. However, the execution logs can be queried only in Function Logs, Real-time Logs, and Advanced Logs. The logs for lifecycle hooks are not displayed in the invocation request list. For more information, see View the logs of instance lifecycle hooks.

Implement hook methods

Function Compute calls the corresponding lifecycle hooks when corresponding instance lifecycle events occur. You can configure Initializer and PreStop hooks for a function.

Path

Input request

Expected response

(Optional) POST /initialize

Request body: none.

Request headers: common request headers. For more information, see Common request headers in Function Compute.

Response body: the return value of Initializer.

StatusCode

  • 2xx: successful

  • Other codes: failed

(Optional) GET /pre-stop

Response body: the return value of the PreStop hook.

StatusCode

  • 2xx: successful

  • Other codes: failed

In this topic, a function that runs in the Python 3.10 runtime is used as an example to describe lifecycle hooks in custom runtimes.

import os
from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/initialize', methods=['POST'])
def init_invoke():
    rid = request.headers.get('x-fc-request-id')
    print("FC Initialize Start RequestId: " + rid)
    # do your things
    print("FC Initialize End RequestId: " + rid)
    return "OK"

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def hello_world(path):
    rid = request.headers.get('x-fc-request-id')
    print("FC invoke Start RequestId: " + rid)
    # do your things
    print("FC invoke End RequestId: " + rid)
    return "Hello, World!", 200, [('Function-Name', os.getenv('FC_FUNCTION_NAME'))]


@app.route('/pre-stop', methods=['GET'])
def prestop_invoke():
    rid = request.headers.get('x-fc-request-id')
    print("FC PreStop Start RequestId: " + rid)
    # do your things
    print("FC PreStop End RequestId: " + rid)
    return "OK"


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000)

In addition to the preceding code, there are also scenarios in which function execution errors are reported in Python. /initialize sample code is as follows:

@app.route('/initialize', methods=['POST'])
def init():
    raise Exception("hahaha")
    return "OK", 200, []
@app.route('/initialize', methods=['POST'])
def init():
    return "OK", 404, []

If you want to use an Initializer hook in a custom runtime, you need to only set the path to /initialize and the method to POST on your HTTP server. You can refer to the sample code of initialize in the preceding table.

Important

If you do not configure the Initializer hook when you create a function, you do not need to set the path to /initialize. In this case, even if the HTTP server implements /initialize, the /initialize logic in the code cannot be called and executed.

A PreStop hook is used in the same way as an Initializer hook.

Error codes

Error code

Description

400

  • If the Initializer hook fails, the 400 or 404 error code is returned. In this case, Function Compute does not resend the request, but retries the Initializer hook until the Initializer hook is successful.

  • If the PreStop hook fails, the 400 or 404 error code is returned. In this case, the function instance can still be frozen or stopped as expected.

404

500

Function Compute restarts the function instance.

Configure lifecycle hooks

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, click the Configurations tab. In the left-side navigation pane, click Lifecycle. Then, click Modify.

  4. In the Lifecycle panel, configure hooks and timeout periods, and then click Deploy.

    image

  5. After you configure a lifecycle hook, you need to implement the corresponding hook in code execution. Click Deploy in the upper part of the code editor, and then click Test Function.

View the logs of instance lifecycle hooks

You can view logs for lifecycle hooks in Logs.

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, click the Tests tab, click Test Function, and then choose Logs > Function Logs.

    On the Logs tab, you can view function invocation logs and Initializer logs. Example:

    2024-06-26 10:59:23FC Initialize Start RequestId: 529eab23-9b3a-4ffc-88c8-9a686*******
    2024-06-26 10:59:23FC Initialize End RequestId: 529eab23-9b3a-4ffc-88c8-9a686*******
    2024-06-26 10:59:25FC Invoke Start RequestId: 1-667b840c-15c49df0-b7dc1*******
    2024-06-26 10:59:25FC Invoke End RequestId: 1-667b840c-15c49df0-b7dc1*******

    Each function instance is cached for a period of time and not immediately destroyed, you cannot view logs for PreStop hooks right away. To quickly trigger a PreStop hook, you can update the function configurations or function code. After the update is complete, you can view the logs for PreStop hooks in Function Logs. The following sample code shows an example:

    2024-06-26 11:04:33FC PreStop Start RequestId: c4385899-f071-490e-a8b7-e33c5*******
    2024-06-26 11:04:33FC PreStop End RequestId: c4385899-f071-490e-a8b7-e33c5*******