This topic shows you how to configure PreFreeze and PreStop functions by using the Function Compute console, Funcraft, and SDKs.

Background information

Feature overview

Usage notes

  • The input parameters of PreFreeze and PreStop functions do not include the event parameter.
  • PreFreeze and PreStop functions have no return values. Return logic appended to PreFreeze and PreStop functions does not take effect.
  • You can configure PreStop functions in all runtime environments. However, you cannot configure PreFreeze functions in the Python, PHP, and C# runtime environments.
  • If you use the Java runtime environment, you must update fc-java-core to version 1.4.0 or later. Otherwise, you cannot use PreFreeze and PreStop functions.

Use the Function Compute console

When you use the console to create a function, you cannot configure PreFreeze and PreStop functions in Function Compute. You can configure the PreFreeze and PreStop functions when you update the function.

  1. Log on to the Function Compute console.
  2. In the top navigation bar, select a region.
  3. In the left-side navigation pane, click Services and Functions. In the Services pane, click the service that you require.
  4. On the Functions tab, find the function for which you want to configure PreFreeze and PreStop functions and click Modify Configurations in the Actions column.
    Modify the configurations of the function
  5. On the Modify Configurations page, turn on the extension function switch as required, specify the function handler and timeout period, and then click Submit.
    Configure extension functions
    Note You must specify a function handler and a timeout period for each extension function. The function handler is in the format of [File name].[Extension function name]. Assume that you set the handler of the PreStop function to index.preStopHandler when you create a function in the Python runtime environment. In this case, the file name is index.py and the name of the PreStop function is preStopHandler.
  6. After you specify the handler of the extension function, implement the function when you execute the code.
    1. On the Functions tab, click the name of the function that you require.
    2. Click the Code tab. In the Code Management section, enter the code of the extension function.
      For example, if you set the handler of the PreStop function to index.preStopHandler, you must implement the preStopHandler function. For more information about the sample code of extension functions in different runtime environments, see the Sample code section in this topic.Code of the extension function

Use Funcraft

The following code provides an example on how to use Funcraft to configure PreFreeze and PreStop functions:

  codeUri: . /
  ......
  InstanceLifecycleConfig:
    PreFreeze:
      Handler: index.PreFreeze
      Timeout: 60
    PreStop:
      Handler: index.PreStop
      Timeout: 60

To disable an extension function, leave the Handler parameter of the extension function unspecified. Otherwise, the function is not updated by default. For example, to disable the PreFreeze function, deploy and update the function based on the following configuration. In this case, the Timeout parameter of the PreFreeze function is invalid.

  codeUri: . /
  ......
  InstanceLifecycleConfig:
    PreFreeze:
      Handler: ""
      Timeout: 60
    PreStop:
      Handler: index.PreStop
      Timeout: 60

Use SDKs

You can use SDKs to deploy and update extension functions. The following code provides an example on how to use the SDK for Go to configure PreStop and PreFreeze functions when you create a function:

package main

import (
  "github.com/aliyun/fc-go-sdk"
  "fmt"
  "os"
)

func main() {
  client, _ := fc.NewClient(
    os.Getenv("ENDPOINT"),
    "2016-08-15", 
    os.Getenv("ACCESS_KEY_ID"),
    os.Getenv("ACCESS_KEY_SECRET"),
  )

  serviceName := "ExtensionService"
  functionName := "ExtensionFunction"
  createFunctionInput := fc.NewCreateFunctionInput(serviceName).WithFunctionName(functionName)
  // Configure PreStop and PreFreeze functions.
  preStopHook := fc.NewLifecycleHook().WithHandler("index.preStop").WithTimeout(int32(30))
  preFreezeHook := fc.NewLifecycleHook().WithHandler("index.preFreeze").WithTimeout(int32(10))
  instanceLifecycle := fc.NewInstanceLifecycleConfig().WithPreStopHook(preStopHook).WithPreStopHook(preFreezeHook)
  createFunctionOutput, err := client.CreateFunction(createFunctionInput.WithInstanceLifecycleConfig(instanceLifecycle))
  if err ! = nil {
    fmt.Fprintln(os.Stderr, err)
  } else {
    fmt.Printf("CreateFunction response: %s \n", createFunctionOutput)
  }
  return
}

Sample code

The following part describes the sample code of extension functions in different runtime environments. The PreFreeze function is defined in the same way as the PreStop function in the same runtime environment. Therefore, this topic provides only the sample code of the PreStop function.

 
# -*- coding: utf-8 -*-

import logging

def handler(event, context):
    logger = logging.getLogger()
    logger.info('handler start')
    return "ok"

def pre_stop(context):
    logger = logging.getLogger()
    logger.info('preStop start')
'use strict';

var counter = 0;
module.exports.handler = function(event, context, callback) {
    counter += 2;
    callback(null, String(counter));
};

module.exports.preFreeze = function(ctx, callback) {
    counter += 1;
    callback(null, "");
};
<?php      

$counter = 0;
function fc_func_pre_stop($context) {
    sleep(2);
}

function fc_func_handler($event, $context) {
    global $counter;
    $counter += 2;
    return $counter;
}
 ?>
      
using System;
using System.IO;
using Aliyun.Serverless.Core;

using Microsoft.Extensions.Logging;
namespace Aliyun.Serverless.TestHandlers
{
    public class PreStopAndPojoCounter
    {
        public int counter;
        public PreStopAndPojoCounter()
        {
            this.counter = 0;
        }

        public void PreStop(IFcContext context)
        {
            // todo
        }

        // todo
    }
}
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.PreFreezeHandler;

import java.io.IOException;

public class PreFreezeNormal implements PreFreezeHandler {
    @Override
    public void preFreeze(Context context) throws IOException {
        // todo
    }
}
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.StreamRequestHandler;
import com.aliyun.fc.runtime.PreStopHandler;

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

public class PreStopSleepStreamNormal implements StreamRequestHandler, PreStopHandler {
    public PreStopSleepStreamNormal() {}

    @Override
    public void preStop(Context context) throws IOException {
        // todo
    }

    @Override
    public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
        // todo
    }
}