All Products
Search
Document Center

CDN events trigger

Last Updated: Sep 16, 2019

With 1,200+ nodes distributed across the globe, Alibaba Cloud CDN (Content Delivery Network) enables users to effectively reduce website response time to milliseconds, ensure smooth video streaming and handle large volumes of traffic. As a low-cost and scalable service, Alibaba Cloud CDN comes without any long-term contracts or minimum usage commitments. Based on the seamless integration of Alibaba Cloud Function Compute and Alibaba Cloud CDN, FC can receive and process different kinds of CDN events. The user can create CDN events trigger with filters to handle events from a specific domain, and process these events with specific functions. For example, the user can create CDN events trigger and some logging functions to handle CDN cache purge event from “www.taobao.com” domain.

CDN events trigger usage scenario:

  1. When content is pre-warmed or purged, “CachedObjectsPushed “ or “CachedObjectsRefreshed “ event will fire and invoke user’s function. So the user can get notified in time instead of keeping polling status from CDN.
  2. When “CachedObjectsBlocked “ event fired, user’s function can be invoked to delete the original content in time, instead of involving CDN team to handle it.
  3. When CDN log file generated, “LogFileCreated “ event will fire and invoke user’s function to copy or process log file immediately.

CDN events

CDN will convert the user specified event to JSON string, and invoke the function. Events supported by CDN events trigger as below:

Event Name Event Version Filter Key Description
CachedObjectsRefreshed 1.0.0 domain See RefreshObjectCaches API for details.
CachedObjectsBlocked 1.0.0 domain CDN resource blocked
CachedObjectsPushed 1.0.0 domain See PushObjectCache API for details.
LogFileCreated 1.0.0 domain See DescribeCdnDomainLogs API for details.

CDN event schema:

CachedObjectsRefreshed,CachedObjectsPushed with CachedObjectsBlocked event schema:

  1. {
  2. "events": [
  3. {
  4. "eventName": "CachedObjectsRefreshed",//event name
  5. "eventVersion": "1.0.0", // event version
  6. "eventSource": "cdn", // event source name
  7. "region": "cn-hangzhou", //default region:"cn-hangzhou"
  8. "eventTime": "2018-03-16T14:19:55+08:00",//refresh start time
  9. "traceId": "cf89e5a8-7d59-4bb5-a33e-4c3d08e25acf",//id of event source, used for debugging
  10. "resource": {
  11. "domain": "example.com"
  12. },
  13. "eventParameter": {
  14. "objectPath": [
  15. "/2018/03/16/13/33b430c57e7.mp4",//content URI
  16. "/2018/03/16/14/4ff6b9bd54d.mp4"//content URI
  17. ],
  18. "createTime": 1521180769,//refresh start time
  19. "domain": "example.com",//domain
  20. "completeTime": 1521180777,//refresh complete time
  21. "objectType": "File", //refresh type, including File and Directory
  22. "taskId": 2089687230 //refresh task ID
  23. },
  24. "userIdentity": {
  25. "aliUid": "1xxxxxxxxxx" //account id
  26. }
  27. }
  28. ]
  29. }

LogFileCreated event schema:

  1. {
  2. "events": [
  3. {
  4. "eventName": "LogFileCreated",//event name
  5. "eventSource": "cdn",//event source name
  6. "region": "cn-hangzhou",//default region:"cn-hangzhou"
  7. "eventVersion": "1.0.0",//event versino
  8. "eventTime": "2018-06-14T15:31:49+08:00",//event start time
  9. "userIdentity": {
  10. "aliUid": "1xxxxxxxxxxxx" //account id
  11. },
  12. "resource": {
  13. "domain": "example.com"//domain
  14. },
  15. "eventParameter": {
  16. "domain": "example.com",//domain
  17. "endTime": 1528959900, //end time of log file
  18. "fileSize": 1788115,//log file size
  19. "filePath": "http://cdnlog.cn-hangzhou.oss.aliyun-inc.com/www.aliyun.com/2017_12_27/www.aliyun.com_2017_12_27_0800_0900.gz?OSSAccessKeyId=xxxx&Expires=xxxx&Signature=xxxx",//log file path
  20. "startTime": 1528959600 //start time of log file
  21. },
  22. "traceId": "c6459282-6a4d-4413-894c-e4ea39686738" //id of event source, used for debugging
  23. }
  24. ]
  25. }

Configuration a CDN events trigger:

Trigger example:cdn_events_trigger.yml

  1. triggerConfig:
  2. eventName: "LogFileCreated"
  3. eventVersion: "1.0.0"
  4. notes: "cdn events trigger test"
  5. filter:
  6. domain: ["www.taobao.com","www.tmall.com"]

Trigger parameter descriptions

  • eventName is CDN event which invokes the function execution, can not be changed after creation.
  • eventVersion is CDN event version which invokes the function execution, can not be changed after creation.
  • notes Descriptions.
  • filter Filters (Need to have at least one filter).

filter schema:

  1. filter:
  2. key1: [value avalue b]
  3. key2: [value cvalue d]

Demos

There are 3 ways to set CDN events trigger for a given function, Function Compute console, fcli and SDK:

Demo 1: Console operations

This example describes how to use Function Compute Console to set CDN events trigger. For more information about how to create triggers, please see Use event source service and Create a trigger.

Log in on Function Compute console,select region and service as you need. Please check Create a service if you need to create service.

Set a trigger while creating a function
  1. Click Create Function, choose Empty Function, then click Next.
  2. Select CDN Events Trigger and configure the parameters as below:createFunctionTrigger
  3. Configure Service Name, Function Name, Function Description and Runtime parameters, select In-line Edit and paste the following python runtime sample code,then click Next.
  1. import json
  2. import logging
  3. LOG = logging.getLogger()
  4. def handler(event, context):
  5. logger = logging.getLogger()
  6. eventObj = json.loads(event)["events"]
  7. logger.info("EventCount: %d" % len(eventObj))
  8. logger.info("eventName: %s" % eventObj[0]["eventName"])
  9. logger.info("eventVersion: %s" % eventObj[0]["eventVersion"])

4.(Optional)Configure Permissions,click Next, check it all the information is error-free, then click Create.

Set a trigger after function creation

  1. Select a function in the service, select the Triggers tab, then click Create Trigger.
  2. Select CDN Events Trigger and configure the parameters as below, then click OK.createTrigger

Demo 2: fcli operations

First, create a yaml file as Trigger Config. A trigger with trigger config yaml file below will invoke some function when CDN receiving logFileCreated(version 1.0.0) event from www.taobao.com and www.tmall.com domains:

  1. triggerConfig:
  2. eventName: "LogFileCreated"
  3. eventVersion: "1.0.0"
  4. notes: "cdn events trigger test"
  5. filter:
  6. domain: ["www.taobao.com","www.tmall.com"]

Command to create trigger under the function folder:

  1. mkt triggerName -t cdn_events -r acs:ram::account_id:role/AliyunCDNEventNotificationRole -s acs:cdn:*:account_id -c TriggerConfig.yaml

For more about fcli, please see fcli.

Demo 3: SDK programming

Using fc-python-sdk as an example to describe how to set a CDN events trigger by SDK. Function Compute provides fc-nodejs-sdk and fc-java-sdk as well.

Create trigger Python code

  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 = 'cdn_events'
  9. source_arn = 'acs:cdn:*:<Your Account ID>'
  10. invocation_role = 'acs:ram::<Your Account ID>:role/<Your Invocation Role>'
  11. trigger_config = {
  12. 'eventName': 'logFileCreated',
  13. 'eventVersion': '1.0.0',
  14. 'notes': 'notes',
  15. 'filter': {
  16. 'domain' : ['www.taobao.com'],
  17. }
  18. }
  19. client.create_trigger(service_name, function_name, trigger_name, trigger_type, trigger_config, source_arn, invocation_role)

Function Python code

  1. import json
  2. import logging
  3. LOG = logging.getLogger()
  4. def handler(event, context):
  5. logger = logging.getLogger()
  6. eventObj = json.loads(event)["events"]
  7. logger.info("EventCount: %d" % len(eventObj))
  8. logger.info("eventName: %s" % eventObj[0]["eventName"])
  9. logger.info("eventVersion: %s" % eventObj[0]["eventVersion"])

Please contact us for more information.