Function instance lifecycle hook methods

Updated at:

Implement function instance lifecycle hooks in the C# runtime so that custom code runs when an instance starts and before it is destroyed.

Background information

After you implement and configure function instance lifecycle hooks, Function Compute calls the corresponding hook when the related instance lifecycle event occurs. The C# runtime supports the Initializer and PreStop hooks. For more information, see Configure instance lifecycles.

Function instance lifecycle hooks follow the same billing rule as regular invocation requests, but you can query their execution logs only in Real-time Logs, Function Logs, or Advanced Logs. The Invocation Request List does not display hook logs. For instructions, see View the logs of instance lifecycle hooks.

Hook method signatures

  • Initializer hook

    Executed after the function instance starts successfully and before the handler runs. Function Compute ensures that the Initializer hook succeeds exactly once during the lifetime of an instance. If the first execution of your Initializer hook fails, the function invocation directly returns a failure. The next invocation creates a new function instance to run the Initializer hook.

    Note

    When the Initializer hook times out or fails, the server always returns the HTTP 200 status code. To determine whether the error is caused by an initialization failure, you must check the response header X-Fc-Error-Type:InitializationError or the errorMessage field in the response body.

  • PreStop hook

    Executed before the function instance is destroyed.

In C#, the Initializer hook and the PreStop hook have the same method signature: both take only one Context input parameter and have no return parameter. The definition is as follows:

public void FunctionName(IFcContext context);

The hook methods can also be defined as static methods:

public static void FunctionName(IFcContext context);

Simple example: streaming event handler

The following sample code shows a simple program that contains an Initializer hook and a PreStop hook:

using System;
using System.IO;
using System.Threading.Tasks;
using Aliyun.Serverless.Core;
using Microsoft.Extensions.Logging;

namespace Example
{
    public class Hello
    {
        public void Initialize(IFcContext context)
        {
            IFcLogger logger = context.Logger;
            logger.LogInformation("Initialize start");
            logger.LogInformation("Handle initializer: {0}", context.RequestId);
            logger.LogInformation("Initialize end");
        }

        public void PreStop(IFcContext context)
        {
            IFcLogger logger = context.Logger;
            logger.LogInformation("PreStop start");
            logger.LogInformation("Handle PreStop: {0}", context.RequestId);
            logger.LogInformation("PreStop end");
        }

        public async Task<Stream> StreamHandler(Stream input, IFcContext context)
        {
            IFcLogger logger = context.Logger;
            logger.LogInformation("Handle request: {0}", context.RequestId);

            MemoryStream copy = new MemoryStream();
            await input.CopyToAsync(copy);
            copy.Seek(0, SeekOrigin.Begin);
            return copy;
        }

        static void Main(string[] args){}
    }
}

Configure lifecycle hooks

Console

In Function Compute console, on the function's Configuration > Instance Configuration page, configure the lifecycle hooks. For instructions, see Configure instance lifecycles. A hook method uses the same format as the handler: AssemblyName::Namespace.ClassName::MethodName. For more information, see Handlers.

The following example is provided:

  • Initializer hook: HelloFcApp::Example.Hello::Initialize

  • PreStop hook: HelloFcApp::Example.Hello::PreStop

Serverless Devs

If you use the Serverless Devs tool, you must add the Initializer hook and the PreStop hook to the s.yaml configuration file.

  • Initializer hook configuration

    Under the function configuration, add the instanceLifecycleConfig.initializer field, which includes the following two fields: handler and timeout.

  • PreStop hook configuration

    Under the function configuration, add the instanceLifecycleConfig.preStop field, which includes the following two fields: handler and timeout.

The following example shows the configuration:

# ------------------------------------
#   Official manual: https://manual.serverless-devs.com/user-guide/aliyun/#fc3
#   Common tips: https://manual.serverless-devs.com/user-guide/tips/
#   If you have questions, ask them in the DingTalk group: 33947367
# ------------------------------------
edition: 3.0.0
name: hello-world-app
access: "default"

vars: # global variables
  region: "cn-hangzhou"

resources:
  hello_world:
    component: fc3 
    actions:       
      pre-${regex('deploy|local')}: 
        - run: dotnet publish -c Release -o ./target
          path: ./HelloWorldApp
    props:
      region: ${vars.region}              
      functionName: "start-dotnetcore-p6jp"
      description: 'hello world by serverless devs'
      runtime: "dotnetcore3.1"
      code: ./HelloWorldApp/target/
      handler: HelloWorldApp::Example.Hello::StreamHandler
      memorySize: 128
      timeout: 10
      instanceLifecycleConfig:      # extension function
        initializer:                # initializer function
          handler: HelloFcApp::Example.Hello::Initialize
          timeout: 60     
        preStop:                    # PreStop function
          handler: HelloFcApp::Example.Hello::PreStop  # function entry point
          timeout: 60               # timeout period    
      # triggers:
      #   - triggerName: httpTrigger # trigger name
      #     triggerType: http # trigger type
      #     description: 'xxxx'
      #     qualifier: LATEST # version of the service to trigger
      #     triggerConfig:
      #       authType: anonymous # authentication type. Valid values: anonymous and function
      #       disableURLInternet: false # specifies whether to disable the public network access URL
      #       methods: # HTTP access methods supported by the trigger. Valid values: GET, POST, PUT, DELETE, and HEAD
      #         - GET
      #         - POST

For information about the YAML configuration specifications of Serverless Devs, see Common Serverless Devs commands.

View the logs of instance lifecycle hooks

You can view the logs for lifecycle hook 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 Test Function 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-03-04 17:57:28FC Initialize Start RequestId: 1-65e59b07-1520da26-bf73bbb91b69
    2024-03-04 17:57:282024-03-04 09:57:28.192 1-65e59b07-1520da26-bf73bbb91b69 [info] initializer
    2024-03-04 17:57:28FC Initialize End RequestId: 1-65e59b07-1520da26-bf73bbb91b69
    2024-03-04 17:57:28FC Invoke Start RequestId: 1-65e59b07-1520da26-bf73bbb91b69
    2024-03-04 17:57:28FC Invoke End RequestId: 1-65e59b07-1520da26-bf73bbb91b69

    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-03-04 18:33:26FC PreStop Start RequestId: 93c93603-9fbe-4576-9458-193c8b213031
    2024-03-04 18:33:262024-03-04 10:33:26.077 93c93603-9fbe-4576-9458-193c8b213031 [info] preStop
    2024-03-04 18:33:26FC PreStop End RequestId: 93c93603-9fbe-4576-9458-193c8b213031