Dumping CDN Logs to OBS

CDN records access logs of all domain names (excluding those deleted if you have enabled the enterprise project function). You can view and download the logs of the last 30 days on the CDN console and analyze the access to your resources in detail.

CDN works with FunctionGraph to dump CDN logs to OBS buckets for a longer period, so that you can perform customized data analysis to better understand the CDN service quality and the user access details, and improve your decision making.

This section describes how to call an API to create a Python 3.6 function and a timer trigger to periodically dump CDN logs to OBS.

Prerequisites

Currently, logs can only be dumped to OBS buckets in CN North-Beijing4. Prepare an OBS bucket in CN North-Beijing4.

Procedure

  1. Create an agency.
    1. Log in to the HUAWEI CLOUD console. On the homepage of the management console, choose Service List > Management & Governance > Identity and Access Management.
    2. In the navigation pane, choose Agencies and click Create Agency in the upper right corner.
    3. On the Create Agency page, set the parameters as follows:
      • Agency Name: Enter FG_TO_CDN.
      • Agency Type: Select Cloud service.
      • Cloud Service: Select FunctionGraph.
      • Validity Period: Select Unlimited.

    4. Click Next to grant permissions to the FG_TO_CDN agency.
      • Permissions: Select OBS OperateAccess and CDN LogsReadOnlyAccess.

    5. Click Next and configure the application scope.
      • Scope: Select All resources.

    6. Click OK to complete the agency configuration.
  2. Prepare a FunctionGraph environment.
    1. Log in to the HUAWEI CLOUD console. On the homepage of the management console, choose Service List > Compute > FunctionGraph. In the upper left corner of the page, select the CN North-Beijing4 region.
    2. In the upper right corner of the page, click Create Function.
      • Template: Click Create from scratch.
      • Function name: Enter a function name, for example, cdn_to_obs.
      • App: Select default.
      • Agency: Select FG_TO_CDN.
      • Enterprise Project: Select default.
      • Runtime: Select Python 3.6.
      • Code Entry Mode: Select Default code.

    1. Click Create Function. On the displayed code editing page, copy the sample code to the online IDE.

      To dump logs of multiple domain names, create a FunctionGraph function for each domain name.

    2. Click the Configuration tab.
      • Execution Timeout: Timeout interval for executing the function. If the execution times out, the function will be forcibly stopped. You are advised to set this parameter to 900.

        If you find that the number of dumped logs is incorrect, submit a service ticket to FunctionGraph to increase the execution timeout period.

      • url: Set the value to https://cdn.myhuaweicloud.com/v1.0/cdn/logs (URL for downloading CDN logs).
      • domain_name: Set the value to the acceleration domain name whose logs need to be dumped.
      • obsAddress: Set the value to the domain name of the OBS bucket for storing logs.
      • destBucket: Set the value to the name of the OBS bucket for storing logs.

      1. Click Save in the upper right corner.
    3. Create a trigger. On the function configuration page, click the Triggers tab and click Create Trigger on the right.
      • Trigger Type: Select Timer.
      • Timer Name: Enter a timer name, for example, Timer-0001.
      • Rule: Select Cron expression.
      • Cron expression: Enter 0 0 8 * *? in the text box below Rule. Logs will be dumped at 08:00 a.m. every day.
      • Enable Trigger: Turn on the switch.

      1. Click OK to complete the configuration of the timer trigger.
    4. Create a test event. In the upper right corner of the function configuration page, select Configure test event from the Select test event drop-down list.
      • Configure Test Event: Select Create new test event.
      • Event Template: Select blank-template.
      • Event Name: Enter an event name, for example, test.
      • Enter {"message":"CDNLog-OBS"} in the text box below Event Name.

      1. Click Save to create the test event.
    5. Test the function. On the function details page, select test from the Select test event drop-down list in the upper right corner and click Test.

  3. Check whether the configuration is successful.
    1. Log in to the HUAWEI CLOUD console. On the homepage of the management console, choose Service List > Storage > Object Storage Service.
    2. Click the bucket for storing logs. In the navigation pane on the left, choose Objects.
    3. Check whether the access path of logs is Bucket name/Acceleration domain name/Log date/Log file.

    • If you use the sample code, only logs of the previous day will be dumped. If no log is generated for the acceleration domain name on the previous day, no log file will be dumped to the OBS bucket.
    • You will be charged for logs dumped to the OBS bucket. For details, see OBS Billing.
  4. Stop log dump.
    1. Log in to the HUAWEI CLOUD console. On the homepage of the management console, choose Service List > Compute > FunctionGraph. In the upper left corner of the page, select the CN North-Beijing4 region.
    2. In the navigation pane, choose Functions > Function List, and click the name of the function created in 2.
    3. On the function details page, click the Triggers tab.

    1. Click Disable next to the target trigger.

Sample Code

The code is as follows:

# -*- coding:utf-8 -*-
import requests
import datetime
import time
import os
import sys
import json

from com.obs.client.obs_client import ObsClient

from urllib.parse import urlparse

if sys.version_info.major == 2 or not sys.version > '3':
    import httplib
else:
    import http.client as httplib

current_file_path = os.path.dirname(os.path.realpath(__file__))
# Adds the current path to search paths to import third-party libraries.
sys.path.append(current_file_path)

TEMP_ROOT_PATH = "/tmp/"  # Downloads a file from OBS to this directory.
region = 'china'  # This parameter does not need to be changed and will be used when FunctionGraph accesses OBS.
secure = True  # This parameter does not need to be changed and will be used when FunctionGraph accesses OBS.
signature = 'v4'  # This parameter does not need to be changed and will be used when FunctionGraph accesses OBS.
port = 443  # This parameter does not need to be changed and will be used when FunctionGraph accesses OBS.
path_style = True  # This parameter does not need to be changed and will be used when FunctionGraph accesses OBS.


def handler(event, context):
    logger = context.getLogger()
    queryDate = context.getUserData('queryDate')
    if queryDate is None:
        yesterday = datetime.date.today() + datetime.timedelta(-1)
        queryDate = yesterday.strftime("%Y-%m-%d")
        timeStamp = int(time.mktime(yesterday.timetuple()) * 1000)
    else:
        date = datetime.datetime.strptime(queryDate, "%Y-%m-%d")
        timeStamp = int(time.mktime(date.timetuple()) * 1000)

    pageSize = 20
    pageNumber = 1

    requests.packages.urllib3.disable_warnings()
    start(context, queryDate, timeStamp, pageSize, pageNumber)


def start(context, queryDate, timeStamp, pageSize, pageNumber):
    logger = context.getLogger()
    logUrl = context.getUserData('url')
    domainName = context.getUserData('domain_name')

    params = {'query_date': timeStamp, 'domain_name': domainName, 'page_size': pageSize, 'page_number': pageNumber, 'enterprise_project_id':'ALL'}
    headers = {'Content-Type': 'application/json;charset=UTF-8', 'X-Auth-Token': context.getToken()}
    res = requests.get(logUrl, params=params, headers=headers, verify=False)
    if res.status_code != 200:
        logger.info("query log urls: " + res.url + ", error: " + res.text)
        return ("query log urls: " + res.url + ", error: " + res.text)

    resJson = json.loads(res.text)
    logger.info(res.text)
    total = resJson['total']
    i = 0
    for val in resJson['logs']:
        i += 1
        logger.info(val["link"])

        url = urlparse(val["link"])
        netlocs = url.netloc.split(":")
        conn = httplib.HTTPConnection(netlocs[0], int(netlocs[1]))
        conn.request('GET', url.path + "?" + url.query)
        objName = os.path.join(val["domain_name"], queryDate, val["name"])
        put_content_to_obs(context, objName, conn.getresponse())

    if pageSize * pageNumber < total:
        start(context, queryDate, timeStamp, pageSize, pageNumber + 1)


def put_content_to_obs(context, objName, content):
    ak = context.getAccessKey()
    sk = context.getSecretKey()
    obsAddress = context.getUserData('obsAddress')
    destBucket = context.getUserData('destBucket')
    TestObs = ObsClient(access_key_id=ak, secret_access_key=sk,
                        is_secure=secure, server=obsAddress, signature=signature, path_style=path_style, region=region,
                        ssl_verify=False, port=port,
                        max_retry_count=5, timeout=20)
    resp = TestObs.putContent(destBucket, objName, content=content)
    if resp.status < 300:
        print('requestId:', resp.requestId)
    else:
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)