Envie dados de medição de uma instância de serviço.
Observações de uso
Esta operação envia dados de medição apenas para instâncias de serviço do Compute Nest com pagamento conforme o uso. O método de relatório dos itens faturáveis deve estar definido como Reported by Service Provider.
Para instâncias ECS ou ACK criadas por um serviço do Compute Nest, chame esta operação diretamente da instância para enviar os dados de medição. Para chamar esta operação com a OpenAPI, consulte Chamar PushMeteringData usando a OpenAPI.
Parâmetros da solicitação
|
Parameter |
Type |
Required |
Description |
Example |
|
Metering |
String |
Yes |
Dados de medição formatados como string JSON. Inclui os seguintes parâmetros:
Nota
|
|
|
Token |
String |
Yes |
Token que o Compute Nest utiliza para verificar se a solicitação proviene de um provedor de serviços legítimo. O token corresponde ao hash MD5 de 32 caracteres em minúsculas de uma string específica. Essa string é formada pela concatenação da string JSON de
|
|
Parâmetros de resposta
|
Parameter |
Type |
Description |
Example |
||
|
RequestId |
String |
ID da solicitação retornado pelo Compute Nest. |
e6862d3a-9305-4289-8dd3-9c52a680228b |
||
|
Success |
Boolean |
Indica se a solicitação foi bem-sucedida. |
true |
||
|
PushMeteringDataRequestId |
String |
ID da solicitação retornado pelo Alibaba Cloud Marketplace. |
7lc658a2-tr41---c25es45vc248 |
||
|
Token |
String |
Assinatura digital retornada. Utilize este token para verificar a resposta. Para mais informações, consulte Verificar uma assinatura digital do Compute Nest. |
50130a063c6acf833280d23169898bd4 |
Exemplos
Este exemplo demonstra como chamar a operação de uma instância ECS criada por um serviço do Compute Nest com pagamento conforme o uso no Alibaba Cloud Marketplace.
Exemplo com curl
-
Obtenha o ID da região da instância ECS
Antes de chamar esta operação, obtenha o ID da região da instância ECS onde sua aplicação está implantada. Esse ID será necessário em uma etapa posterior.
-
Execute o comando abaixo para consultar o ID da região no serviço de metadados da instância:
curl http://100.100.100.200/latest/meta-data/region-id -
Resposta de exemplo:
cn-hangzhou
-
-
Prepare os parâmetros
"Metering":"[{\"StartTime\":\"1664451045\",\"EndTime\":\"1664451198\",\"Entities\":[{\"Key\":\"Frequency\",\"Value\":\"6\"}]}]","Token":"7aa81300b2aea77984b772495c8e4e83"-
Metering:[{\"StartTime\":\"1664451045\",\"EndTime\":\"1664451198\",\"Entities\":[{\"Key\":\"Frequency\",\"Value\":\"6\"}]}]NotaComo este exemplo utiliza um comando curl, a string JSON do parâmetro
Meteringdeve ter escape com o caractere\. Caso chame a operação diretamente do seu código, não é necessário aplicar escape na string. Token: gere o token criando um hash MD5 de 32 caracteres em minúsculas da string que concatena o JSONMeteringconvertido em string, um caractere "e" comercial (&) e sua chave de serviço. O token neste exemplo é7aa81300b2aea77984b772495c8e4e83.
-
-
Envie a solicitação
curl -H "Content-Type: application/json" -XPOST https://cn-hangzhou.axt.aliyun.com/computeNest/marketplace/push_metering_data -d '{"Metering":"[{\"StartTime\":\"1664451045\",\"EndTime\":\"1664451198\",\"Entities\":[{\"Key\":\"Frequency\",\"Value\":\"6\"}]}]","Token":"7aa81300b2aea77984b772495c8e4e83"}'NotaEm
https://cn-hangzhou.axt.aliyun.com,cn-hangzhourepresenta a região obtida na Etapa 1. Ao realizar a chamada, substitua as informações da região pela sua região real. -
Visualize a resposta
{ "RequestId":"4ca591b5-bc30-****-****-c4d0ec5d24ed", "Success":"true", "PushMeteringDataRequestId":"7lc658a2-tr41-****-****-c25es45vc248", "Token":"50130a063c6acf833280d23169898bd4" }
Exemplos de código
Python
import requests
import json
import hashlib
import time
import sys
from urllib.request import urlopen
def get_region_id():
"""Gets the region ID from the Alibaba Cloud instance metadata service."""
try:
with urlopen(
"http://100.100.100.200/latest/meta-data/region-id",
timeout=2
) as response:
return response.read().decode().strip()
except Exception as e:
print(f"Failed to get region ID: {str(e)}", file=sys.stderr)
sys.exit(1)
def push_metering_data(entities_map, service_key):
# Get the current time as a UNIX timestamp in seconds.
current_time = int(time.time())
start_time = current_time
end_time = current_time + 1
# Construct the Metering data.
metering_data = [
{
"StartTime": str(start_time),
"EndTime": str(end_time),
"Entities": [
{"Key": key, "Value": str(value)}
for key, value in entities_map.items()
]
}
]
metering_str = json.dumps(metering_data)
# Get the region ID and construct the request URL.
region_id = get_region_id()
url = f"https://{region_id}.axt.aliyun.com/computeNest/marketplace/push_metering_data"
# Calculate the token.
token_str = metering_str + "&" + service_key
token = hashlib.md5(token_str.encode()).hexdigest().lower()
# Send the POST request.
try:
response = requests.post(
url,
json={
"Metering": metering_str,
"Token": token
},
headers={"Content-Type": "application/json"}
)
print(f"Request URL: {url}")
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
except Exception as e:
print(f"Request Failed: {str(e)}", file=sys.stderr)
if __name__ == "__main__":
# Sample parameters. Replace the key with your billable item and the value with the metered quantity.
entities = {
"Frequency": "6"
}
# Your service key.
service_key = "your_service_key_here"
# Call the function.
push_metering_data(entities, service_key)
Execução de exemplo:
[root@xxx aZ ~]# vim push.py
[root@xxx aZ ~]# python3 push.py
Request URL: https://cn-hangzhou.axt.aliyun.com/computeNest/marketplace/push_metering_data
Status Code: 200
Response: {"code":200,"requestId":"5979658a-7d11-4c61-xxx","instanceId":"i-bp140hj xxx","result":{"RequestId":"B3588CBD-6C3F-51C7-xxx","PushMeteringDataRequestId":"88D8CADB-2417-5417-504-xxx","Token":"xxx"},"Success":true}
Java
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
public class MeteringPusher {
public static void main(String[] args) {
try {
// Get the region ID dynamically.
String regionId = getRegionId();
System.out.println("Detected Region ID: " + regionId);
// Construct the request body.
Map<String, String> entities = new HashMap<>(); // Construct the Entities. Replace with your actual data.
entities.put("Frequency", "6");
String serviceKey = "your_service_key_here"; // Replace with your actual service key.
JSONObject payload = generateDynamicRequest(regionId, entities, serviceKey);
String paylodString = payload.toString();
// For testing purposes, you can comment out the dynamic generation and use a static payload string. Remember to replace the parameters.
// String paylodString = "{\"Metering\":\"[{\\\"StartTime\\\":\\\"1664451045\\\",\\\"EndTime\\\":\\\"1664451198\\\",\\\"Entities\\\":[{\\\"Key\\\":\\\"Frequency\\\",\\\"Value\\\":\\\"6\\\"}]}]\",\"Token\":\"7aa81300b2aea77984b772495c8e4e83\"}";
// Send the POST request.
String urlStr = "https://" + regionId + ".axt.aliyun.com/computeNest/marketplace/push_metering_data";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = paylodString.getBytes("UTF-8");
os.write(input, 0, input.length);
}
// Read the response.
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine);
}
conn.disconnect();
System.out.println("Response: " + response.toString());
System.out.println("Request URL: " + urlStr);
} catch (Exception e) {
e.printStackTrace();
}
}
// Get the region ID from the Alibaba Cloud instance metadata service.
private static String getRegionId() throws Exception {
String regionIdUrl = "http://100.100.100.200/latest/meta-data/region-id";
HttpURLConnection conn = (HttpURLConnection) new URL(regionIdUrl).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(2000); // 2-second timeout
conn.setReadTimeout(2000);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()))) {
return in.readLine().trim();
}
}
// Generate the request data dynamically.
private static JSONObject generateDynamicRequest(String regionId, Map<String, String> entities, String serviceKey) throws Exception {
// Get the current timestamp.
long currentTime = System.currentTimeMillis() / 1000;
long startTime = currentTime;
long endTime = currentTime + 1;
// Construct the Metering data.
JSONArray meteringArray = new JSONArray();
JSONObject meteringItem = new JSONObject();
meteringItem.put("StartTime", String.valueOf(startTime));
meteringItem.put("EndTime", String.valueOf(endTime));
JSONArray entitiesArray = new JSONArray();
for (Map.Entry<String, String> entry : entities.entrySet()) {
entitiesArray.put(new JSONObject()
.put("Key", entry.getKey())
.put("Value", entry.getValue()));
}
meteringItem.put("Entities", entitiesArray);
meteringArray.put(meteringItem);
// Calculate the token.
String meteringStr = meteringArray.toString();
String tokenStr = meteringStr + "&" + serviceKey;
String token = md5(tokenStr);
// Construct the complete request payload.
JSONObject payload = new JSONObject();
payload.put("Metering", meteringStr);
payload.put("Token", token);
return payload;
}
// Computes the MD5 hash of a string.
private static String md5(String input) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
Execução de exemplo:
[root@xxx ~]# javac MeteringPusher.java
[root@xxx ~]# java MeteringPusher
Detected Region ID: cn-hangzhou
Response: {"code":200,"requestId":"20a00ad2-bb10-4abxxx","instanceId":"i-bp140hjfmsqcuqanv6ea","result":{"RequestId":"3FF6B8A8-F72F-5Bxxx","PushMeteringDataRequestId":"E2E_862fc9bfd36fe02bf7b7380ed437ba7","Success":true}}
Request URL: https://cn-hangzhou.axt.aliyun.com/computeNest/marketplace/push_metering_data
Certifique-se de que seu projeto inclua a biblioteca org.json. Se utilizar Maven, por exemplo, adicione a seguinte dependência:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230618</version>
</dependency>
Códigos de erro
|
Error code |
Error message |
Description |
|
OperationDenied |
The service instance does not support pushing metering data. |
O envio de dados de medição não é suportado porque a instância de serviço não utiliza o modelo de pagamento conforme o uso. |
|
Only metering entities classified as Custom and associated with a service can be pushed. The entity ${EntityId} is invalid. |
O item faturável especificado não suporta envio de dados. Verifique se o método de relatório está definido como Reported by Service Provider e se a associação com o serviço está correta. |
|
|
MissingParameter.${parametersName} |
The required parameter "${parametersName}" is missing. |
Um parâmetro obrigatório está ausente. |
|
InvalidParameter.${parametersName} |
The provided parameter "${parametersName}" is invalid. |
O parâmetro especificado é inválido. |
|
EntityNotExist.ServiceInstance |
The specified service instance cannot be found. |
A instância de serviço não existe. Isso pode ocorrer caso a instância não tenha sido criada pelo Compute Nest. |