All Products
Search
Document Center

Function Compute:Context

Last Updated:Apr 25, 2024

This topic describes the context in Java runtimes of Function Compute. Examples are provided in this topic.

What is a context?

When Function Compute runs a function, the system passes a context object to the method that is used to execute the function. The context object contains information about the invocation, service, function, and execution environment. The following table describes the parameters that are contained in a context.

Parameter

Description

RequestId

The request ID. You can record the request ID and use it to troubleshoot errors.

Function

The basic information about the invoked function, such as the name, handler, memory, and timeout period.

Credentials

The temporary AccessKey pair that Function Compute obtains by assuming your service-linked role. The temporary AccessKey pair is valid for 36 hours. You can use credentials in your code to access related services such as Object Storage Service (OSS). This way, you can access the services without the need to write your AccessKey pair in the function code. For more information, see Grant Function Compute permissions to access other Alibaba Cloud services.

Logger

The logger that is encapsulated by Function Compute.

Service

The basic information of the called service.

Definition:

package com.aliyun.fc.runtime;

public interface Context {

    public String getRequestId();

    public Credentials getExecutionCredentials();

    public FunctionParam getFunctionParam();

    public FunctionComputeLogger getLogger();

    public Service getService();

    # public OpenTracing getTracing();

    public int getRetryCount();
}

Example: Use a temporary key to access OSS

The following sample program provides an example on how to use a temporary key in a context to upload a file to Object Storage Service (OSS). For detailed code, see java11-oss.

package example;

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

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.Credentials;
import com.aliyun.fc.runtime.StreamRequestHandler;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

public class App implements StreamRequestHandler {

    @Override
    public void handleRequest(
            InputStream inputStream, OutputStream outputStream, Context context) throws IOException {

        // The name of the bucket, which must be created in advance. 
        String bucketName = "my-bucket";
        // Specify the endpoint of the region where the bucket resides. We recommend that you use an internal endpoint. In this example, the internal endpoint https://oss-cn-hangzhou-internal.aliyuncs.com of the China (Hangzhou) region is used. 
        String endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com";

        // Obtain the key information. Before you execute the function, make sure that the service to which the function belongs is configured with a role that is attached with the AliyunOSSFullAccess policy. 
        // We recommend that you use the AliyunFCDefaultRole role. 
        Credentials creds = context.getExecutionCredentials();

        // Create an OSSClient instance. 
        /*
        The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. 
        We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
        In this example, the Access Key pair is obtained from the context. 
        */
        OSS ossClient = new OSSClientBuilder().build(endpoint, creds.getAccessKeyId(), creds.getAccessKeySecret(), creds.getSecurityToken());

        // Specify a byte array. 
        byte[] content = "Hello FC".getBytes();
        // Specify the name of the bucket and the full path of the object. In this example, the bucket name is examplebucket and the full path of the object is exampledir/exampleobject.txt. Do not include the bucket name in the full path of the object. 
        ossClient.putObject(bucketName, "exampledir/exampleobject.txt", new ByteArrayInputStream(content));

        // Close your OSSClient. 
        ossClient.shutdown();

        outputStream.write(new String("done").getBytes());
    }
}