After you implement and configure instance lifecycle hooks, Function Compute invokes the corresponding hook when a specific instance lifecycle event occurs. This topic describes how to implement instance lifecycle hooks for a custom image.
Background information
The function instance lifecycle involves Initializer and PreStop hooks. Initializer hooks include two types: invoke code and execute instruction. Currently, only GPU-accelerated functions support Initializer hooks of the execute instruction type. For more information, see Configure instance lifecycle.
Instance lifecycle hooks are billed in the same way as normal invocation requests. Their execution logs appear only in Real-time Log, Function Log, or Advanced Log, and are not displayed in the Invocation Request List. For more information, see View the logs of instance lifecycle hooks.
Currently, logs generated by `execute instruction` hooks cannot be written to function logs.
Implement callback methods
When a specific instance lifecycle event occurs, Function Compute invokes the corresponding hook. The instance lifecycle includes Initializer and PreStop hooks. Initializer hooks can be one of two types: invoke code or execute instruction. You can configure only one type of Initializer hook at a time.
Invoke code
After you configure an `invoke code` hook, the system sends an HTTP request to your function. A `POST /initialize` request is sent when the instance starts, and a `GET /pre-stop` request is sent when the instance stops. You must handle these requests in your business code.
Path | Input request | Expected response |
(Optional) POST |
| Response body: The return value of the function's Initializer. StatusCode
Note When an Initializer hook times out or fails, the server always returns an HTTP 200 status code. You must check the |
(Optional) GET |
| Response body: The return value of the function's PreStop. StatusCode
|
To use an Initializer hook in a custom image, you must implement the logic for the `POST /initialize` path in your HTTP server. Similarly, for PreStop hooks, you must implement the logic for the `GET /pre-stop` path. The following example uses a custom runtime for Python 3.10.
If you do not configure an Initializer hook when you create a function, you do not need to implement the `/initialize` path. If you implement the `/initialize` path but do not configure the hook, the logic in your code is not invoked. The same applies to the PreStop hook and the `/pre-stop` path.
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, a function execution error can occur in Python. The following code shows an example of an error scenario for /initialize.
@app.route('/initialize', methods=['POST'])
def init():
raise Exception("hahaha")
return "OK", 200, []@app.route('/initialize', methods=['POST'])
def init():
return "OK", 404, []Execute instruction
You can configure a callback instruction to perform initialization operations after the function instance starts. You can use any shell implementation that is supported by the function runtime environment, such as /bin/bash, /bin/sh, /bin/csh, or /bin/zsh.
The Function Compute console provides two preset shells: /bin/bash and /bin/sh. The following example uses /bin/sh.
#!/bin/sh
URL="http://localhost:7860"
REQUEST_PATH="sdapi/v1/txt2img"
JSON_DATA='{
"prompt": "",
"steps": 1,
"height": 8,
"width": 8
}'
temp_file=$(mktemp)
trap 'rm -f "$temp_file"' EXIT
if ! http_code=$(curl -s -w "%{http_code}" \
-H "Content-Type: application/json" \
-d "$JSON_DATA" \
-o "$temp_file" \
-X POST "$URL"/"$REQUEST_PATH"); then
echo "{\"status\": \"curl_error\", \"code\": $curl_exit_code}" \
| jq . >&2
exit 1
fi
response=$(<"$temp_file")
echo "http code $http_code"
if [ "$http_code" -eq 200 ]; then
echo "$response" | jq -r '.' || printf "%s\n" "$response"
exit 0
else
echo "$response_body" \
| jq -c 'if type == "object" then . else {raw: .} end' 2>/dev/null \
| jq -s '{status: "http_error", code: $code, response: .[0]}' \
--arg code "$http_code" \
>&2
exit 1
fiIf the exit code of the callback instruction is 0, the execution is successful. Any other exit code indicates a failure. You can output error messages to standard error (stderr) in the script to help diagnose errors. For example, the following code snippet shows how to output error information and set the exit code to 1 after a curl request fails.
if ! http_code=$(curl -s -w "%{http_code}" \
-H "Content-Type: application/json" \
-d "$JSON_DATA" \
-o "$temp_file" \
-X POST "$URL"/"$REQUEST_PATH"); then
echo "{\"status\": \"curl_error\", \"code\": $curl_exit_code}" \
| jq . >&2
exit 1
fiCallback error codes
Invoke code
Error code ID | Description |
400 |
|
404 | |
500 | Function Compute restarts the instance. |
Execute instruction
If the exit code of the instruction is not 0, the instruction is not re-executed, and the system returns an error.
Configure lifecycle hooks
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Configuration tab. In the Instance Configuration section, click Edit.
In the Instance Configuration panel, configure the Initializer hook and set the Initializer Timeout.
Invoke code

Execute instruction
The console provides two preset shells:
/bin/bashand/bin/sh.
In the Instance Configuration panel, configure the PreStop hook and set its timeout. Then, click Deploy.

View instance lifecycle hook logs
Currently, logs generated by `execute instruction` hooks cannot be written to function logs.
You can use the Function Log feature to view hook logs.
Log on to the Function Compute console. In the left-side navigation pane, click Functions.
In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.
On the function details page, click the Test tab, click Test Function, and then choose .
On the Function Log tab, you can view the invocation logs of the function and the Initializer hook logs. The following is an 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*******Because each function instance is cached for a period of time and is not immediately destroyed, you may not be able to view the PreStop hook logs immediately. To trigger a PreStop hook immediately, you can update the function's configuration or code. After the update is complete, you can view the PreStop hook logs in the Function Log. The following is 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*******