After you implement and configure instance lifecycle hooks, Function Compute invokes the corresponding hook when a relevant instance lifecycle event occurs. The Node.js runtime currently supports Initializer and PreStop instance lifecycle hooks.
Usage notes
Instance lifecycle hooks are billed in the same way as standard invocation requests. However, their execution logs can only be viewed in Real-time Logs, Function Logs, or Advanced Logs. Hook logs are not displayed in the Invocation Request List. For more information, see View instance lifecycle hook logs.
Initializer hook
The initializer hook runs after a function instance starts but before the request handler runs. Function Compute ensures that an Initializer hook is successfully executed only once during the instance lifetime. If an Initializer hook fails on its first execution, the function invocation also fails. For the next invocation, a new function instance is created to execute the initializer hook.
When an Initializer hook times out or fails, the server returns an HTTP 200 status code. To determine if the error was caused by an initialization failure, you must check the X-Fc-Error-Type:InitializationError
response header or the `errorMessage` field in the response body.
The Initializer hook has only one context input parameter. The following sample code shows a simple Initializer hook.
ES modules
This example supports only Node.js 18 and later runtimes.
export const initialize = async (context) => {
console.log('initializer');
return "";
}
CommonJS modules
exports.initialize = function(context, callback) {
console.log('initializer');
callback(null, "");
};
initialize
is the name of the Initializer hook. This name must match the value that you configure for the Initializer Hook in the Function Compute console. For example, if you set the Initializer Hook for a function to index.initialize
, Function Compute loads the initialize
method from the index.js
file.
Method signature
The only input parameter is
context
, which provides your FC function with its runtime context during invocation.The hook does not return a value. You must call `return` or `callback` in your code to end the function execution.
PreStop hook
A PreStop hook runs before a function instance is destroyed. The method signature is the same as that of an Initializer hook.
The following sample code provides an example of a simple PreStop hook.
ES modules
This example supports only Node.js 18 and later runtimes.
export const preStop = async (context) => {
console.log('preStop');
return "";
}
CommonJS modules
module.exports.preStop = function(context, callback){
console.log('preStop');
callback(null, "");
}
Configure lifecycle hooks
Configure using the console
In the Function Compute console, go to the tab of the FC function to configure the Initializer Hook and PreStop Hook. For more information, see Configure instance lifecycles. The format for a hook is [File name.Method name]
. Examples:
Set Initializer Hook to
index.initialize
. This specifies theinitialize
method in theindex.js
file.Set PreStop Hook to
index.preStop
, which specifies thepreStop
method in theindex.js
file.
Configure using the Serverless Devs tool
If you use the Serverless Devs tool, you can add the Initializer Hook and PreStop Hook to the s.yaml
configuration file.
Configure the Initializer hook
Add the instanceLifecycleConfig.initializer field under the props configuration. This field includes the handler and timeout fields.
Configure the PreStop hook
Add the instanceLifecycleConfig.preStop field under the props configuration. This field includes the handler and timeout fields.
The following is a sample configuration.
edition: 3.0.0
name: hello-world-app
access: default # The alias of the key.
resources:
hello_world:
component: fc3 # The name of the component. Serverless Devs itself is like a game console and does not have specific business capabilities. Components are like game cartridges. You insert different cartridges into the console to get different features. Similarly, you use different components to implement different business capabilities.
# actions: # Custom execution logic. For more information about actions, see: https://docs.serverless-devs.com/serverless-devs/yaml#%E8%A1%8C%E4%B8%BA%E6%8F%8F%E8%BF%B0actions
props:
region: cn-hangzhou # For more information about how to use variables, see: https://docs.serverless-devs.com/serverless-devs/yaml#%E5%8F%98%E9%87%8F%E8%B5%8B%E5%80%BC
functionName: nodejs-fc-hooks
description: "Node.js lifecycle hooks by serverless devs"
runtime: nodejs20
code: ./code
handler: index.handler
memorySize: 128
timeout: 30
instanceLifecycleConfig:
preStop:
handler: index.preStop
timeout: 3
initializer:
handler: index.initialize
timeout: 3
internetAccess: true
logConfig: auto
For more information about the YAML configuration specifications for Serverless Devs, see Common Serverless Devs commands.
View the logs of instance lifecycle hooks
You can view the logs for lifecycle hook in 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 Function tab, click Test Function, and then choose .
On the Logs tab, you can view function invocation logs and Initializer logs. Example:
2023-09-06 11:18:10FC Initialize Start RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7 2023-09-06 11:18:10load code for handler:index.initialize 2023-09-06 11:18:102023-09-06 11:18:10 1-64f7ef72-64caf1ff0046194d9a26bbd7 [verbose] initializer 2023-09-06 11:18:10FC Initialize End RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7 2023-09-06 11:18:10FC Invoke Start RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7 2023-09-06 11:18:10load code for handler:index.handler 2023-09-06 11:18:10FC Invoke End RequestId: 1-64f7ef72-64caf1ff0046194d9a26bbd7
Each function instance is cached for a period of time and not destroyed immediately, you cannot view the logs for PreStop hooks right away. To quickly trigger the 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:
2023-09-06 11:08:10FC PreStop Start RequestId: 944bca62-b209-47a1-9e48-2723647bce0a 2023-09-06 11:08:10load code for handler:index.preStop 2023-09-06 11:08:102023-09-06 11:08:10 944bca62-b209-47a1-9e48-2723647bce0a [verbose] preStop 2023-09-06 11:08:10FC PreStop End RequestId: 944bca62-b209-47a1-9e48-2723647bce0a
Sample program
Function Compute provides a sample MySQL program that uses Initializer and PreStop hooks. In this example, the Initializer hook retrieves MySQL database configurations from environment variables, creates MySQL connections, and tests connectivity. The PreStop hook closes the MySQL connections.
For more information, see nodejs14-mysql.
References
For more information about instance lifecycle hooks, see Configure instance lifecycles.