This topic describes some terms of Function Compute, including the function handler, handler function, function input parameters, log records, and troubleshooting.

Function handler

When you create a function, you must specify a handler for the function. Function Compute starts executing the function from its handler. The handler of a function in Function Compute is in the format of [File name].[Function name].

For example, when you create a Node.js function with Handler set to index.handler, Function Compute loads the handler function defined in the index.js file.

Handler function

A handler function is a function that is specified by a function handler. The handler function is similar to the main() function in on-premises development. Handler functions must comply with the programming model provided by Function Compute.

A handler function can be an event function or an HTTP function.

  • An event function can be used as a regular handler function that provides a segment of business logic code. All handler functions are event functions except those for HTTP functions.
  • An HTTP function is a function that is configured with an HTTP trigger. HTTP functions can directly process HTTP requests and return HTTP responses. They are suitable for creating web applications. The programming model for HTTP functions is different from that for event functions.

The following example shows an event function that runs in a Python runtime:

def handler(event, context):
    return 'hello world'            

In this model, the custom event parameter and the platform-defined context parameter are the input parameters of the handler function. The handler function must parse the parameters and be able to invoke other functions defined in the code. Except for the definition, the handler function has the same code organization logic as an on-premises function.

For more information about the handler function model for each programming language, see Programming languages.

Initializer function

Function Compute dynamically executes functions on different instances based on requests. When a function is invoked in succession, the function can be executed on the same instance for multiple times. An initializer function is used to ensure that functions are executed on the same instance only once.

In database-related scenarios, you can add time-consuming business logic to the initializer function, such as the business logic for creating a connection pool and loading function dependency libraries. This prevents such business logic from being repeated each time the function is invoked, and reduces the latency of the function.

Prior to handler functions, initializer functions are executed after Function Compute allocates functions to be executed on different instances. Although HTTP functions and event functions have different programming models, their corresponding initializer functions have the same programming model.

For more information about the initializer function model for each programming language, see the corresponding programming language.

Input parameters of functions

Input parameters of a function are the content passed to the function when the function is invoked. Input parameters of a function usually consist of the event parameter and the context parameter. However, the number of input parameters may vary with the programming language and environment.

  • event parameter

    The event parameter is a custom input parameter for a function. It is passed to the function in the format of byte streams. The data structure of the event parameter can be customized and can be a simple string, a JSON object, or a picture (which is binary data). Function Compute does not interpret the content of the event parameter. You must convert byte streams to the corresponding data type in the function.

    The value of the event parameter varies based on trigger conditions.

    • If a function is triggered by an event source service, the event source service passes the event to the function as the event parameter in a format predefined by Function Compute. You can write code in this format and obtain information from the event parameter. For example, when you use an Object Storage Service (OSS) event trigger, OSS passes the information about the bucket and its objects to the event parameter in the JSON format.
    • If a function is invoked by using an SDK, you can customize the event parameter between the invoker and the function code. The invoker passes data in the defined format, and the function code obtains the data in the same format. For example, you can define {"key":"val"}, a data structure in the JSON format, as the event parameter. When an invoker passes the data {"key":"val"}, the function code converts byte streams to data in the JSON format and then invokes event["key"] to obtain the value of the val field.

    The following sample code provides an example on how to use the event parameter in Python:

    import json
    def handler(event, context):
        evt = json.loads(event)
        print(evt['key'])
        return 'success'
                        
  • context parameter

    The context parameter is a function input parameter defined by Function Compute. Designed by Function Compute, the data structure of the context parameter contains the runtime information of a function. The context parameter has the following data structure:

    • Data structure
      {  
         requestId: '9cda63c3-1ac9-45ba-8a59-2593bb9bc101',  
         credentials: {    
            accessKeyId: 'xxx',    
            accessKeySecret: 'xxx',    
            securityToken: 'xxx'  
         },  
         function: {    
            name: 'xxx',    
            handler: 'index.handler',    
            memory: 512,    
            timeout: 60,    
            initializer: 'index.initializer',    
            initializationTimeout: 10  
         },  
         service: {    
            name: 'xxx',    
            logProject: 'xxx',    
            logStore: 'xxx',    
            qualifier: 'xxx',    
            versionId: 'xxx'  
         },  
         region: 'xxx',  
         accountId: 'xxx'
      }
    • Scenarios
      • Obtain the temporary AccessKey pair of a user from context.credentials and use the temporary AccessKey pair in context to access other Alibaba Cloud services, such as OSS. This prevents the use of hard-coded keys in code.
      • Obtain the basic information of the current execution from context. Such basic information includes the request ID, service name, function name, and service version or alias.
    • Example

      The following sample Python code provides an example on how to use the personal information in the context parameter to access OSS:

      import json
      import oss2
      def handler(event, context):    
          creds = context.credentials    
          auth = oss2.StsAuth(creds.access_key_id, creds.access_key_secret, creds.security_token)    
          bucket = oss2.Bucket(auth, 'oss-endpoint', 'your-bucket-name')    
          bucket.put_object('object-name', 'Awesome FC')    
          return 'success'

Log records

Function Compute is integrated with log records. Function Compute stores all function invocation records and the logs printed in function code into Logstores. You can make a record of function logs by executing the logging statements provided by Function Compute. This helps you debug the function and troubleshoot issues.

Note
  • You must configure a Logstore at the service level so that Function Compute sends function logs to the specified Logstore.
  • Function Compute automatically creates and configures Logstores for functions and services that are created in the Function Compute console.
Programming language Built-in log printing statement of the programming language Logging statement provided by Function Compute References
Node.js console.log() console.log() Display logs
Python print() logging.getLogger().info() Print logs
Java System.out.println() context.getLogger().info() Generate logs
PHP echo "" . PHP_EOL $GLOBALS['fcLogger']->info() Print logs
C# Console.WriteLine("") context.Logger.LogInformation() Print logs

Logs printed by using the built-in log printing statements of programming languages are also collected to Logstores. To facilitate log filtering, each log printed by using the logging statements provided by Function Compute is tagged with the request ID.

# Log printed by using the built-in log printing statements of programming languages
# print('hello world')
message:  hello world

# Log printed by using the logging statements provided by Function Compute
# logger.info('hello world')
message:  2020-03-13T04:06:49.099Z f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650 [INFO] hello world
            

Log elements

A function execution log contains the service name, function name, the current function version, alias, and code logs.

The following example shows the data structure of a function execution log:

__source__:  
__tag__:__receive_time__:  1584072413
__topic__:  myService
functionName:  myFunction
message:  2020-03-13T04:06:49.099Z f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650 [INFO] hello world
qualifier:  LATEST
serviceName:  myService
versionId:         
  • When the execution of a function starts, the system prints FC Invoke Start RequestId: f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650, which indicates that function execution starts.
  • When the execution of a function is complete, the system prints FC Invoke End RequestId: f84a9f4f-2dfb-41b0-9d6c-1682a2f3a650, which indicates that function execution ends.

Troubleshooting

Errors in Function Compute include two types: HandledInvocationError and UnhandledInvocationError.

  • HandledInvocationError

    Only the errors returned by the callback parameter in Node.js functions are of the HandledInvocationError type. Error information is contained in responses.

    'use strict';
      module.exports.handler = function(event, context, callback) {
        console.log('hello world');
        callback('this is error', 'hello world');
      }          

    The following example shows a response that contains error information.

    {"errorMessage":"this is error"}          
  • UnhandledInvocationError

    All errors except those of the HandledInvocationError type are of the UnhandledInvocationError type.

    The stack trace of an UnhandledInvocationError error is printed in logs. You can view the logs to find the corresponding stack trace based on the context.