A replicação de dados copia automaticamente objetos e operações, como crie, sobrescrita e exclua de objetos, de um bucket source para um bucket de destino. O object storage service (oss) oferece suporte à replicação entre regiões (CRR) e à replicação na mesma região (SRR).
Observações
O código de exemplo usa o ID da região
cn-hangzhou, da região china (Hangzhou), e um endpoint público por padrão. Para acessar recursos de outros service da Alibaba Cloud na mesma região do bucket, use o endpoint interno. Para mais informações sobre regiões e endpoints do oss, consulte Regions and endpoints.-
Uma conta da Alibaba Cloud possui as permissões necessárias por padrão. Para replicar dados como usuário RAM ou ao usar credenciais de acesso temporárias do Security Token service (STS), são necessárias as seguintes permissões:
Para ative a replicação de dados, é necessária a permissão
oss:PutBucketReplication.A permissão
oss:PutBucketRtcé obrigatória para ative ou desativar o recurso de controle de tempo de replicação (RTC).A permissão
oss:GetBucketReplicationpermite consultar as regras de replicação de dados.A consulta das regiões de destino disponíveis para replicação de dados requer a permissão
oss:GetBucketReplicationLocation.Para consultar o progresso de uma tarefa de replicação de dados, é preciso ter a permissão
oss:GetBucketReplicationProgress.Desativar a replicação de dados requer a permissão
oss:DeleteBucketReplication.
Código de exemplo
Ative a replicação de dados
Antes de ative a replicação de dados, certifique-se de que os buckets source e de destino estejam sem versionamento ou com o versionamento ativado.
O código de exemplo a seguir ative a replicação de dados de um bucket source para um bucket de destino na mesma região ou em uma região diferente:
<?php
// Include the autoload file to load the SDK and other dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
// Use the Alibaba Cloud OSS V2 namespace.
use AlibabaCloud\Oss\V2 as Oss;
// Define the command-line parameters, descriptions, and whether the parameters are required.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
"bucket" => ['help' => 'The name of the bucket', 'required' => True],
"target-bucket" => ['help' => 'The name of the target bucket', 'required' => True],
"target-location" => ['help' => 'The location of the target bucket', 'required' => True],
];
// Create an array of long options required by getopt. Example: ["region:", "endpoint:", ...]
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Retrieve the command-line arguments passed.
$options = getopt("", $longopts);
// Check whether all required parameters are provided. If one is missing, an error message is displayed and the program exits.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help";
exit(1);
}
}
// Extract the command-line arguments.
$region = $options["region"];
$bucket = $options["bucket"];
$targetBucket = $options["target-bucket"];
$targetLocation = $options["target-location"];
// Use access credentials stored in environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Load the default configuration.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Construct a PutBucketReplicationRequest object.
$request = new Oss\Models\PutBucketReplicationRequest(
bucket: $bucket,
replicationConfiguration: new Oss\Models\ReplicationConfiguration(
rules: array(
new Oss\Models\ReplicationRule(
destination: new Oss\Models\ReplicationDestination(
bucket: $targetBucket,
location: $targetLocation,
),
rtc: new Oss\Models\ReplicationTimeControl(
status: 'enabled' // Enable replication time control (RTC).
)
)
)
)
);
// Execute the request and obtain the result.
$result = $client->putBucketReplication($request);
// Display the status code, request ID, and replication rule ID.
printf(
'status code:' . $result->statusCode . PHP_EOL .
'request id:' . $result->requestId . PHP_EOL .
'replication rule id:' . $result->replicationRuleId
);
Consultar regras de replicação de dados
O código a seguir consulta as regras de replicação de dados de um bucket:
<?php
// Include the autoload file to load the SDK and other dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
// Use the Alibaba Cloud OSS V2 namespace and abbreviate it as Oss.
use AlibabaCloud\Oss\V2 as Oss;
// Define and describe command-line arguments.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
"bucket" => ['help' => 'The name of the bucket', 'required' => True],
];
// Construct an array of long options required by getopt.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Retrieve the long options passed from the command line.
$options = getopt("", $longopts);
// Traverse all parameter definitions and check whether all required ones are provided.
foreach ($optsdesc as $key => $value) {
// If a required parameter is missing, display an error message and exit the program.
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help";
exit(1);
}
}
// Extract the region and bucket name from the command-line arguments.
$region = $options["region"];
$bucket = $options["bucket"];
// Load access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Load the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Construct a GetBucketReplicationRequest object.
$request = new Oss\Models\GetBucketReplicationRequest(bucket: $bucket);
// Send the request and obtain the result.
$result = $client->getBucketReplication($request);
// Display the status code, request ID, and replication rules.
printf(
'status code:' . $result->statusCode . PHP_EOL .
'request id:' . $result->requestId . PHP_EOL .
'replication config:' . var_export($result->replicationConfiguration, true)
);
Ative ou desativar o recurso RTC
O código de exemplo a seguir ative ou desativa o recurso RTC para uma regra de CRR:
<?php
// Include the autoload file to load the SDK and dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
// Use the Alibaba Cloud OSS V2 namespace and abbreviate it as Oss.
use AlibabaCloud\Oss\V2 as Oss;
// Define the command-line parameters, descriptions, and whether the parameters are required.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
"bucket" => ['help' => 'The name of the bucket', 'required' => True],
"rule-id" => ['help' => 'The replication rule id of the bucket', 'required' => True],
];
// Construct an array of long options required by getopt. A key with a colon at the end expects a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Retrieve the long options passed from the command line.
$options = getopt("", $longopts);
// Check whether all required parameters are provided.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help";
exit(1);
}
}
// Extract the region, bucket, and replication rule ID.
$region = $options["region"];
$bucket = $options["bucket"];
$ruleId = $options["rule-id"];
// Load access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Load the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Construct a PutBucketRtcRequest object.
$request = new Oss\Models\PutBucketRtcRequest(
bucket: $bucket,
rtcConfiguration: new Oss\Models\RtcConfiguration(
rtc: new Oss\Models\ReplicationTimeControl(
status: 'disabled' // Disable RTC.
),
id: $ruleId // The ID of the replication rule to be modified.
)
);
$result = $client->putBucketRtc($request);
// Display the status code and request ID.
printf(
'status code:' . $result->statusCode . PHP_EOL .
'request id:' . $result->requestId
);
Consultar as regiões disponíveis para replicação de dados
O código de exemplo a seguir consulta as regiões de destino disponíveis para um bucket source:
<?php
// Include the autoload file to load the SDK and other dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
// Use the Alibaba Cloud OSS V2 namespace and abbreviate it as Oss.
use AlibabaCloud\Oss\V2 as Oss;
// Define the command-line parameters, descriptions, and whether the parameters are required.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
"bucket" => ['help' => 'The name of the bucket', 'required' => True],
];
// Construct an array of long options required by getopt.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Retrieve the long options passed from the command line.
$options = getopt("", $longopts);
// Traverse parameter definitions and check whether all required ones are provided.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help";
exit(1);
}
}
// Extract the region and bucket name from the command-line arguments.
$region = $options["region"];
$bucket = $options["bucket"];
// Load access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Load the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a GetBucketReplicationLocationRequest object to query regions to which data can be replicated.
$request = new Oss\Models\GetBucketReplicationLocationRequest(bucket: $bucket);
// Send the request and obtain the result.
$result = $client->getBucketReplicationLocation($request);
// Display the status code, request ID, and available destination regions.
printf(
'status code:' . $result->statusCode . PHP_EOL .
'request id:' . $result->requestId . PHP_EOL .
'replication location:' . var_export($result->replicationLocation, true)
);
Consultar o progresso de uma tarefa de replicação de dados
É possível consultar o progresso da replicação de dados históricos e incrementais.
O progresso de uma tarefa de replicação de dados históricos é expresso em porcentagem. É possível consultar o progresso de tarefas de replicação de dados históricos apenas para buckets com essa funcionalidade ativada.
O progresso de uma tarefa de replicação de dados incrementais é expresso como um momento específico. Os dados armazenados no bucket source antes desse momento já foram replicados.
O código de exemplo a seguir consulta o progresso da replicação de dados para uma regra de replicação específica:
<?php
// Include the autoload file to load the SDK and dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
// Use the Alibaba Cloud OSS V2 namespace and abbreviate it as Oss.
use AlibabaCloud\Oss\V2 as Oss;
// Define the command-line parameters, descriptions, and whether the parameters are required.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
"bucket" => ['help' => 'The name of the bucket', 'required' => True],
"rule-id" => ['help' => 'The replication rule id of the bucket', 'required' => True],
];
// Construct an array of long options required by getopt. A key with a colon at the end expects a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Retrieve the long options passed from the command line.
$options = getopt("", $longopts);
// Traverse parameter definitions and check whether all required ones are provided.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help";
exit(1);
}
}
// Extract the region, bucket, and replication rule ID.
$region = $options["region"];
$bucket = $options["bucket"];
$ruleId = $options["rule-id"];
// Load access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Load the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Construct a GetBucketReplicationProgressRequest object to query the replication progress for a specific replication rule.
$request = new Oss\Models\GetBucketReplicationProgressRequest(bucket: $bucket, ruleId: $ruleId);
// Send the request and obtain the result.
$result = $client->getBucketReplicationProgress($request);
// Display the status code, request ID, and replication progress details.
printf(
'status code:' . $result->statusCode . PHP_EOL .
'request id:' . $result->requestId . PHP_EOL .
'replication progress:' . var_export($result->replicationProgress, true)
);
Desativar a replicação de dados
Para desativar a replicação de dados, exclua a regra de replicação configurada para o bucket source.
O código de exemplo a seguir exclua a regra de replicação especifique do bucket:
<?php
// Include the autoload file to load the SDK and other dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
// Use the Alibaba Cloud OSS V2 namespace and abbreviate it as Oss.
use AlibabaCloud\Oss\V2 as Oss;
// Define the command-line parameters, descriptions, and whether the parameters are required.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
"bucket" => ['help' => 'The name of the bucket', 'required' => True],
"rule-id" => ['help' => 'The replication rule id of the bucket', 'required' => True],
];
// Construct an array of long options required by getopt. A key with a colon at the end expects a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Retrieve the long options passed from the command line.
$options = getopt("", $longopts);
// Traverse parameter definitions and check whether all required ones are provided.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help";
exit(1);
}
}
// Extract the region, bucket, and replication rule ID.
$region = $options["region"];
$bucket = $options["bucket"];
$ruleId = $options["rule-id"];
// Load access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Load the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider, region, and optional endpoint.
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Construct a DeleteBucketReplicationRequest object to delete replication rules.
$request = new Oss\Models\DeleteBucketReplicationRequest(
bucket: $bucket,
replicationRules: new Oss\Models\ReplicationRules(
ids: [$ruleId] // The list of IDs of replication rules to be deleted.
)
);
// Send the request to delete the specified replication rules.
$result = $client->deleteBucketReplication($request);
// Display the status code and request ID.
printf(
'status code:' . $result->statusCode . PHP_EOL .
'request id:' . $result->requestId
);