En este tema se describe cómo gestionar el ciclo de vida de los datos de Object Storage Service (OSS) mediante OSS SDK for PHP V2.
Contexto
No todos los datos almacenados en OSS se consultan con frecuencia. Sin embargo, es necesario conservar los datos de acceso poco frecuente para cumplir con las normativas o los requisitos de archivado. OSS permite configurar reglas de ciclo de vida que automatizan la gestión de sus datos. Existen dos tipos de reglas:
Regla basada en la última fecha de modificación. Este tipo de regla sirve para eliminar datos que no se han modificado durante un periodo prolongado. También permite moverlos a una clase de almacenamiento más económica para datos fríos.
Regla basada en la última fecha de acceso. Con esta opción se identifican los patrones de acceso y se mueven automáticamente los datos fríos a una clase de almacenamiento más rentable. De este modo, se implementa un almacenamiento por niveles para datos calientes y fríos, lo que reduce los costos de almacenamiento.
Notas
Antes de configurar una regla de ciclo de vida basada en la última fecha de modificación o de acceso, asegúrese de conocer bien la función de gestión del ciclo de vida. Para obtener más información, consulte Lifecycle rules based on last modification time y Lifecycle rules based on last access time.
El código de ejemplo de este tema utiliza el identificador de región
cn-hangzhou, correspondiente a China (Hangzhou). De forma predeterminada, se usa el endpoint público para acceder a los recursos de un bucket. Si necesita acceder a dichos recursos desde otros servicios de Alibaba Cloud ubicados en la misma región que el bucket, utilice el endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.Para configurar reglas de ciclo de vida, necesita el permiso
oss:PutBucketLifecycle. Para consultarlas, requiere el permisooss:GetBucketLifecycle. Por último, para borrarlas debe contar con el permisooss:DeleteBucketLifecycle. Para obtener más información, consulte Grant a custom policy.
Configuración de reglas de ciclo de vida
A continuación se muestran ejemplos de código para configurar reglas de ciclo de vida en un bucket, ya sea por la última fecha de modificación o de acceso. Puede modify one or more of the lifecycle rules configuradas para un bucket.
Configurar una regla basada en la última fecha de modificación para cambiar la clase de almacenamiento de objetos con un prefijo específico
El siguiente ejemplo configura una regla basada en la última fecha de modificación de los objetos. Su propósito es cambiar la clase de almacenamiento de aquellos cuyo nombre tenga un prefijo determinado:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Define a lifecycle rule that moves objects whose names are prefixed with "log/" to IA 30 days after they were last modified.
$lifecycleRule = new Oss\Models\LifecycleRule(
prefix: 'log/', // The prefix of object names.
transitions: array(
new Oss\Models\LifecycleRuleTransition(
days: 30, // Specify the days.
storageClass: 'IA' // Change to IA.
)
),
id: 'rule', // The rule ID.
status: 'Enabled' // Enable the rule.
);
// Create a lifecycle configuration and add lifecycle rules to the configuration.
$lifecycleConfiguration = new LifecycleConfiguration(
rules: array($lifecycleRule)
);
// Create a request to set a lifecycle configuration and pass the lifecycle configuration.
$request = new Oss\Models\PutBucketLifecycleRequest(
bucket: $bucket,
lifecycleConfiguration: $lifecycleConfiguration
);
// Call the putBucketLifecycle method to configure the lifecycle rules.
$result = $client->putBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
Configurar una regla basada en la última fecha de modificación para cambiar la clase de almacenamiento de objetos sin prefijos ni etiquetas específicas
El siguiente código configura una regla que afecta a los objetos sin el prefijo "log" o sin la etiqueta "key1:value1". Estos se trasladan a Infrequent Access (IA) 30 días después de su última modificación y caducan a los 100 días de dicha fecha:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
$lifecycleRule = new Oss\Models\LifecycleRule(
id: 'rule', // The rule ID.
status: 'Enabled' // Enable the rule.
prefix: 'log/', // The prefix of object names.
transitions: array(
new Oss\Models\LifecycleRuleTransition(
days: 30, // Specify the days.
storageClass: 'Archive' // Change the storage class to Archive.
)
),
filter: new Oss\Models\LifecycleRuleFilter( // Specify filters.
not: new Oss\Models\LifecycleRuleNot( // Specify exclusion filters.
prefix: 'log', // Exclude objects whose names contain the "log" prefix.
tag: new Oss\Models\Tag( // Specify tag filters.
key: 'key1',
value: 'value1'
)
)
),
expiration: new Oss\Models\LifecycleRuleExpiration(
days: 100 // Set the object expiration time to 100 days.
)
);
// Create a lifecycle configuration and add lifecycle rules to the configuration.
$lifecycleConfiguration = new LifecycleConfiguration(
rules: array($lifecycleRule)
);
// Create a request to set a lifecycle configuration and pass the lifecycle configuration.
$request = new Oss\Models\PutBucketLifecycleRequest(
bucket: $bucket,
lifecycleConfiguration: $lifecycleConfiguration
);
// Call the putBucketLifecycle method to configure the lifecycle rules.
$result = $client->putBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
Configurar una regla basada en la última fecha de acceso para cambiar la clase de almacenamiento
El siguiente fragmento muestra cómo configurar una regla de ciclo de vida basada en la última fecha de acceso para modificar la clase de almacenamiento:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
use AlibabaCloud\Oss\V2\Models\LifecycleConfiguration;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
{}
$lifecycleRule = new Oss\Models\LifecycleRule(
prefix: 'log/', // The prefix of object names.
transitions: array(
new Oss\Models\LifecycleRuleTransition(
days: 30, // Specify the days.
storageClass: 'IA', // Change to IA.
isAccessTime: 'true', // Trigger the change based on the last access time.
returnToStdWhenVisit: 'true' // Return to the Standard storage class after they are accessed.
)
),
id: 'rule', // The rule ID.
status: 'Enabled' // Enable the rule.
);
// Create a lifecycle configuration and add lifecycle rules to the configuration.
$lifecycleConfiguration = new LifecycleConfiguration(
rules: array($lifecycleRule)
);
// Create a request to set a lifecycle configuration and pass the lifecycle configuration.
$request = new Oss\Models\PutBucketLifecycleRequest(
bucket: $bucket,
lifecycleConfiguration: $lifecycleConfiguration
);
// Call the putBucketLifecycle method to configure the lifecycle rules.
$result = $client->putBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
Consulta de reglas de ciclo de vida
El siguiente código consulta las reglas de ciclo de vida configuradas en un bucket:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request to query lifecycle rules.
$request = new Oss\Models\GetBucketLifecycleRequest(bucket: $bucket);
// Call the getBucketLifecycle method to query lifecycle rules.
$result = $client->getBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL . // The request ID.
'lifecycle:' . var_export($result->lifecycleConfiguration, true) . PHP_EOL // The lifecycle rules.
);
Borrado de reglas de ciclo de vida
El siguiente ejemplo borra todas las reglas de ciclo de vida de un bucket. Si solo desea eliminar algunas, siga las instrucciones de Delete lifecycle rules.
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
];
// Generate a long options list to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSS client instance.
$client = new Oss\Client($cfg);
// Create a request to delete lifecycle rules of a bucket.
$request = new Oss\Models\DeleteBucketLifecycleRequest(bucket: $bucket);
// Call the deleteBucketLifecycle method to delete lifecycle rules.
$result = $client->deleteBucketLifecycle($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code.
'request id:' . $result->requestId . PHP_EOL // The request ID.
);
Referencias
Para obtener más información sobre la operación de API que configura una regla de ciclo de vida, consulte PutBucketLifecycle.
Si necesita detalles sobre la operación de API que consulta las reglas de ciclo de vida, consulte GetBucketLifecycle.
Respecto a la operación de API que elimina las reglas de ciclo de vida, consulte DeleteBucketLifecycle.