All Products
Search
Document Center

OSS event trigger

Last Updated: Apr 21, 2019

Alibaba Cloud Object Storage Service (OSS) allows you to securely store massive amounts of data in the cloud at low costs. With HTTP RESTful APIs, you can easily store and access data on the Internet.

Function Compute integrates seamlessly with OSS. You can configure functions for different types of events so that OSS can automatically call a function after a certain event is detected. For example, you can configure a function to process PutObject events. When you call an OSS PutObject API operation to upload an image to OSS, the corresponding function is triggered to process this image. In the following figure, an image/voice processing function can be used to flexibly call services to process the image/voice data, and then write the results back to the storage services. During this process, you only need to write the function code. With this code, OSS can simultaneously process large amounts of data in real time and with high reliability.

oss-triggers-fc

OSS events

After an event is detected, OSS encodes the event information into a JSON string and passes it to an event processing function. The following table lists the events that are supported by OSS.

Event Description Remarks
oss:ObjectCreated:PutObject A function is triggered after the OSS PutObject API operation creates an object. PutObject is used to upload files. For more information, see PutObject.
oss:ObjectCreated:PutSymlink A function is triggered after the OSS PutSymlink API operation creates an object. PutSymlink is used to create a symbolic link that points to the TargetObject on OSS. You can use this symbolic link to access the TargetObject. For more information, see PutSymlink.
oss:ObjectCreated:PostObject A function is triggered after the OSS PostObject API operation creates an object. PostObject is used to upload files to a specific bucket using the HTML form. For more information, see PostObject.
oss:ObjectCreated:CopyObject A function is triggered after the OSS CopyObject API operation creates an object. CopyObject is used to copy an existing object in OSS into another object. For more information, see CopyObject.
oss:ObjectCreated:InitiateMultipartUpload A function is triggered after the OSS InitialMultipartUpload API operation is executed. Before you transmit data in Multipart Upload mode, you must call the InitialMultipartUpload API operation to notify OSS to initialize a Multipart Upload event. For more information, see InitiateMultipartUpload.
oss:ObjectCreated:UploadPart A function is triggered after the OSS UploadPart API operation is executed. After a Multipart Upload event is initialized, you can upload data in parts based on the specified object name and Upload ID. For more information, see UploadPart.
oss:ObjectCreated:UploadPartCopy A function is triggered after the OSS UploadPartCopy API operation is executed. UploadPartCopy is used to upload a part by copying data from an existing object. For more information, see UploadPartCopy.
oss:ObjectCreated:CompleteMultipartUpload A function is triggered after the OSS CompleteMultipartUpload API operation is executed. After all data parts are uploaded, you must call the CompleteMultipartUpload API operation to complete the Multipart Upload of the entire file. For more information, see CompleteMultipartUpload.
oss:ObjectCreated:AppendObject A function is triggered after the OSS AppendObject API operation is executed. AppendObject is used to upload files in appending mode. For more information, see AppendObject.
oss:ObjectCreated:* A function is triggered after any of the preceding ObjectCreated API operations is executed. A function is triggered after any of the preceding ObjectCreated API operations is executed.
oss:ObjectRemoved:DeleteObject A function is triggered after the OSS DeleteObject API operation deletes an object. DeleteObject is used to delete a certain object. For more information, see DeleteObject.
oss:ObjectRemoved:DeleteObjects A function is triggered after the OSS DeleteObjects API operation deletes multiple objects. DeleteObjects is used to delete files in batches.
oss:ObjectRemoved:AbortMultipartUpload A function is triggered after the OSS AbortMultipartUpload API operation stops a Multipart Upload event. AbortMultipartUpload is used to stop a Multipart Upload event based on the Upload ID that you provide. For more information, see AbortMultipartUpload.

OSS event format

When an OSS event triggers a function to execute, the OSS event format serves as the input parameter event of the function. You can obtain the event information in the code. For more information about the event parameter, see Parameter event. The following example is the Node.js-compiled function code for obtaining the bucket name:

  1. module.exports.handler = function(event, context, callback) {
  2. var event = JSON.parse(event);
  3. var bucketName = event.events[0].oss.bucket.name;
  4. console.log('bucketName: '+ bucketName);
  5. callback(null, bucketName);
  6. };
  1. {
  2. "events": [
  3. {
  4. "eventName": "ObjectCreated:PutObject",
  5. "eventSource": "acs:oss",
  6. "eventTime": "2017-04-21T12:46:37.000Z",
  7. "eventVersion": "1.0",
  8. "oss": {
  9. "bucket": {
  10. "arn": "acs:oss:cn-shanghai:123456789:bucketname",
  11. "name": "testbucket",
  12. "ownerIdentity": "123456789",
  13. "virtualBucket": ""
  14. },
  15. "object": {
  16. "deltaSize": 122539,
  17. "eTag": "688A7BF4F233DC9C88A80BF985AB7329",
  18. "key": "image/a.jpg",
  19. "size": 122539
  20. },
  21. "ossSchemaVersion": "1.0",
  22. "ruleId": "9adac8e253828f4f7c0466d941fa3db81161e853"
  23. },
  24. "region": "cn-shanghai",
  25. "requestParameters": {
  26. "sourceIPAddress": "140.205.128.221"
  27. },
  28. "responseElements": {
  29. "requestId": "58F9FF2D3DF792092E12044C"
  30. },
  31. "userIdentity": {
  32. "principalId": "123456789"
  33. }
  34. }
  35. ]
  36. }

Configure an OSS trigger

Example

oss_events_trigger.yml

  1. triggerConfig:
  2. events:
  3. - oss:ObjectCreated:PostObject
  4. - oss:ObjectCreated:PutObject
  5. filter:
  6. key:
  7. prefix: source/

Parameters

  • events: Indicates the type of an OSS event.
  • filter: Filters OSS events. Only OSS objects that meet the filtering condition can trigger a function. This parameter has a key attribute:
    • key: Indicates the key supported by the filter. This attribute contains the following attributes:
      • prefix: Matches the prefix.
      • suffix: Matches the suffix.

Create OSS trigger

The following examples describe how to create an OSS trigger for a function using the Function Compute consoleFunction Compute console, the command-line tool fcli, or the SDK.

This example demonstrates how to create an OSS trigger using the console. You can either create a trigger when creating a function, or after the function is created. For more information about triggers and how to create a trigger, see Introduction and Create a trigger.

Log on to the Function Compute consoleFunction Compute console and select a required region and service. If no services are available, create a service. For more information, see Create a service.

Example 1. Create an OSS trigger in the console

Create a trigger when creating a function

  1. Click Create Function. On the displayed page, select the Empty Function template.

  2. Set Trigger Type to Object Storage Service (OSS), configure it as follows, and then click Next.

    Trigger

  3. Set the required function information. Select In-line Edit, paste the following sample code for the handler in the Python runtime environment, and then click Next.

    1. # -*- coding: utf-8 -*-
    2. import json
    3. import logging
    4. def handler(event, context):
    5. logger = logging.getLogger()
    6. eventObj = json.loads(event)["events"]
    7. logger.info("eventName: %s" % eventObj[0]["eventName"])
    8. logger.info("bucketName: %s" % eventObj[0]["oss"]["bucket"]["name"])
    9. return "success"
  4. (Optional) Configure the required permissions and click Next. Verify that all settings are correct and click Create.

Create a trigger after a function is created

  1. Select a function, click the Triggers tab, and then click Create Trigger.

  2. On the displayed page, set Trigger Type to Object Storage Service (OSS), set the required parameters, and then click OK.

    Create a trigger

Example 2. Create OSS trigger by using fcli

First, you must create a .yaml file with the Trigger Config, such as config.yaml. If an object is uploaded to the /source directory of a bucket using the PUT or POST method, content in the .yaml file for triggering a function is as follows:

  1. triggerConfig:
  2. events:
  3. - oss:ObjectCreated:PostObject
  4. - oss:ObjectCreated:PutObject
  5. filter:
  6. key:
  7. prefix: source/

Create a trigger in the directory of the corresponding function.

  1. mkt test_oss_trigger -t oss -r acs:ram::account_id:role/AliyunOSSEventNotificationRole -s acs:oss:cn-region:account_id:bucketName -c config.yaml
  • -r —invocation-role string: Sets a role for triggering the function.
  • -s —source-arn string: Specifies the event source, such as acs:oss:cn-shanghai:12345678:myBucketName.
  • -c —trigger-config string: Sets the configuration file for the trigger.
  • -t —type string: Specifies the trigger type. The default trigger is the OSS trigger.

For more information about how to use fcli, see fcli.

Example 3. Create OSS trigger by using SDK

  1. client = fc2.Client(
  2. endpoint='<Your Endpoint>',
  3. accessKeyID='<Your AccessKeyID>',
  4. accessKeySecret='<Your AccessKeySecret>')
  5. service_name = 'serviceName'
  6. function_name = 'functionName'
  7. trigger_name = 'triggerName'
  8. trigger_type = 'oss'
  9. source_arn = 'acs:oss:{0}:{1}:{2}'.format('<region>', '<account_id>', '<self.code_bucket>')
  10. invocation_role = 'acs:ram::<Your Account ID>:role/<Your Invocation Role>'
  11. trigger_config = {
  12. 'events': ['oss:ObjectCreated:*'],
  13. 'filter': {
  14. 'key': {
  15. 'prefix': 'source',
  16. }
  17. }
  18. }
  19. client.create_trigger(service_name, function_name, trigger_name, trigger_type, trigger_config, source_arn, invocation_role)