Resolving Alibaba Cloud API Signature Issues for Bill Analysis¶
Compared with purchasing private hosts, buying resources from multiple public clouds requires a fundamentally different cost mindset. Purchasing private hosts is a one-time investment. Whether you use them or not after the purchase, and whether they perform well or poorly, there is no ongoing impact on your future spending. With public cloud resources, on the other hand, you have to constantly remind yourself: although the initial investment is small, every day that passes incurs another day of costs. Therefore, we urgently need a way to view at a glance the cost breakdown and bill analysis of spending across multiple cloud resources.
Collecting Alibaba Cloud Cost API Data¶
Taking Alibaba Cloud bills as an example, to collect and analyze Alibaba Cloud cost and billing information, you need a solid understanding of the Transactions and Billing Management APIs. When calling Alibaba Cloud APIs, the most troublesome part is the API signature mechanism. Alibaba Cloud provides a dedicated explanation in its general documentation, but the documentation only explains the signature mechanism itself, which can be quite daunting for developers with limited experience. So how can we collect billing cost data based on such incomplete documentation?
API Request Fundamentals¶
Simply put, calling an Alibaba Cloud API is an HTTP request (mostly GET, and this example is also based on GET requests), except that a batch of parameters must be appended. For example, a request to view snapshots looks like this:
http://ecs.aliyuncs.com/?SignatureVersion=1.0&Format=JSON&Timestamp=2017-08-07T05%3A50%3A57Z&RegionId=cn-hongkong&AccessKeyId=xxxxxxxxx&SignatureMethod=HMAC-SHA1&Version=2017-12-14&Signature=%2FeGgFfxxxxxtZ2w1FLt8%3D&Action=DescribeSnapshots&SignatureNonce=b5046ef2-7b2b-11e7-a3c5-00163e001831&ZoneId=cn-hongkong-b
The common parameters required by a request (that is, the parameters needed to call any API) are:
SignatureVersion # Signature algorithm version, currently 1.0
Format # Response message format, JSON or XML, default is XML
Timestamp # Request timestamp, UTC time, e.g.: 2021-12-16T12:00:00Z
AccessKeyId # Account key ID
SignatureMethod # Signature method, currently HMAC-SHA1
Version # Version number, in date form, e.g.: 2017-12-14; varies by product
Signature # The most difficult signature to get right
SignatureNonce # Unique random number to prevent network attacks. Different requests must use different random numbers.
Apart from Signature, the other parameters are relatively easy to obtain, and some are even fixed values. For details, refer to the Alibaba Cloud documentation
In addition to the common parameters, you also need the request parameters of the specific interface (Action). The parameters of each Action interface can be found in the API documentation of the corresponding product, such as QuerySettleBill
Since Signature is derived from both the common parameters and the interface parameters, it is more complex.
Constructing the Canonicalized Query String¶
- Create a dict
In Python, the dict type is used to express the one-to-one correspondence of parameters. Create a dict and write the request parameters into it.
D = {
'BillingCycle':str(time.strftime("%Y-%m", time.gmtime())),
'Action':'QuerySettleBill',
# 'PageNum':'5',
'Format':'JSON',
'Version':'2017-12-14',
'AccessKeyId':'LTAI5tLumx55Vui4WJwZJneK',
'SignatureMethod':'HMAC-SHA1',
'MaxResults' : '300',
# 'NextToken':"", #?
'Timestamp':str(time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())),
'SignatureVersion':'1.0'
# 'SignatureNonce':str_seed
}
- Sort
Because the signature requires uniqueness, including ordering, the parameters must be sorted by name.
# Because the signature requires uniqueness, including ordering, the parameters must be sorted by name
sortedD = sorted(D.items(),key=lambda x: x[0])
- URL encoding
Since the standard request string must use the UTF-8 character set, some characters in the request parameter names and values that do not conform to the specification must be URL-encoded. The specific rules are:
Characters A-Z, a-z, 0-9, and the characters "-", "_", ".", "~" are not encoded;
Other characters are encoded in the %XY format, where XY is the hexadecimal representation of the character's ASCII code. For example, the English double quotation mark (") corresponds to %22;
Extended UTF-8 characters are encoded in the %XY%ZA... format;
English spaces ( ) must be encoded as %20, not as the plus sign (+).Note: Libraries that support URL encoding (such as java.net.URLEncoder in Java) generally follow the MIME type rules of "application/x-www-form-urlencoded". During implementation, you can use this approach directly and then replace the plus sign (+) in the encoded string with %20, the asterisk (*) with %2A, and %7E back to the tilde (~) to obtain the encoded string described by the above rules.
Here we use the urllib library in Python to perform encoding:
# Use the urllib library in Python to perform encoding
def percentEncode(str):
res = urllib.parse.quote(str.encode('utf8'), '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
- Generate the canonicalized query string
# Generate the canonicalized query string
canstring = ''
for k,v in sortedD:
canstring += '&' + percentEncode(k) + '=' + percentEncode(v)
Constructing the StringToSign¶
The rule is:
StringToSign=
HTTPMethod + "&" +
percentEncode("/") + "&" +
percentEncode(CanonicalizedQueryString)
So in this example:
Calculating the HMAC Value¶
# access_key_secret
access_key_secret = '<access_key_secret>'
# Calculate the HMAC value
h = hmac.new((access_key_secret + "&").encode('utf8'), stringToSign.encode('utf8'), sha1)
Calculating the Signature Value¶
# Calculate the signature value to generate the signature
signature = base64.encodestring(h.digest()).strip()
At this point, the signature is generated.
Adding the Signature¶
So in this example, the final request URL is:
# Make the final API call
url = 'http://business.aliyuncs.com/?' + urllib.parse.urlencode(D)
http://business.aliyuncs.com/?BillingCycle=2021-12&Action=QuerySettleBill&Format=JSON&Version=2017-12-14&AccessKeyId=LTAI5tLumx55Vui4WJwZJneK&SignatureMethod=HMAC-SHA1&MaxResults=300&Timestamp=2021-12-16T12%3A27%3A58Z&SignatureVersion=1.0&SignatureNonce=0.30196531140307337&NextToken=&Signature=zFb4631sSGONvAeWD3xCIovMeoM%3D
You can paste it directly into a browser to access it, and the result is:
Complete Example¶
import sys, datetime
import time
import json
import urllib
import hmac
from hashlib import sha1
import base64
import random
import requests
# Common parameters required by a request (the parameters needed to call any API)
D = {
'BillingCycle':str(time.strftime("%Y-%m", time.gmtime())),
'Action':'QuerySettleBill',
# 'PageNum':'5',
'Format':'JSON',
'Version':'2017-12-14',
'AccessKeyId':'<AccessKeyId>',
'SignatureMethod':'HMAC-SHA1',
'MaxResults' : '300',
# 'NextToken':"", #?
'Timestamp':str(time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())),
'SignatureVersion':'1.0'
# 'SignatureNonce':str_seed
}
# Current time
now_time = str(time.strftime("%Y-%m-%d", time.gmtime()))
# Connect to the local DataKit
datakit = DFF.SRC('datakit')
# Use the urllib library in Python to perform encoding
def percentEncode(str):
res = urllib.parse.quote(str.encode('utf8'), '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
# Get bills
def getBill():
# Current position of bill records
next_token = ""
# Loop through bills and write them to DataKit
for i in range(10000):
random.seed()
# Unique random number to prevent network replay attacks. Use different random values for different requests.
D["SignatureNonce"] = str(random.random())
D["NextToken"] = next_token
# Because the signature requires uniqueness, including ordering, the parameters must be sorted by name
sortedD = sorted(D.items(),key=lambda x: x[0])
# Generate the canonicalized query string
canstring = ''
for k,v in sortedD:
canstring += '&' + percentEncode(k) + '=' + percentEncode(v)
# Generate the canonicalized query string
stringToSign = 'GET&%2F&' + percentEncode(canstring[1:])
# access_key_secret
access_key_secret = '<access_key_secret>'
# Calculate the HMAC value
h = hmac.new((access_key_secret + "&").encode('utf8'), stringToSign.encode('utf8'), sha1)
# Calculate the signature value to generate the signature
signature = base64.encodestring(h.digest()).strip()
# Add the signature
D['Signature'] = signature
# Make the final API call
url = 'http://business.aliyuncs.com/?' + urllib.parse.urlencode(D)
# Request Alibaba Cloud bill costs
print(url)
Technology Route Selection¶
Architecture Concept¶
This approach uses Crontab to periodically schedule Python scripts that fetch Alibaba Cloud bill data and write it into the MySQL storage engine, with Grafana displaying the bill analysis data. You can obtain the corresponding Bills templates from Grafana Dashboards to simplify operations. The following technical research is conducted based on this architecture concept.
Technical Research¶
In the current open-source visualization landscape, Grafana is the most popular and offers the most visualization templates. Kibana is also a decent visualization platform, but compared with Grafana, Kibana is better suited to the ELK architecture. Based on our requirements, Kibana is not a good fit. Grafana is also an open-source visualization tool that can be used on a variety of data stores, and is a feature-rich replacement for Graphite-web that helps us easily create and edit dashboards. It includes a unique Graphite target parser that makes metric and function editing easy. Users can create comprehensive charts with smart axis formats (such as lines and points). Grafana also comes with a built-in alerting engine, allowing us to attach conditional rules to dashboard panels and send triggered alerts to selected notification endpoints (for example, email, Slack, PagerDuty, custom webhooks), and more. This also happens to meet our need for Alibaba Cloud cost alerting. However, Grafana is designed to analyze and visualize metrics such as system CPU, memory, disk, and I/O utilization. Grafana does not support full-text data queries, which makes the user experience less friendly. After some searching in the open-source community, we found that "Guance" also exactly meets our requirements. It not only combines all the advantages of Grafana and Kibana but also has many unique features. Moreover, it offers Serverless online programming and scheduling, which solves the pain point of being unable to manage the scheduling of our Python scripts for fetching Alibaba Cloud bill data. In addition, as an open-source commercial product, its UI aesthetics leave Grafana in the dust. Moreover, the free quota it provides is just enough to meet our needs, andwhen we encounter usage issues, we can also get official product support.
Technical Comparison¶
| Grafana | Guance | |
|---|---|---|
| Complexity of use | Installation and configuration are cumbersome, and an additional storage engine is required | Complete installation with a single command, out-of-the-box within 30 minutes |
| Documentation completeness | Grafana's official website has complete documentation, but there is little Chinese documentation, which is a headache for those who are not good at English. | Very complete Chinese documentation and a large number of use case guidance courses. |
| Community activity | Active community, strong development and maintenance team, fast version upgrades and iterations. | A commercial product with a very active community, strong development and maintenance team, quick problem resolution, and fast version upgrades and iterations. |
| Feature completeness | 54 data sources, 173+ dashboards, rich dashboard plugins such as heat maps, line charts, graphs and other display formats, and supports simple alerting, etc. | 200+ data source integrations, 200+ dashboards, support for multiple operating systems, a standard unified DQL for querying multiple data types, and unified management of metric data, log data, APM-layer data, infrastructure, containers, middleware, and network performance. Also features powerful anomaly detection, advanced permission capabilities, and support for complex alert rule configuration, etc. |
| Development trends | Market share is trending upward, and the project itself is developing and improving rapidly. | As a mature commercial product and a leader in the observability field, its market share is trending upward, and it is developing and improving rapidly. |
| Performance | Low resource usage | Unified management, low resource usage, binary data files, high transmission efficiency, and low bandwidth usage. |
| Serverless programming | None | Sandbox environment based on Python 3.x |
| Cost | Free | Free |
| Service | Community support | Professional technical team support |
Requirements Matching¶
From the comparison above, we found that using "Guance" can greatly reduce usage costs and makes installation, configuration, and management very convenient. Compared with Grafana, which only serves as a display platform and still needs an external storage engine as its data source, "Guance" uniformly collects and manages multiple types of data—metric data, log data, APM-layer data, infrastructure, containers, middleware, network performance, and more—which is far more convenient and eliminates cumbersome steps such as installing and maintaining a storage engine. Grafana, on the other hand, lacks complete Chinese documentation, which can be a headache for those who are not strong in English. In contrast, Guance has complete Chinese documentation and a large number of use case guidance videos, making it easier to get started with the product and focus on the requirements themselves. As a commercial product, "Guance" even when used for free,can provide professional technical team support and has a large community where you can exchange usage insights with many other product users. In terms of features, it goes beyond Grafana with powerful anomaly detection, advanced permission capabilities, and support for complex alert rule configuration, so requirements beyond cost analysis can also be well implemented. Moreover, "Guance" enables unified component management through visualization, with low resource usage, binary data files, high transmission efficiency, and low bandwidth consumption. In addition, for those who care about aesthetics, the product UI design of "Guance" features a refreshing minimalist style that stands out. Therefore, for our requirements, the clear choice is to build with "Guance".
Implementing Cost Management with Guance¶
Deployment Instructions¶
The example Linux version is: CentOS Linux release 7.8.2003 (Core)
Collect all Alibaba Cloud bill cost data through a single server.
Prerequisites¶
Install DataKit¶
Before using "Guance" to monitor hosts, you need to install DataKit. DataKit is the officially released data collection application that supports the collection of hundreds of data types. By configuring collection sources, you can collect a variety of data in real time, such as host, process, container, log, application performance, and user access.
Before installing DataKit, you need to register a "Guance" account. After registration, log in to the "Guance" workspace to obtain the DataKit installation command and deploy your first DataKit.
Obtain the Installation Command¶
You can log in to the "Guance" workspace, click "Integrations" > "DataKit" in sequence, and select the DataKit installation mode as shown below. Then copy the "Install Command" and run it on the host.
-
Installation OS: Linux
-
System type: X86 amd64
-
DataWay address: OpenWay
Run the Installation Command on the Host¶
Open a command-line terminal, log in to the server, and run the copied "Install Command". After installation completes, Install Success is displayed, and you can use the link provided in the DataKit installation result to view DataKit's installation status, manual, and update records.
Getting Started with "Guance"¶
After DataKit is successfully installed, the host object collector hostobject is enabled by default. You can directly view the host where DataKit was just installed under "Infrastructure" > "Hosts" in the "Guance" workspace, including host status, hostname, operating system, CPU utilization, MEM utilization, single-core CPU load, and more. You can also click the host to view more details.
Install the Func Portable Edition¶
System and Environment Requirements¶
The host running DataFlux Func must meet the following requirements:
-
CPU cores >= 2
-
Memory >= 4GB
-
Disk space >= 20GB
-
Network bandwidth >= 10 Mbps
-
Operating system Ubuntu 16.04 LTS/CentOS 7.2 or higher
-
Clean system (no operations other than network configuration after the operating system is installed)
-
Port
8088open (this system uses port8088by default; make sure the firewall, security group, and other settings allow inbound access to8088) -
When using an external MySQL, the MySQL version must be 5.7 or higher
-
When using an external Redis, the Redis version must be 4.0 or higher
Note: DataFlux Func does not support MacOS or Windows. You can install DataFlux Func on a virtual machine or cloud host.
Note: DataFlux Func does not support Redis in cluster mode. If you have high availability requirements, choose the primary-secondary version.
Note: If you install DataFlux Func on Alibaba Cloud ECS and enable the Alibaba Cloud Shield plugin, the system configuration should be increased accordingly because Cloud Shield itself consumes significant resources.
Download Command for the Portable Edition¶
Note: All shell commands mentioned in this article can be run directly under the root user; non-root users need to add sudo to run them.
Note: This article only provides the most common operating steps. For detailed installation and deployment, refer to the "Maintenance Manual".
Install Using the Automatic Installation Script¶
In the downloaded dataflux-func-portable directory,
run the following command to automatically configure and finally start the entire DataFlux Func:
Note: Before installation, confirm the system requirements and server configuration.
Note: DataFlux Func does not support Mac. Copy it to a Linux system before running the installation.
The automatic installation script enables quick installation and startup within a few minutes. The automatic configuration includes:
-
Running MySQL, Redis, and DataFlux Func (including Server, Worker, Beat)
-
Automatically creating and storing all data in the
/usr/local/dataflux-func/directory (including MySQL data, Redis data, DataFlux Func configuration, logs, and other files) -
Randomly generating the MySQL
rootuser password and the system Secret, and saving them in the DataFlux Func configuration file -
Redis is set without a password
-
MySQL and Redis do not provide external access
After execution completes, you can use a browser to access http://{server IP address/domain}:8088 to perform initialization through the operation UI.
Note: If the runtime environment has poor performance, use the
_docker ps_command to confirm that all components have started successfully before accessing it (see the following list).
-
dataflux-func_mysql -
dataflux-func_redis -
dataflux-func_server -
dataflux-func_worker-0 -
dataflux-func_worker-1-6 -
dataflux-func_worker-7 -
dataflux-func_worker-8-9 -
dataflux-func_beat
Obtain RAM Access Control¶
-
Log in to the RAM console https://ram.console.aliyun.com/users
-
Save or download the CSV file for AccessKeyID and AccessKey Secret (used in the configuration file)
Configuration Implementation¶
Log in to DataFlux Function¶
Log in to Func at http://ip:8088 (default admin/admin)
Create a Script Set¶
Enter the title/description.
Edit the Script¶
Write a script to write the bill data into DataKit, preparing for report creation.
The complete script is as follows:
import sys, datetime
import time
import json
import urllib
import hmac
from hashlib import sha1
import base64
import random
import requests
# Common parameters required by a request (the parameters needed to call any API)
D = {
'BillingCycle':str(time.strftime("%Y-%m", time.gmtime())),
'Action':'QuerySettleBill',
# 'PageNum':'5',
'Format':'JSON',
'Version':'2017-12-14',
'AccessKeyId':'<AccessKeyId>',
'SignatureMethod':'HMAC-SHA1',
'MaxResults' : '300',
# 'NextToken':"", #?
'Timestamp':str(time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())),
'SignatureVersion':'1.0'
# 'SignatureNonce':str_seed
}
# Current time
now_time = str(time.strftime("%Y-%m-%d", time.gmtime()))
# Connect to the local DataKit
datakit = DFF.SRC('datakit')
# Use the urllib library in Python to perform encoding
def percentEncode(str):
res = urllib.parse.quote(str.encode('utf8'), '')
res = res.replace('+', '%20')
res = res.replace('*', '%2A')
res = res.replace('%7E', '~')
return res
# Get bills
@DFF.API('getBill')
def getBill():
# Current position of bill records
next_token = ""
# Loop through bills and write them to DataKit
for i in range(10000):
random.seed()
# Unique random number to prevent network replay attacks. Use different random values for different requests.
D["SignatureNonce"] = str(random.random())
D["NextToken"] = next_token
# Because the signature requires uniqueness, including ordering, the parameters must be sorted by name
sortedD = sorted(D.items(),key=lambda x: x[0])
canstring = ''
for k,v in sortedD:
canstring += '&' + percentEncode(k) + '=' + percentEncode(v)
# Generate the canonicalized query string
stringToSign = 'GET&%2F&' + percentEncode(canstring[1:])
# access_key_secret
access_key_secret = '<access_key_secret>'
# Calculate the HMAC value
h = hmac.new((access_key_secret + "&").encode('utf8'), stringToSign.encode('utf8'), sha1)
# Calculate the signature value to generate the signature
signature = base64.encodestring(h.digest()).strip()
# Add the signature
D['Signature'] = signature
# Make the final API call
url = 'http://business.aliyuncs.com/?' + urllib.parse.urlencode(D)
# Request Alibaba Cloud bill costs
response = requests.get(url)
billing_cycle = response.json()["Data"]["BillingCycle"]
account_id = response.json()["Data"]["AccountID"]
next_token = response.json()["Data"]["NextToken"]
if next_token is not None:
bill = response.json()["Data"]["Items"]["Item"]
print(bill)
# Write today's bill to Guance
for i in bill:
print(i["UsageEndTime"])
time = i["UsageEndTime"].split(" ")[0]
print(time,now_time)
if time == now_time:
measurement = "aliyunSettleBill"
tags = {
"BillingCycle":billing_cycle,
"AccountID":account_id
}
fields = {
"ProductName":i["ProductName"],
"SubOrderId":i["SubOrderId"],
"BillAccountID":i["BillAccountID"],
"DeductedByCashCoupons":i["DeductedByCashCoupons"],
"PaymentTime":i["PaymentTime"],
"PaymentAmount":i["PaymentAmount"],
"DeductedByPrepaidCard":i["DeductedByPrepaidCard"],
"InvoiceDiscount":i["InvoiceDiscount"],
"UsageEndTime":i["UsageEndTime"],
"Item":i["Item"],
"SubscriptionType":i["SubscriptionType"],
"PretaxGrossAmount":i["PretaxGrossAmount"],
"Currency":i["Currency"],
"CommodityCode":i["CommodityCode"],
"UsageStartTime":i["UsageStartTime"],
"AdjustAmount":i["AdjustAmount"],
"Status":i["Status"],
"DeductedByCoupons":i["DeductedByCoupons"],
"RoundDownDiscount":i["RoundDownDiscount"],
"ProductDetail":i["ProductDetail"],
"ProductCode":i["ProductCode"],
"ProductType":i["ProductType"],
"OutstandingAmount":i["OutstandingAmount"],
"BizType":i["BizType"],
"PipCode":i["PipCode"],
"PretaxAmount":i["PretaxAmount"],
"OwnerID":i["OwnerID"],
"BillAccountName":i["BillAccountName"],
"RecordID":i["RecordID"],
"CashAmount":i["CashAmount"],
}
try:
status_code, result = datakit.write_logging(measurement=measurement, tags=tags, fields=fields)
print(status_code,result)
except:
print("插入失败!")
else:
break
else:
continue
break
else:
break
Publish the Script¶
Save the configuration, then publish it.
Create a Scheduled Task¶
Add an automatic trigger task: Management > Auto Trigger Configuration > Create Task. Since bills are generated daily, setting the collection frequency to once a day is sufficient.
View Reported Data¶
Log preview
Create an Explorer¶
Import the Explorer












