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 Container runtime.

Background

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

The billing rules for instance lifecycle hooks 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. Logs for lifecycle hooks are not displayed in invocation request lists. For more information, see View logs of instance lifecycle hooks.

Hook implementation methods

Function Compute calls the corresponding hook when the corresponding lifecycle event occurs. You can configure Initializer and PreStop hooks for function instances.

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

This following code snippet provides an example of implementing instance lifecycle hooks in the Python 3.10 custom runtime:

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 normal code, function exceptions may be reported in Python. The following code snippets provide examples of /initialize:

@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 implement an Initializer hook in a Custom Container runtime, you must implement the logic of the /initialize path and the POST method in your HTTP server. You can use the sample code for initialize in the preceding table as references.

Important

If you do not configure an Initializer hook when you create a function, you do not need to implement /initialize. In this case, even if your HTTP server implements /initialize, the /initialize logic in your 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 an Initializer hook fails, the 400 or 404 error code is returned. In this case, the request is not repeatedly submitted. However, the system continues to retry until the invocation succeeds.

  • If a 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 the lifecycle hooks and timeout periods, and then click Deploy.

    image

  5. After you configure a lifecycle hook, you need to implement the hook in your code. Click Deploy above the code editor, and then click Test Function.

View logs of instance lifecycle hooks

You can view logs of 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 logs of function invocations and Initializer hooks. 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. Therefore, 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, 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*******