API introduction

Last Updated: Jun 30, 2017

Overview

The Cloud Monitor service interface is called by sending an HTTP request to the Cloud Monitor server (only HTTP is supported currently) and receiving the response of the Cloud Monitor server to this request.

After receiving a user request, the Cloud Monitor server performs necessary authentication and parameter verification on the request. After all verifications are successful, the server submits or performs the associated operations based on the parameters specified for the request. Then, it returns the processing results to the caller in the form of an HTTP response.

Request composition

Requests are composed of the following parts:

  • HTTP Method — Currently, all Cloud Monitor interfaces support GET method calls. Metric data can also be reported through POST.
  • Request URL — The request URL contains the service address of a request, name of the operation to be executed, operation parameters, and public request parameters.
  • Server address: The domain name of the Cloud Monitor service is http://metrics.aliyuncs.com/.
  • Operation name: Each interface requires you to specify the name of the operation you want to execute, that is, the Action parameter.
  • Operation parameter: Different operation parameters must be set for different operations to be executed. For details, see the instructions for each interface.
  • Public request parameters: Parameters required for each request, such as Time Stamp and Signature.
  • For the server to correctly verify the user’s authentication and authorize request execution, the request must be signed before submission for processing. For signature rules, refer to the signature mechanism section.
  • After the server finishes processing the request, response results are returned. Response results are categorized into successful results and error messages. For a description of the format, refer to the returned results section. The client can parse the response message body to obtain the execution results.

Request parameters

Name Type Required? Description
Action String Yes Operation interface, required parameter. Value: QueryMetricList.
Project String Yes Name space. It indicates the product to which the metric data belongs, for example, “acs_ocs” and “acs_rds”. Namespaces can be used.
Metric String Yes The metric item name. For available names, refer to the metric list.
Period String No The time interval, always calculated in seconds. E.g., 60, 300, 900. If this is not entered, the raw data is queried based on the report period stated during metric item registration. If the statistical period is entered, the corresponding statistical data is queried.
StartTime String Yes The start time. It can be a millisecond value counted from 00:00, January 1, 1970, or formatted data, such as 2015-10-20 00:00:00.
EndTime String No It can be a millisecond value counted from 00:00, January 1, 1970, or formatted data, such as 2015-10-20 00:00:00.
Dimensions String Yes Locate the dimension of the metric data position. In the example of the metric item “disk IO”, the unique monitoring position can be located via two dimensions, namely, instance and disk name. NOTE: For details about the dimensions for each metric item, refer to “Preset metric item reference”.
Cursor String No Paging cursor. It indicates that the next query continues with the latest query.
Length String Yes Number of items to be queried this time. The maximum value is 1,000. If set to any number greater than 1,000, this parameter is automatically reset to 1,000.

Parameter description

  • For details about how to assign values for Project, Metric, Period and Dimensions, refer to Preset metric item reference.

  • startTime and endTime are in the left-open and right-closed mode, and startTime cannot be the same as or later than endTime.

  • Cursor is a parameter in paging mode. The Cursor parameter indicates there is a next page. If the return result is null, there are no more pages.

  • Generally, the Period value can be 60 (1 minute), 300 (5 minutes), or 900 (15 minutes). You can set the Period parameter based on the document requirements and query scenario. For example, to query data for a specified day, if you set Period to 60, then 1,000 data items are returned (Actually there are 1,440 items but only 1,000 items are returned since the maximum return value cannot be greater than 1,000); if you set Period to 300, then 288 data items are returned.

  • The first letter of each parameter is in uppercase.

  • The interface supports RAM subaccount calls. The operation descriptor at authorization is “cms:QueryMetricList” and the resource descriptor is “*”.

Return parameters

Name Type Description
Code String Return code. It generally includes 200 (normal), 400 (parameter error), 403 (permission error), 500 (server error). Return codes except 200 are all error codes. You can refer to the error code prompt information to learn about them.
Msg String The status description returned by the query. Msg is blank when Code is “200”.
Success Boolean Whether or not the current query was performed successfully. If there is an exception on the server side, the returned value is “false” (and “true” otherwise).
Size Integer Number of actually returned items in the current query
RequestId/TracerId String Unique request ID. When there is an issue with querying, you can provide this field to a technician to troubleshoot the problem.
Datapoints JSON Metric data
Cursor String Cursor is returned as a parameter for the next query if the number of queried items is greater than the length value within the time range specified in your query. If Cursor is not returned, all items are queried.

Return value error code

Error Code Description Meaning
400 Bad Request Parameter error
403 Forbidden Permission restriction. AccessKey does not match that of the item to be queried.
500 Internal Server Error Server error

Call example

We take Java as an example. For details on signing methods, refer to Signature algorithms in the call method.

Signature code:UrlUtil.java

  1. import java.net.URLEncoder;
  2. import java.util.Map;
  3. import org.apache.commons.lang.StringUtils;
  4. import org.apache.log4j.Logger;
  5. public class UrlUtil {
  6. private static Logger logger = Logger.getLogger(UrlUtil.class);
  7. private final static String CHARSET_UTF8 = "utf8";
  8. /**
  9. *
  10. * @param url
  11. * @return
  12. */
  13. public static String urlEncode(String url) {
  14. if (!StringUtils.isEmpty(url)) {
  15. try {
  16. url = URLEncoder.encode(url, "UTF-8");
  17. } catch (Exception e) {
  18. logger.warn("Url encode error:" + e.getMessage());
  19. }
  20. }
  21. return url;
  22. }
  23. public static String generateQueryString(Map<String, String> params, boolean isEncodeKV) {
  24. StringBuilder canonicalizedQueryString = new StringBuilder();
  25. for (Map.Entry<String, String> entry : params.entrySet()) {
  26. if (isEncodeKV)
  27. canonicalizedQueryString.append(percentEncode(entry.getKey())).append("=")
  28. .append(percentEncode(entry.getValue())).append("&");
  29. else
  30. canonicalizedQueryString.append(entry.getKey()).append("=")
  31. .append(entry.getValue()).append("&");
  32. }
  33. if (canonicalizedQueryString.length() > 1) {
  34. canonicalizedQueryString.setLength(canonicalizedQueryString.length() - 1);
  35. }
  36. return canonicalizedQueryString.toString();
  37. }
  38. public static String percentEncode(String value) {
  39. try {
  40. // After using URLEncoder.encode for encoding, replace"+","*", and "%7E" with values that conform to the encoding standard specified by the API
  41. return value == null ? null : URLEncoder.encode(value, CHARSET_UTF8)
  42. .replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
  43. } catch (Exception e) {
  44. //Impossible exception
  45. }
  46. return "";
  47. }
  48. }

SignatureUtils.java

  1. import java.io.IOException;
  2. import java.io.UnsupportedEncodingException;
  3. import java.net.URI;
  4. import java.net.URISyntaxException;
  5. import java.net.URLDecoder;
  6. import java.net.URLEncoder;
  7. import java.util.Map;
  8. import java.util.TreeMap;
  9. import javax.crypto.Mac;
  10. import javax.crypto.spec.SecretKeySpec;
  11. import org.apache.commons.codec.binary.Base64;
  12. import org.apache.commons.lang.StringUtils;
  13. public class SignatureUtils {
  14. private final static String CHARSET_UTF8 = "utf8";
  15. private final static String ALGORITHM = "UTF-8";
  16. private final static String SEPARATOR = "&";
  17. public static Map<String, String> splitQueryString(String url)
  18. throws URISyntaxException, UnsupportedEncodingException {
  19. URI uri = new URI(url);
  20. String query = uri.getQuery();
  21. final String[] pairs = query.split("&");
  22. TreeMap<String, String> queryMap = new TreeMap<String, String>();
  23. for (String pair : pairs) {
  24. final int idx = pair.indexOf("=");
  25. final String key = idx > 0 ? pair.substring(0, idx) : pair;
  26. if (!queryMap.containsKey(key)) {
  27. queryMap.put(key, URLDecoder.decode(pair.substring(idx + 1), CHARSET_UTF8));
  28. }
  29. }
  30. return queryMap;
  31. }
  32. public static String generate(String method, Map<String, String> parameter,
  33. String accessKeySecret) throws Exception {
  34. String signString = generateSignString(method, parameter);
  35. System.out.println("signString---"+signString);
  36. byte[] signBytes = hmacSHA1Signature(accessKeySecret + "&", signString);
  37. String signature = newStringByBase64(signBytes);
  38. System.out.println("signature---"+signature);
  39. if ("POST".equals(method))
  40. return signature;
  41. return URLEncoder.encode(signature, "UTF-8");
  42. }
  43. public static String generateSignString(String httpMethod, Map<String, String> parameter)
  44. throws IOException {
  45. TreeMap<String, String> sortParameter = new TreeMap<String, String>();
  46. sortParameter.putAll(parameter);
  47. String canonicalizedQueryString = UrlUtil.generateQueryString(sortParameter, true);
  48. if (null == httpMethod) {
  49. throw new RuntimeException("httpMethod can not be empty");
  50. }
  51. StringBuilder stringToSign = new StringBuilder();
  52. stringToSign.append(httpMethod).append(SEPARATOR);
  53. stringToSign.append(percentEncode("/")).append(SEPARATOR);
  54. stringToSign.append(percentEncode(canonicalizedQueryString));
  55. return stringToSign.toString();
  56. }
  57. public static String percentEncode(String value) {
  58. try {
  59. return value == null ? null : URLEncoder.encode(value, CHARSET_UTF8)
  60. .replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
  61. } catch (Exception e) {
  62. }
  63. return "";
  64. }
  65. public static byte[] hmacSHA1Signature(String secret, String baseString)
  66. throws Exception {
  67. if (StringUtils.isEmpty(secret)) {
  68. throw new IOException("secret can not be empty");
  69. }
  70. if (StringUtils.isEmpty(baseString)) {
  71. return null;
  72. }
  73. Mac mac = Mac.getInstance("HmacSHA1");
  74. SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(CHARSET_UTF8), ALGORITHM);
  75. mac.init(keySpec);
  76. return mac.doFinal(baseString.getBytes(CHARSET_UTF8));
  77. }
  78. public static String newStringByBase64(byte[] bytes)
  79. throws UnsupportedEncodingException {
  80. if (bytes == null || bytes.length == 0) {
  81. return null;
  82. }
  83. return new String(Base64.encodeBase64(bytes, false), CHARSET_UTF8);
  84. }
  85. public static void main(String[] args) {
  86. String str = "GET&%2F&AccessKeyId%3DCdwKFNmXeHJuMOrT&Action%3DDescribeInstances&Format%3DJSON&RegionId%3Dcn-hangzhou&SignatureMethod%3DHMAC-SHA1&SignatureNonce%3D9fdf20f2-9a32-4872-bcd4-c6036082ebef&SignatureVersion%3D1.0&Timestamp%3D2015-12-21T09%253A05%253A44Z&Version%3D2014-05-26";
  87. byte[] signBytes;
  88. try {
  89. signBytes = SignatureUtils.hmacSHA1Signature("byczfpx4PKBzUNjjL4261cE3s6HQmH" + "&", str.toString());
  90. String signature = SignatureUtils.newStringByBase64(signBytes);
  91. } catch (Exception e) {
  92. // TODO Auto-generated catch block
  93. e.printStackTrace();
  94. }
  95. }
  96. }

Query Examples of Metric Data for ECS Instances

  1. import java.io.IOException;
  2. import java.io.UnsupportedEncodingException;
  3. import java.net.URISyntaxException;
  4. import java.text.SimpleDateFormat;
  5. import java.util.Date;
  6. import java.util.HashMap;
  7. import java.util.Locale;
  8. import java.util.Map;
  9. import java.util.SimpleTimeZone;
  10. import java.util.UUID;
  11. import net.sf.json.JSON;
  12. import net.sf.json.JSONArray;
  13. import org.apache.commons.httpclient.HttpClient;
  14. import org.apache.commons.httpclient.HttpException;
  15. import org.apache.commons.httpclient.HttpMethod;
  16. import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
  17. import org.apache.commons.httpclient.methods.GetMethod;
  18. import org.apache.commons.httpclient.methods.PostMethod;
  19. import org.springframework.http.HttpHeaders;
  20. import org.springframework.http.MediaType;
  21. public class EcsTemplate {
  22. private final static String SIGNATURE_VERSION = "1.0";
  23. private final static String defaultSignatureType = "HMAC-SHA1";
  24. private final static String API_Format = "JSON";
  25. //cms version
  26. private final static String API_VERSION = "2015-10-20";
  27. //Enter your AccessKey information.
  28. private final static String accessKeyId = "YouraccessKeyId";
  29. private final static String accessKeySecret = "YouraccessKeySecret";
  30. private final static String domainnew = "metrics.aliyuncs.com";
  31. protected String domain="metrics.aliyuncs.com";
  32. //protected String domain = "alert.aliyuncs.com";
  33. private static String formatISO8601Date(Date date) {
  34. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",
  35. Locale.US);
  36. df.setTimeZone(new SimpleTimeZone(0, "GMT"));
  37. return df.format(date);
  38. }
  39. protected HttpHeaders buildHttpHeaders(String sessionId) {
  40. HttpHeaders headers = new HttpHeaders();
  41. headers.setContentType(MediaType.APPLICATION_JSON);
  42. headers.set("Authentication", sessionId);
  43. return headers;
  44. }
  45. public static void main(String[] args) {
  46. Map<String, String> parameters = new HashMap<String, String>();
  47. //String action = "DescribeInstances";
  48. String action = "QueryMetricList";
  49. parameters.put("RegionId", "cn");
  50. parameters.put("Action", action);
  51. parameters.put("Project", "acs_ecs");
  52. parameters.put("Metric", "CPUUtilization");
  53. parameters.put("StartTime", "2016-01-01 00:00:00");
  54. parameters.put("Period", "60");
  55. parameters.put("Length", "1000");
  56. //Note the dimension format!!
  57. parameters.put("Dimensions", "{\"instanceId\":\"********\"}");
  58. parameters.put("AccessKeyId", accessKeyId);
  59. parameters.put("Format", API_Format);
  60. parameters.put("SignatureMethod", defaultSignatureType);
  61. parameters.put("SignatureNonce", UUID.randomUUID().toString());
  62. parameters.put("SignatureVersion", SIGNATURE_VERSION);
  63. parameters.put("Version",API_VERSION );
  64. parameters.put("Timestamp", formatISO8601Date(new Date()));
  65. String url = "http://"+domainnew;
  66. if(!url.endsWith("/")){
  67. url += "/";
  68. }
  69. url += "?";
  70. url += UrlUtil.generateQueryString(parameters, true);
  71. String signature = null;
  72. try {
  73. signature = SignatureUtils.generate("GET", parameters, accessKeySecret);
  74. } catch (Exception e) {
  75. e.printStackTrace();
  76. }
  77. url += "&Signature=" + signature;
  78. HttpMethod http1 = new PostMethod();
  79. HttpMethod httpMethod = new GetMethod(url);
  80. System.out.println(url);
  81. HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
  82. httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(6000);//Set the request timeout time to 6 seconds.
  83. httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000); //Set the read timeout time.
  84. try {
  85. int statusCode = httpClient.executeMethod(httpMethod);
  86. //if(statusCode!=200)return null;
  87. byte[] bytes = httpMethod.getResponseBody();
  88. String result = "[" + statusCode + "]"+new String(bytes, "UTF-8");
  89. System.out.println(result);
  90. } catch (HttpException e) {
  91. e.printStackTrace();
  92. } catch (IOException e) {
  93. e.printStackTrace();
  94. }
  95. }
  96. }
Thank you! We've received your feedback.