This topic describes how to configure an Object Storage Service (OSS) trigger in the Function Compute console, including how to create a trigger, write a function, and test a function. In this topic, an OSS trigger is created to trigger function execution when an object is added to an OSS bucket.

Scenarios

You can configure an OSS trigger and set the prefix to source in the trigger rule. When an image is added to the source directory of a specified OSS bucket, function execution is triggered. The function resizes the image and stores the image in the processed directory of the same bucket. For example, source/serverless.png is processed, and the processed image is stored as processed/serverless.png.

Prerequisites

Create a trigger

  1. Log on to the Function Compute console.
  2. In the left-side navigation pane, click Services and Functions.
  3. In the top navigation bar, select the region where the service resides.
  4. On the Services page, find the service that you want to manage and click Functions in the Actions column.
  5. On the Functions page, click the name of the function that you want to manage.
    hanshuguanli
  6. On the function details page, click the Triggers tab, select the version or alias from the Version or Alias drop-down list, and then click Create Trigger.
  7. In the Create Trigger panel, enter the relevant information. Click OK.
    Parameter Description Example
    Trigger Type The type of the trigger. Select OSS. OSS
    Name The name of the trigger. Enter a custom trigger name. oss-trigger
    Version or Alias The version or alias of the service. The default value is LATEST. If you want to create a trigger for another version or alias, select a version or alias from the Version or Alias drop-down list on the function details page. For more information about versions and aliases of a service, see Manage versions and Manage aliases. LATEST
    Bucket Name The name of the OSS bucket. Select an OSS bucket from the drop-down list. bucket-zh****
    Object Prefix The prefix of the object that you want to match. We recommend that you configure prefixes and suffixes to avoid additional costs generated by function execution loops. If you specify the same event type for different triggers of a bucket, the prefixes or suffixes cannot be repeated. For more information, see Trigger rules. source
    Object Suffix The suffix of the object name you want to match. We recommend that you configure prefixes and suffixes to avoid additional costs generated by function execution loops. If you specify the same event type for different triggers of a bucket, the prefixes or suffixes cannot be repeated. For more information, see Trigger rules. zip

    Trigger Event

    The trigger event. Select one or more trigger events from the drop-down list. For more information about OSS events, see OSS events.

    In this example, oss:ObjectCreated:PutObject is selected.

    oss:ObjectCreated:PutObject
    Role Name The name of the role. Select AliyunOSSEventNotificationRole.
    Note After you set the preceding parameters, click OK. If you create a trigger of this type for the first time, click Authorize Now in the dialog box that appears.
    AliyunOSSEventNotificationRole

    After the trigger is created, the created trigger is displayed in the Trigger Name list.

Write a function

After you create the OSS trigger, you can write a function that is triggered to process data written to OSS bucket based on OSS events.

On the function details page, click the Function Code tab and write code in the code editor.

Preparations and sample code:

Preparations:
  • Run the following commands in the terminal to create the package.json file and install the jimp module. // Create the package.json file. npm init // Install the jimp module. npm install jimp
  • Make sure that the handler of the function is index.handler.
Sample code: 'use strict'; console.log('Loading function ...'); var oss = require('ali-oss').Wrapper; var fs = require('fs'); var jimp = require("jimp"); module.exports.handler = function (eventBuf, ctx, callback) { console.log('Received event:', eventBuf.toString()); var event = JSON.parse(eventBuf); var ossEvent = event.events[0]; // Required by OSS sdk: OSS region is prefixed with "oss-", e.g. "oss-cn-shanghai" var ossRegion = "oss-" + ossEvent.region; // Create oss client. var client = new oss({ region: ossRegion, // Credentials can be retrieved from context accessKeyId: ctx.credentials.accessKeyId, accessKeySecret: ctx.credentials.accessKeySecret, stsToken: ctx.credentials.securityToken }); // Bucket name is from OSS event client.useBucket(ossEvent.oss.bucket.name); // Processed images will be saved to processed/ var newKey = ossEvent.oss.object.key.replace("source/", "processed/"); var tmpFile = "/tmp/processed.png"; // Get object console.log('Getting object: ', ossEvent.oss.object.key) client.get(ossEvent.oss.object.key).then(function (val) { // Read object from buffer jimp.read(val.content, function (err, image) { if (err) { console.error("Failed to read image"); callback(err); return; } // Resize the image and save it to a tmp file image.resize(128, 128).write(tmpFile, function (err) { if (err) { console.error("Failed to write image locally"); callback(err); return; } // Putting object back to OSS with the new key console.log('Putting object: ', newKey); client.put(newKey, tmpFile).then(function (val) { console.log('Put object:', val); callback(null, val); return; }).catch(function (err) { console.error('Failed to put object: %j', err); callback(err); return }); }); }); }).catch(function (err) { console.error('Failed to get object: %j', err); callback(err); return }); };
Preparations:
  • Make sure that the RAM role configured for the Function Compute service to which the function belongs has the permissions to access OSS. You can log on to the Resource Access Management console to grant the RAM role the permissions to access OSS.
  • Make sure that the handler of the function is index.handler.
Sample code: # -*- coding: utf-8 -*- import oss2, json from wand.image import Image def handler(event, context): evt = json.loads(event) creds = context.credentials # Required by OSS sdk auth=oss2.StsAuth( creds.access_key_id, creds.access_key_secret, creds.security_token) evt = evt['events'][0] bucket_name = evt['oss']['bucket']['name'] endpoint = 'oss-' + evt['region'] + '.aliyuncs.com' bucket = oss2.Bucket(auth, endpoint, bucket_name) objectName = evt['oss']['object']['key'] # Processed images will be saved to processed/ newKey = objectName.replace("source/", "processed/") remote_stream = bucket.get_object(objectName) if not remote_stream: return remote_stream = remote_stream.read() with Image(blob=remote_stream) as img: with img.clone() as i: i.resize(128, 128) new_blob = i.make_blob() bucket.put_object(newKey, new_blob)
Preparations:
  • Make sure that the RAM role configured for the Function Compute service to which the function belongs has the permissions to access OSS. You can log on to the RAM console to grant the RAM role the permissions to access OSS.
  • Make sure that the handler of the function is index.handler.
Sample code: <?php use OSS\OssClient; function handler($event, $context) { $event = json_decode($event, $assoc = true); $accessKeyId = $context["credentials"]["accessKeyId"]; $accessKeySecret = $context["credentials"]["accessKeySecret"]; $securityToken = $context["credentials"]["securityToken"]; $evt = $event['events'][0]; $bucketName = $evt['oss']['bucket']['name']; $endpoint = 'oss-' . $evt['region'] . '.aliyuncs.com'; $objectName = $evt['oss']['object']['key']; $newKey = str_replace("source/", "processed/", $objectName); try { $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken); $content = $ossClient->getObject($bucketName , $objectName); if ($content == null || $content == "") { return; } $imagick = new Imagick(); $imagick->readImageBlob($content); $imagick->resizeImage(128, 128, Imagick::FILTER_LANCZOS, 1); $ossClient->putObject($bucketName, $newKey, $imagick->getImageBlob()); } catch (OssException $e) { print($e->getMessage()); } }
Preparations:
  • Add the following dependencies to the pom.xml file. <dependencies> <dependency> <groupId>com.aliyun.fc.runtime</groupId> <artifactId>fc-java-core</artifactId> <version>1.4.1</version> </dependency> <dependency> <groupId>com.aliyun.fc.runtime</groupId> <artifactId>fc-java-event</artifactId> <version>1.2.0</version> </dependency> </dependencies>
  • Make sure that the handler of the function is example.App::handleRequest.
Sample code: 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.event.OSSEvent; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class App implements StreamRequestHandler { private static final ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @Override public void handleRequest( InputStream inputStream, OutputStream outputStream, Context context) throws IOException { OSSEvent ossEvent = mapper.readValue(inputStream, new TypeReference<OSSEvent>() {}); for (OSSEvent.Event event : ossEvent.events) { outputStream.write(String.format("received %s from %s @ %s", event.eventName, event.eventSource, event.region).getBytes()); outputStream.write(String.format("received bucket %s", event.oss.bucket.arn).getBytes()); outputStream.write(String.format("received object %s and it's size is %s", event.oss.object.key, event.oss.object.size).getBytes()); } } }

Test a function

After you write the function, you must debug the function to verify that the code is correct. When an OSS event occurs, the function is automatically triggered.

An OSS event is passed to the function as an input parameter. You can manually pass an event to the function to trigger the function and test whether the code of the function is correct.

  1. On the Function Details page, click the Function Code tab, and then click the xialatubiao icon. From the drop-down list, select Configure Test Parameters.
  2. In the Configure Test Parameters dialog box, click the Create New Test Event or Edit Existing Test Event tab, and specify the Event Name and event content. Click OK.

    The event parameter is an input parameter of Function Compute. When you create an object in or delete an object from a specified OSS bucket, the event data in the JSON format is sent to the function. The following code provides an example of the event data:

    {
      "events": [
        {
          "eventName": "ObjectCreated:PutObject",
          "eventSource": "acs:oss",
          "eventTime": "2021-08-13T06:45:43.000Z",
          "eventVersion": "1.0",
          "oss": {
            "bucket": {
              "arn": "acs:oss:cn-shanghai:123456789:bucketname",
              "name": "testbucket",
              "ownerIdentity": "123456789"
            },
            "object": {
              "deltaSize": 122539,
              "eTag": "688A7BF4F233DC9C88A80BF985AB****",
              "key": "image/a.jpg",
              "size": 122539
            },
            "ossSchemaVersion": "1.0",
            "ruleId": "9adac8e253828f4f7c0466d941fa3db81161****"
          },
          "region": "cn-shanghai",
          "requestParameters": {
            "sourceIPAddress": "140.205.XX.XX"
          },
          "responseElements": {
            "requestId": "58F9FF2D3DF792092E12044C"
          },
          "userIdentity": {
            "principalId": "123456789"
          }
        }
      ]
    }           
    The following table describes the parameters in the event.
    Parameter Type Example Description
    eventName String ObjectCreated:PutObject The type of the event.
    eventSource String acs:oss The event source. Set the value to acs.oss.
    eventTime String 2021-08-13T06:45:43.000Z The time when the event occurred. The time follows the ISO 8601 standard in the yyyy-MM-ddTHH:mm:ssZ format.
    eventVersion String 1.0 The version of the event protocol.
    oss Map The content of the OSS event.
    bucket Map The details of the OSS bucket.
    name String testbucket The name of the bucket.
    arn String acs:oss:cn-shanghai:123456789:bucketname The Alibaba Cloud Resource Name (ARN) of the bucket.
    ownerIdentity String 123456789 The ID of the user that created the bucket.
    object Map The details of the OSS object.
    size Int 122539 The size of the OSS object. Unit: byte.
    deltaSize Int 122539 The variation of the size of the OSS object. Unit: byte.
    • If an object is added, the value of this parameter indicates the size of the object.
    • If an object overwrites an existing object with the same name, the value of this parameter indicates the size difference between the new object and the original object.
    eTag String 688A7BF4F233DC9C88A80BF985AB**** The tag of the object.
    key String image/a.jpg The name of the object.
    ossSchemaVersion String 1.0 The version of the OSS schema.
    ruleId String 9adac8e253828f4f7c0466d941fa3db81161**** The ID of the rule that matches the event.
    region String cn-shanghai The region in which the bucket resides.
    requestParameters Map The request parameters.
    sourceIPAddress String 140.205.XX.XX The IP address from which the request is sent.
    responseElements Map The details of the response.
    requestId String 58F9FF2D3DF792092E12044C The ID of the request.
    userIdentity Map The property of the user.
    principalId String 123456789 The ID of the Alibaba Cloud account that is used to initiate the request.
  3. On the function details page, click the Function Code tab, and then click Test Function.

References

In addition to the Function Compute console, you can configure triggers in the following ways:
  • Use the Serverless Devs tool to configure triggers. For more information, see Serverless Devs.
  • Configure triggers by using the SDK. For more information, see Supported SDKs.

To modify or delete a created trigger, see Manage triggers.