All Products
Search
Document Center

Function Compute:Lifecycle hooks for function instances

Last Updated:Sep 30, 2024

This topic describes how to implement lifecycle hooks for function instances in a Java runtime.

Background

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

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

Hook method signature

Initializer hook signature

An Initializer hook is executed after a function instance is started before a handler runs. Function Compute ensures that an Initializer hook is successfully invoked only once in the lifecycle of a function instance. If the initializer hook fails to be executed, the system retries the Initializer hook until the Initializer hook is successfully invoked, and then runs your handler. To make sure that the Initializer hook can be repeatedly retried, configure the Initializer hook properly.

An Initializer hook contains only the context input parameter and can be invoked in the same manner as an event handler.

To use an Initializer hook, the FunctionInitializer interface must be inherited and the initialize method in the interface must be implemented. The following sample code provides an example on how to define the FunctionInitializer interface:

package com.aliyun.fc.runtime;

import java.io.IOException;

/**
 * This is the interface for the initialization operation
 */
public interface FunctionInitializer {

    /**
     * The interface to handle a function compute initialize request
     *
     * @param context The function compute initialize environment context object.
     * @throws IOException IOException during I/O handling
     */
    void initialize(Context context) throws IOException;
}

PreStop hook signature

A PreStop hook is executed before a function instance is destroyed. To use a PreStop hook, the PreStopHandler interface must be inherited and the preStop method in the interface must be implemented. The following sample code provides an example on how to define the PreStopHandler interface:

package com.aliyun.fc.runtime;

import java.io.IOException;

/**
 * This is the interface for the preStop operation
 */
public interface PreStopHandler {

    /**
     * The interface to handle a function compute preStop request
     *
     * @param context The function compute preStop environment context object.
     * @throws IOException IOException during I/O handling
     */
    void preStop(Context context) throws IOException;
}

Example: StreamRequestHandler

package example;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;
import com.aliyun.fc.runtime.FunctionInitializer;
import com.aliyun.fc.runtime.PreStopHandler;

public class App implements StreamRequestHandler, FunctionInitializer, PreStopHandler {
    @Override
    public void initialize(Context context) throws IOException {
        context.getLogger().info("initialize start ...");
    }

    @Override
    public void handleRequest(
            InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
        context.getLogger().info("handlerRequest ...");
        outputStream.write(new String("hello world\n").getBytes());
    }

    @Override
    public void preStop(Context context) throws IOException {
        context.getLogger().info("preStop start ...");
    }
}

Configure lifecycle hooks

Use the Function Compute console

You can configure a lifecycle hook on the function details page in the Function Compute console. The format of a hook is [Package name].[Class name]::[Method name].FC The following figure shows an example:db_java_lifecycle

  • In the preceding example, Initializer Hook is set to example.App::initialize, which indicates that the initialize method in the App.java file of the example package is implemented.

  • PreStop Hook is set to example.App::preStop, which indicates that the preStop method in the App.java file of the example package is implemented.

Use Serverless Devs

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

  • Initializer hook

    Add instanceLifecycleConfig.initializer, including the handler and timeout fields, to function.

  • PreStop hook

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

Sample code:

# ------------------------------------
#   Official manual: https://manual.serverless-devs.com/user-guide/aliyun/#fc3
#   Tips: https://manual.serverless-devs.com/user-guide/tips/
# If you have any questions, join the DingTalk group 33947367 for technical support.
# ------------------------------------
edition: 3.0.0
name: hello-world-app
access: "default"

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

resources:
  hello_world:
    component: fc3 
    actions:       
      pre-${regex('deploy|local')}: 
        - run: mvn package -DskipTests
          path: ./
    props:
      region: ${vars.region}              
      functionName: "start-java-1xqf"
      description: 'hello world by serverless devs'
      runtime: "java8"
      code: ./target/HelloFCJava-1.0-SNAPSHOT-jar-with-dependencies.jar
      handler: example.App::handleRequest
      memorySize: 128
      timeout: 10
      instanceLifecycleConfig:      # The extension function
        initializer:                # The Initializer hook
          handler: example.App::initialize
          timeout: 60     
        preStop:                    # The PreStop hook
          handler: example.App::preStop  # The function handler
          timeout: 60               # The timeout period.
 

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

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

Sample program

  • java11-mysql: The sample program that is provided by Function Compute. This program provides an example of configuring Initializer and PreStop hooks.

    In this program, an Initializer hook in a Java runtime is used to obtain database configurations from environment variables and establish MySQL connections. A PreStop hook is used to terminate MySQL connections.