This topic describes how to implement lifecycle hooks for function instances in the Python runtime environment.

Background information

After you configure a lifecycle hook for a function instance, Function Compute invokes the hook when a related lifecycle event for the instance occurs. The following lifecycle hooks can be configured for a function instance: Initializer, PreFreeze, and PreStop. For more information, see Lifecycle hooks for function instances.

The billing rules for the 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, Instance Logs, or Advanced Logs. The logs for lifecycle hooks are not displayed in Call Request List. For more information, see View the logs of instance lifecycle hooks..

Note Python 2.7 and earlier versions do not support the PreFreeze hook.

Initializer hooks

An Initializer hook is invoked after a function instance is started and before a handler runs. Function Compute ensures that the Initializer hook is successfully invoked only once in the lifecycle of a function instance. If your Initializer hook fails to be executed, an error is returned for the function invocation. When you invoke the function next time, the system creates another function instance to execute the Initializer hook.

An Initializer hook consists of the context input parameter and can be invoked in the same manner as a handler.

The following sample code provides an example on how to define a simple Initializer method:

def initialize(context):
    print("initialize invoked")

initialize is the method name of the Initializer hook. The name must be the same as the value of the Initializer Hook parameter that you configured in the Function Compute console. For example, if the value of the Initializer Hook parameter for the function is index.initialize, Function Compute loads the initialize method that is defined in index.py after the Initializer hook is configured.

Method signature

  • The input parameter context specifies the runtime context that is provided when the Function Compute function is invoked.
  • No value is returned.

PreFreeze hooks

A PreFreeze hook is executed before a function instance is frozen. The method signature of a PreFreeze hook is the same as the method signature of an Initializer hook.

The following sample code provides an example of a simple PreFreeze hook:

def preFreeze(context):
    print("preFreeze invoked")

PreStop hooks

A PreStop hook is executed before a function instance is destroyed. The method signature of the PreStop hook is the same as the method signature of an Initializer hook.

The following sample code provides an example of a simple PreStop hook:

def preStop(context):
    print("preStop invoked")

Configure lifecycle hooks

Use the Function Compute console

You can configure the Initializer Hook, PreFreeze Hook, and PreStop Hook parameters on the function configuration page in the Function Compute console. For more information, see Function instance lifecycle.

The format of a hook is [File name.Method name]. For example, if you set Initializer Hook to index.initialize, the initialize method in the index.py file is used.

shengmingzhouqi

Use Serverless Devs

If you use Serverless Devs to configure a lifecycle hook, you must add the configurations of Initializer and PreStop hooks to the s.yaml file.
  • Configure the Initializer hook

    Add the initializer and initializationTimeout fields to the function configurations.

  • Configure the PreStop hook

    Add the instanceLifecycleConfig.preStop field, including handler and timeout, to the function parameter.

Sample code:

edition: 1.0.0          #  The version of the YAML syntax. The version complies with the semantic versioning specifications.
name: hello-world       #  The name of the project.
access: default         #  The alias of the key.

services:
  fc-deploy-test: # The name of the module.
    component: devsapp/fc  # The name of the component.
    props:                 # The property value of the component.
      region: cn-hangzhou   # The ID of the region.
      service:             # The configurations of the service.
        name: fc-deploy-service    # The name of the service.
        description: dem component # A brief description of the service.
      function:                       # The configurations of the function.
        name: fc-base-service         # The name of the function.
        description: 'this is test'   # A brief description of the function.
        codeUri: './code'             # The location of the code.
        handler: 'index.handler'      # The handler of the function. The format varies based on the language.
        memorySize: 128               # The memory size for the function.
        runtime: python3              # The runtime environment.
        timeout: 60                   # The timeout period for the execution of the function.
        initializationTimeout: 20     # The timeout period for the execution of the Initializer method.
        initializer: index.my_initializer # The Initializer method.
        instanceLifecycleConfig:      # The extension function.
          preStop:                    # The PreStop hook.
            handler: index.preStop        # The function handler.
            timeout: 60               # The timeout period.

For more information about the YAML syntax of Serverless Devs, see Serverless Devs commands.

View the logs of instance lifecycle hooks.

You can view the logs for lifecycle hook in Function Logs.

  1. Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
  2. In the top navigation bar, select a region. On the Services page, click the desired service.
  3. On the Functions page, click the name of the desired function. On the Function Details page that appears, click the Test Function tab.
  4. On the Test Function tab, click Test Function. Choose Logs > Function Logs.
    On the Function Logs tab, you can view the invocation logs, and the logs for the Initializer hooks and PreFreeze hooks of the function. Example:
    2022-10-09 19:26:17 FunctionCompute dotnetcore3.1 runtime inited.
    2022-10-09 19:26:17 FC Initialize Start RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Initialize start
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Handle initializer: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Initialize end
    2022-10-09 19:26:17 FC Initialize End RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 FC Invoke Start RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Handle request: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 FC Invoke End RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 FC PreFreeze Start RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] PreFreeze start
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] Handle PreFreeze: 793ad2f1-9826-4d9a-90d9-5bf39e******
    2022-10-09 19:26:17 2022-10-09 19:26:17 793ad2f1-9826-4d9a-90d9-5bf39e****** [INFO] PreFreeze end
    2022-10-09 19:26:17 FC PreFreeze End RequestId: 793ad2f1-9826-4d9a-90d9-5bf39e******
    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. Example:
    2022-10-09 19:32:17 FC PreStop Start RequestId: 03be685c-378b-4736-8b08-a67c1d*****
    2022-10-09 19:32:17 2022-10-09 19:32:17 03be685c-378b-4736-8b08-a67c1d***** [INFO] PreStop start
    2022-10-09 19:32:17 2022-10-09 19:32:17 03be685c-378b-4736-8b08-a67c1d***** [INFO] Handle PreStop: 03be685c-378b-4736-8b08-a67c1d*****
    2022-10-09 19:32:17 2022-10-09 19:32:17 03be685c-378b-4736-8b08-a67c1d***** [INFO] PreStop end
    2022-10-09 19:32:17 FC PreStop End RequestId: 03be685c-378b-4736-8b08-a67c1d*****

Sample programs

Function Compute provides the sample of a MySQL database that uses an Initializer hook and a PreStop hook. In this example, the Initializer hook is used to obtain the MySQL database configurations from environment variables, create the MySQL database connections, and test the connectivity. The PreStop hook is used to close the MySQL connection.

For more information, see python3-mysql.