Use an Object FC access point to trigger functions

更新时间:
复制 MD 格式

You can create an Object FC Access Point in Object Storage Service (OSS) to integrate OSS with Function Compute (FC). By using an Object FC Access Point, GetObject requests automatically trigger a function. The function processes the data and returns the result to your application, which enables automated data processing and business workflows.

Process overview

The following figure illustrates how an Object FC Access Point works.

image
  1. The bucket owner creates an Object FC Access Point that is associated with a function created in Function Compute.

  2. The Object FC Access Point is automatically created based on the specified settings.

  3. The user sends a GetObject request to OSS by using the Object FC Access Point. OSS invokes the defined function to process and return requested data to the user.

Limits

Limit

Description

Creation methods

You can create an Object FC Access Point only by using the OSS console or OSS API. You cannot create an Object FC Access Point by using OSS SDKs or ossutil.

Number of Object FC Access Points

  • You can create up to 1,000 Object FC Access Points for an Alibaba Cloud account.

  • You can create up to 100 Object FC Access Points for a bucket.

Modification rule

After you create an Object FC Access Point, you can modify only its policy. You cannot modify the basic information about the Object FC Access Point, such as its name and alias.

Access methods

An Object FC Access Point does not support anonymous access.

Prerequisites

  • Object Storage Service (OSS)

    Create an OSS bucket, and create an access point in the same region as the bucket.

  • Function Compute (FC)

    1. Create the AliyunServiceRoleForFC service-linked role. If you are logging on to the Function Compute 3.0 console for the first time, follow the on-screen instructions to create the role.

    2. Create an FC function. This topic uses an event-driven function as an example. The function is triggered by GetObject API calls made through the Java, Python, or Go SDKs. When you deploy function code by using one of these SDKs, you must create a function with a compatible runtime.

      • When you deploy function code by using the Java SDK, you must create a function with the Runtime set to Java 11.

      • When you deploy function code by using the Python SDK, you must create a function with the Runtime set to Python 3.10.

      • When you deploy function code by using the Go SDK, you must create a function with the Runtime set to Go 1.

    3. Assign a role to the FC function. This role must have the oss:WriteGetObjectResponse permission. For more information, see Manage permissions for a RAM role. The following code shows the policy content:

      {
        "Statement": [
          {
            "Action": "oss:WriteGetObjectResponse",
            "Effect": "Allow",
            "Resource": "*"
          }
        ],
        "Version": "1"
      }

Procedure

Step 1: Create an Object FC Access Point

  1. Log on to the OSS console. In the left-side navigation pane, click Object FC Access Points.

  2. On the Object FC Access Points page, click Create Object FC Access Point. In the Create Object FC Access Point panel, configure the following parameters and click OK.

    Parameter

    Description

    Region

    Select the same region for the supporting access point and the OSS bucket.

    Object FC Access Point Name

    Enter a name for the Object FC Access Point.

    Supporting Access Point

    Select a previously created access point.

    OSS API

    Select GetObject.

    Function to Invoke

    Select the target FC function, and then select the FC Function Supports Range GetObject Requests check box.

    FC Function Version

    Select a version of the function. The LATEST version is used by default.

  3. Grant the required permissions.

    Important

    If this is the first time you use an Object FC Access Point, click Access Point Permission Delegation to grant the necessary permissions. Otherwise, the Object FC Access Point cannot access the function.

    The Object FC Access Point enters the Creating state. The access point becomes ready in about 10 minutes. You can use the access point only after its status changes to Created. Click Go to RAM for Authorization to grant permissions, and then click Complete.

Important

Function Compute is triggered only when you call the GetObject API by using the Object FC Access Point Alias. If you use the alias to call an API other than GetObject, the request is automatically routed to the underlying OSS access point, and its permission policy applies.

Step 2: Write the function code

  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. Choose Function Details > Code. In the code editor, replace the content of the index.py file with the following sample code. This example uses a function with the Python 3.10 runtime. For more code samples, see Write request functions.

    # -*- coding: utf-8 -*-
    import io
    from PIL import Image
    import oss2
    import json
    # Example: China (Qingdao) region endpoint.
    endpoint = 'http://oss-cn-qingdao.aliyuncs.com'
    fwd_status = '200'
    # FC function entry
    def handler(event, context):
        evt = json.loads(event)
        creds = context.credentials
        # Do not forget security_token
        auth = oss2.StsAuth(creds.access_key_id, creds.access_key_secret, creds.security_token)
        headers = dict()    
        event_ctx = evt["getObjectContext"]
        route = event_ctx["outputRoute"]
        token = event_ctx["outputToken"]
        print(evt)
        endpoint = route
        service = oss2.Service(auth, endpoint)
        # Create a 200x200 red PNG image.
        # Write the transformed image to the GetObject response.
        image = Image.new('RGB', (200, 200), color=(255, 0, 0))
        transformed = io.BytesIO()
        image.save(transformed, "png")
        resp = service.write_get_object_response(route, token, fwd_status, transformed.getvalue(), headers)
        print('status: {0}'.format(resp.status))
        print(resp.headers)
        return 'success'
  4. On the Code tab, choose to open a terminal window. Run the following command to update the OSS Python SDK version.

    pip install oss2 "pyopenssl>=23.0.0" "urllib3==1.26.15" "charset-normalizer==2.1.1"  -t .
  5. Click Deploy.

Step 3: Use the Object FC Access Point

After you create an Object FC Access Point, OSS automatically generates an alias for it. You can use this alias to call the GetObject API.

  1. Log on to the OSS console. In the left-side navigation pane, click Object FC Access Points.

  2. On the Object FC Access Points page, find the Object FC Access Point and copy its alias from the Object FC Access Point Alias column.

  3. Use one of the following methods to call the GetObject API by using the Object FC Access Point Alias to verify that the function is triggered automatically.

    SDK

    1. Accessing resources with an Object FC Access Point Alias requires OSS SDK for Python 2.18.3 or later.

      pip3 install oss
    2. Run the following Python sample script locally.

      Before you run the script, replace the endpoint and bucket_name placeholders, and the parameters within the bucket.get_object_to_file method, with your actual values.

      • endpoint: The access endpoint of OSS.

      • bucket_name: The Object FC Access Point Alias that you copied in the previous step.

      • bucket.get_object_to_file: Replace yourObjectName with the object name and yourLocalFile with the destination local file path.

      # -*- coding: utf-8 -*-
      import oss2
      from oss2.credentials import EnvironmentVariableCredentialsProvider
      # Obtain access credentials from environment variables. Before you run this code, make sure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
      auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
      # Use the public endpoint of the Object FC Access Point to access resources.
      endpoint = "https://oss-cn-qingdao.aliyuncs.com"
      # Use the internal endpoint of the Object FC Access Point to access resources.
      # endpoint = "https://oss-cn-qingdao-internal.aliyuncs.com"
      # Specify the Object FC Access Point Alias.
      bucket_name = "****-d54843759613953fe5b17b6f16d7****-opapalias"
      bucket = oss2.Bucket(auth, endpoint=endpoint, bucket_name=bucket_name)
      # Set yourObjectName to the full path of the object. The path does not include the bucket name.
      # Set yourLocalFile to the local file path. If the file exists, it is overwritten. If not, a new file is created.
      bucket.get_object_to_file('yourObjectName', 'yourLocalFile')

    ossutil CLI

    Install ossutil and run the following command to test the configuration.

    ossutil cp oss://****-d54843759613953fe5b17b6f16d7****-opapalias/demo.txt /Users/demo/Desktop/demo.txt

    REST API

    When you send a GetObject request to an OSS resource, use the copied Object FC Access Point Alias as the Host header value. The following example shows a sample request:

    GET /ObjectName HTTP/1.1
    Host: fc-ap-01-3b00521f653d2b3223680ec39dbbe2****-opapalias.oss-cn-qingdao.aliyuncs.com
    Date: GMT Date
    Authorization: SignatureValue