After you create an Object Storage Service (OSS) trigger, you can start to define a function. This topic describes how to define a function in the Function Compute console, so that OSS events can trigger the function to perform custom data processing in an OSS bucket.

Prerequisites

Create a trigger

Procedure

  1. Log on to the Function Compute console.
  2. In the top navigation bar, select your region.
  3. In the left-side navigation pane, click Service/Function.
  4. Find the target function in the target service and click the name of the function.
  5. Click the Code tab and write code in the code editor.

    The following section shows the sample code:

     'use strict';
     console.log('Loading function ...');
     var oss = require('ali-oss').Wrapper;
     var fs = require('fs');
     var jimp = require("jimp");
     module.exports.resize = 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
         });
     }; 
     # -*- coding: utf-8 -*-
     import oss2, json
     from wand.image import Image
     def resize(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) 
    <?php
      use OSS\OssClient;
      function resize($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());
         }
     } 

Event format

event is an input parameter in Function Compute. When an object is created or deleted in a specified OSS bucket, the event data will be sent to the bound function in JSON format. The following section shows the format:

{
  "events": [
    {
      "eventName": "ObjectCreated:PutObject",
      "eventSource": "acs:oss",
      "eventTime": "2017-04-21T12:46:37.000Z",
      "eventVersion": "1.0",
      "oss": {
        "bucket": {
          "arn": "acs:oss:cn-shanghai:123456789:bucketname",
          "name": "testbucket",
          "ownerIdentity": "123456789",
          "virtualBucket": ""
        },
        "object": {
          "deltaSize": 122539,
          "eTag": "688A7BF4F233DC9C88A80BF985AB7329",
          "key": "image/a.jpg",
          "size": 122539
        },
        "ossSchemaVersion": "1.0",
        "ruleId": "9adac8e253828f4f7c0466d941fa3db81161e853"
      },
      "region": "cn-shanghai",
      "requestParameters": {
        "sourceIPAddress": "140.205.128.221"
      },
      "responseElements": {
        "requestId": "58F9FF2D3DF792092E12044C"
      },
      "userIdentity": {
        "principalId": "123456789"
      }
    }
  ]
}           

What to do next

Test a function