Lifecycle rules based on last access time

更新时间:
复制 MD 格式

You can use lifecycle rules based on last access time to automatically monitor data access patterns and identify cold data. You can then transition the identified cold data to a different storage class. This lets you implement tiered storage for hot and cold data, which reduces your storage costs.

Scenarios

  • Multimedia

    A website stores its videos and images in OSS. Over time, historical data gradually transitions from hot to cold. You may want to transition data that has not been accessed for a long time to the Infrequent Access storage class. However, some older data remains popular and needs to be kept in the Standard storage class. In this scenario, use a lifecycle rule based on last access time to automatically identify hot and cold data for tiered storage, thereby reducing storage costs.

  • Photo albums or cloud drives

    You can set a custom transition period to automatically move cold data that has not been accessed for an extended period to the Infrequent Access storage class, while still ensuring real-time access.

  • Life sciences

    The vast amount of business data generated from gene sequencing is often classified as hot or cold based on its last access time rather than its last modified time. Previously, customers could only manage data tiering manually by analyzing logs or using other methods. A lifecycle rule based on last access time lets the server automatically identify hot and cold data and implement tiered storage. You can also combine policies based on both last access time and last modified time within the same lifecycle rule for more flexible data management.

Limits

Region-specific limits

  • You cannot configure lifecycle rules based on last access time for buckets without regional attributes.

  • You cannot configure lifecycle rules based on last access time in Finance Cloud regions.

No data deletion

Lifecycle rules based on last access time cannot be used to delete data.

Matching conditions

Lifecycle rules support matching only based on prefixes and tags. Wildcard matching, suffix matching, and regular expression matching are not supported.

Part expiration limits

You cannot configure two or more lifecycle rules that contain a part lifecycle policy for objects whose names have overlapping prefixes. Examples:

  • Example 1

    If you configure a lifecycle rule that contains a part policy for a bucket, you cannot configure another lifecycle rule that contains a part policy for any objects in the bucket.

  • Example 2

    If you configure a lifecycle rule that contains a part policy for objects whose names contain the dir1 prefix in a bucket, you cannot configure another lifecycle rule that contains a part policy for objects whose names contain overlapping prefixes, such as dir1/dir2.

Usage notes

Number of rules

A bucket can have up to 1,000 lifecycle rules. A lifecycle rule can contain both policies based on the last modified time and policies based on the last access time.

Billing

  • Object monitoring and management fees

    After you enable access tracking, object monitoring and management fees are incurred. However, OSS does not currently charge these fees.

  • Fees for not meeting the minimum storage duration for Infrequent Access

    Objects in the Infrequent Access storage class have a minimum storage duration of 30 days. If an object is stored for less than 30 days, you are charged for the remaining portion of the minimum duration. The following examples describe how this billing item works with lifecycle rules:

    Example 1: A lifecycle rule transitions a Standard object to the Infrequent Access storage class 10 days after its creation. Five days later, it transitions back to the Standard storage class. In this case, you are charged for 15 days of storage to meet the minimum storage duration requirement for Infrequent Access.

    Example 2: A lifecycle rule transitions a Standard object to the Infrequent Access storage class 10 days after its creation. The object is deleted 15 days later. In this case, you are charged for 5 days of storage to meet the minimum storage duration requirement for Infrequent Access.

    For more information, see Storage fees.

  • Data retrieval fees for Infrequent Access

    Fees for accessing files in the Infrequent Access storage class are calculated based on the amount of data retrieved. For more information, see Data processing fees.

  • Request fees

    A lifecycle rule incurs request fees when it transitions an object's storage class. For more information, see Request fees.

Overwrite semantics

The PutBucketLifecycle operation overwrites the existing configurations of a lifecycle rule of a bucket. For example, if a lifecycle rule named Rule1 is configured for a bucket and you want to configure another lifecycle rule named Rule2 for the bucket, perform the following operations:

  • Call the GetBucketLifecycle operation to query Rule1.

  • Add both Rule1 and Rule2 to the lifecycle rule configuration.

  • Call the PutBucketLifecycle operation to create Rule1 and Rule2 for the bucket.

Effective time

After a lifecycle rule is created, OSS loads the rule within 24 hours. After the rule is loaded, OSS starts running the rule at 08:00 (UTC+8) every day.

Execution time

  • After a rule takes effect, lifecycle operations such as object deletion, storage class transition, and expiration of multipart upload parts are typically completed within 24 hours for up to 1 billion objects in the China (Hangzhou), China (Shanghai), China (Beijing), China (Zhangjiakou), China (Ulanqab), China (Shenzhen), and Singapore regions. In other regions, these operations are typically completed within 24 hours for up to 100 million objects.

  • Execution may take longer than 24 hours, and in some cases several days or weeks, if there are many objects to scan, many objects to which the lifecycle rule applies, many tags, many versions for a single object, or a high volume of new objects being written while the lifecycle task is running.

    Note

    If versioning is enabled for the bucket, an operation on each version of an object is counted as a separate operation.

Last access time update policy

After access tracking is enabled, OSS updates the LastAccessTime of an object based on the following rules:

  1. Initialization: When access tracking is enabled, OSS sets the LastAccessTime of all objects in the bucket to the time when access tracking was enabled.

  2. Update rules: After the initialization, operations such as downloading or overwriting an object update the LastAccessTime of the object. For more information about which operations update the LastAccessTime of an object, see How common operations affect the last access time of objects.

  3. Update mechanism:

    • The LastAccessTime is updated asynchronously. The update is typically complete within 24 hours.

    • If the same object is accessed multiple times within 24 hours, OSS records the time of the first access as the object's LastAccessTime. Subsequent accesses within the 24-hour period do not trigger an update.

Object storage classes for transition

  • Lifecycle rules based on last access time support transitioning objects from the Standard storage class to the Infrequent Access storage class. You can also choose whether to automatically transition an object back to the Standard storage class upon access.

  • Lifecycle rules based on last access time support transitioning objects from the Standard or Infrequent Access storage class to the Archive, Cold Archive, or Deep Cold Archive storage class. You can also transition objects from the Archive storage class to the Cold Archive or Deep Cold Archive storage class. If you want to transition objects from the Standard or Infrequent Access storage class to the Archive, Cold Archive, or Deep Cold Archive storage class, submit a ticket to request permissions. After your request is approved, you must specify the destination storage class for the transition.

    Important

    After your ticket is approved, if you use a policy based on last access time to transition an object from the Standard or Infrequent Access storage class to the Archive, Cold Archive, or Deep Cold Archive storage class, the last access time of the object in the destination storage class defaults to the time when access tracking was enabled for the bucket.

Configure lifecycle rules in a bucket for which OSS-HDFS is enabled

To configure or modify a lifecycle rule based on the last access time to match all objects in a bucket for which OSS-HDFS is enabled, use the NOT element to exclude the objects that are stored in the .dlsdata/ directory. This prevents lifecycle rule-triggered object deletion or storage class conversion actions from applying to OSS-HDFS data and consequently affecting read and write operations on OSS-HDFS data.

p571593 (1)..jpeg

Procedure

OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the left-side navigation pane, choose Data Management > Lifecycle.

  4. On the Lifecycle page, turn on the Enable Access Tracking switch, and then click Create Rule.

  5. In the Create Lifecycle Rule panel, configure the lifecycle rule based on the following descriptions.

    • The bucket has versioning disabled

      Section

      Parameter

      Description

      Basic Settings

      Status

      Set the status of the lifecycle rule. You can select Enabled or Disabled.

      • If you enable the lifecycle rule, OSS transitions the storage classes of data based on the rule.

      • If you disable the lifecycle rule, the lifecycle task is suspended.

      Applied To

      Select the objects to which the lifecycle rule applies. You can select Objects with Specified Prefix or Whole Bucket.

      Allow Overlapped Prefixes

      By default, OSS checks whether the prefixes of lifecycle rules overlap. For example, you set the following two lifecycle rules with overlapping prefixes:

      • Rule 1

        Transitions all objects with the prefix dir1/ in the bucket to the Infrequent Access storage class 180 days after their last access time.

      • Rule 2

        Transitions all objects with the prefix dir1/dir2/ in the bucket to the Archive storage class 30 days after their last access time.

      If this option is not selected, OSS rejects this configuration because objects in the dir1/dir2/ directory would match both transition rules.

      If this option is selected, objects in the dir1/dir2/ directory are transitioned to the Archive storage class after 30 days. Other objects in the dir1/ directory are transitioned to the Infrequent Access storage class after 180 days.

      Prefix

      Enter the object prefix for the rule to match.

      • If you set the prefix to img, the rule matches all objects whose names start with img, such as imgtest.png and img/example.jpg.

      • If you set the prefix to img/, the rule matches all objects whose names start with img/, such as img/example.jpg and img/test.jpg.

      Tag

      The lifecycle rule applies only to objects with the specified tag. For example, if you select Objects with Specified Prefix, set the prefix to img, and set the tag key to a and value to 1, the rule matches all objects whose names start with img and that have the tag a=1. For more information about object tags, see Object tagging.

      NOT

      Use the NOT option to exclude objects that have a specified prefix and tag from the lifecycle rule.

      Important
      • If the NOT option is enabled, you must specify at least a prefix or a tag.

      • The key defined for the tag in the NOT condition cannot be the same as the key defined in the Tag parameter.

      • If the NOT option is enabled, you cannot configure a part expiration policy.

      Object Size

      Specify the object size to which the lifecycle rule applies.

      • Minimum Size: The lifecycle rule applies to objects larger than this value. The value must be greater than 0 B and less than 5 TB.

      • Maximum Size: The lifecycle rule applies to objects smaller than this value. The value must be greater than 0 B and less than or equal to 5 TB.

      Important

      If you configure both Minimum size and Maximum size in the same lifecycle rule, take note of the following items:

      • Make sure that the value of Maximum size is greater than the value of Minimum size.

      • You cannot configure a part expiration policy.

      • You cannot configure a policy to clear delete markers.

      Policy for Objects

      Object Lifecycle

      Select an expiration policy for objects. You can select Validity Period (Days), Expiration Date, or Disabled. If you select Disabled, the object expiration policy does not take effect.

      Lifecycle-based Rules

      Configure the rule to transition the storage class of objects. Data can be transitioned to the following storage classes:

      • IA (Data Remains in IA After Access)

      • IA (Data Is Converted to Standard After Access)

      • Archive

      • Cold Archive

      • Deep Cold Archive

      For example, if you select the Access Time policy, set Validity Period (Days) to 30, and specify that data is automatically transitioned to IA (Data Remains in IA After Access) after the specified period, an object last accessed on September 1, 2021 is transitioned to that storage class on October 1, 2021.

      Policy for Parts

      Part Lifecycle

      Set the action to perform on expired parts. If you have specified a Tag, you cannot configure this parameter. You can select Validity Period (Days) or Expiration Date for the part expiration policy, or select Disabled. If you select Disabled, the part expiration policy does not take effect.

      Important

      A lifecycle rule must include at least an object expiration policy or a part expiration policy.

      Rules for Parts

      Specify when parts expire based on the validity period or expiration date selected in the part expiration policy. Expired parts are automatically deleted and cannot be recovered.

    • The bucket has versioning enabled

      After you enable versioning, the configuration items in the Basic Settings and Policy for Parts sections are configured in the same way as they are when versioning is disabled. The following table describes only the configuration differences when versioning is enabled.

      Section

      Parameter

      Description

      Policy for Current Versions

      Clear delete markers

      After versioning is enabled, the Clear Delete Markers option is added to the cleanup policy. Other options are the same as when versioning is disabled.

      If you select this option and the current version of an object is the only version and is a delete marker, OSS removes the delete marker of the expired object. If the object has multiple versions and the latest version is a delete marker, OSS retains the delete marker. For more information about delete markers, see Delete markers.

      Policy for Previous Versions

      Object Lifecycle

      Set the expiration policy for noncurrent versions of objects. You can select Validity Period (Days) or Disabled. If you select Disabled, the object expiration policy does not take effect.

      Lifecycle-based Rules

      Set a period of N days. After a noncurrent version of an object is accessed, it is transitioned to a different storage class after N days. For example, if you set the period to 30 days, a noncurrent version that is accessed on September 1, 2021 is transitioned to the specified storage class on October 1, 2021.

  6. Click OK.

    After you save the rule, it appears in the policy list.

Alibaba Cloud SDKs

OSS SDKs for Java, Go, Python, and PHP support the creation of lifecycle rules based on last access time. Before you create a lifecycle rule based on last access time, you must enable access tracking for the specified bucket. For sample code, see SDK overview.

Java

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.*;
import java.util.ArrayList;
import java.util.List;

public class Demo {

    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        // Call the shutdown method to release resources when the OSSClient is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            ossClient.putBucketAccessMonitor(bucketName, AccessMonitor.AccessMonitorStatus.Enabled.toString());
            // Create a lifecycle rule and set the ID to rule1. Specify that the storage classes of objects whose names contain the logs prefix and whose size is less than or equal to 64 KB are changed to IA 30 days after the objects are last accessed. In addition, specify that the objects whose name contain the logs prefix are still stored as IA objects when the objects are accessed again. 
            LifecycleRule lifecycleRule = new LifecycleRule("rule1", "logs", LifecycleRule.RuleStatus.Enabled);
            List<LifecycleRule> lifecycleRuleList = new ArrayList<LifecycleRule>();
            SetBucketLifecycleRequest setBucketLifecycleRequest = new SetBucketLifecycleRequest(bucketName);

            LifecycleRule.StorageTransition storageTransition = new LifecycleRule.StorageTransition();
            storageTransition.setStorageClass(StorageClass.IA);
            storageTransition.setExpirationDays(30);
            storageTransition.setIsAccessTime(true);
            storageTransition.setReturnToStdWhenVisit(false);
            storageTransition.setAllowSmallFile(true);
            List<LifecycleRule.StorageTransition> storageTransitionList = new ArrayList<LifecycleRule.StorageTransition>();
            storageTransitionList.add(storageTransition);
            lifecycleRule.setStorageTransition(storageTransitionList);
            lifecycleRuleList.add(lifecycleRule);
            
            // Create a lifecycle rule and set the ID to rule2. Specify that the previous versions of the objects whose names contain the dir prefix and whose size is greater than 64 KB are changed to IA 10 days after the objects are last accessed. In addition, specify that the storage classes of the objects whose names contain the dir prefix are changed to Standard when the objects are accessed again. 
            LifecycleRule lifecycleRule2 = new LifecycleRule("rule2", "dir", LifecycleRule.RuleStatus.Enabled);
            LifecycleRule.NoncurrentVersionStorageTransition noncurrentVersionStorageTransition = new LifecycleRule.NoncurrentVersionStorageTransition();
            noncurrentVersionStorageTransition.setStorageClass(StorageClass.IA);
            noncurrentVersionStorageTransition.setNoncurrentDays(10);
            noncurrentVersionStorageTransition.setIsAccessTime(true);
            noncurrentVersionStorageTransition.setReturnToStdWhenVisit(true);
            noncurrentVersionStorageTransition.setAllowSmallFile(false);

            List<LifecycleRule.NoncurrentVersionStorageTransition> noncurrentVersionStorageTransitionList = new ArrayList<LifecycleRule.NoncurrentVersionStorageTransition>();
            noncurrentVersionStorageTransitionList.add(noncurrentVersionStorageTransition);
            lifecycleRule2.setNoncurrentVersionStorageTransitions(noncurrentVersionStorageTransitionList);
            lifecycleRuleList.add(lifecycleRule2);

            setBucketLifecycleRequest.setLifecycleRules(lifecycleRuleList);

            // Configure the lifecycle rules. 
            ossClient.setBucketLifecycle(setBucketLifecycleRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Python

import argparse
import datetime
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="put bucket lifecycle sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
  args = parser.parse_args()
  credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
  cfg = oss.config.load_default()
  cfg.credentials_provider = credentials_provider
  cfg.region = args.region
  if args.endpoint is not None:
    cfg.endpoint = args.endpoint
  client = oss.Client(cfg)

  result = client.put_bucket_lifecycle(oss.PutBucketLifecycleRequest(
    bucket=args.bucket,
    lifecycle_configuration=oss.LifecycleConfiguration(
      rules=[
        oss.LifecycleRule(
          id='rule1',
          status='Enabled',
          prefix='data/',
          transitions=[oss.LifecycleRuleTransition(
            days=200,
            storage_class=oss.StorageClassType.IA,
            is_access_time=True,
            return_to_std_when_visit=False
          )]
        ),
        oss.LifecycleRule(
          id='rule2',
          status='Enabled',
          prefix='log/',
          transitions=[
            oss.LifecycleRuleTransition(
              days=120,
              storage_class=oss.StorageClassType.IA,
              is_access_time=True,
              return_to_std_when_visit=False
            ),
            oss.LifecycleRuleTransition(
              days=250,
              storage_class=oss.StorageClassType.ARCHIVE
              # If is_access_time is not set, the rule is based on the last modified time by default.
            )
          ]
        )
      ]
    )
  ))

  print(f'status code: {result.status_code}, '
        f'request id: {result.request_id}')

if __name__ == "__main__":
  main()

Go

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // The region where the bucket is located.
	bucketName string // The name of the bucket.
)

// The init function initializes command-line arguments.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command-line arguments.
	flag.Parse()

	// Check if the bucket name is provided.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check if the region is provided.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configuration, and set the credentials provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to set lifecycle rules for the bucket.
	request := &oss.PutBucketLifecycleRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		LifecycleConfiguration: &oss.LifecycleConfiguration{
			Rules: []oss.LifecycleRule{
				{
					// In lifecycle rule "rule1", transition all objects with the prefix "data/"
					// to the Infrequent Access (IA) storage class 200 days after they are last accessed.
					// When these objects are accessed again, they remain in the IA storage class.
					ID:     oss.Ptr("rule1"),
					Status: oss.Ptr("Enabled"),
					Prefix: oss.Ptr("data/"),
					Transitions: []oss.LifecycleRuleTransition{
						{
							Days:                 oss.Ptr(int32(200)),
							StorageClass:         oss.StorageClassIA,
							IsAccessTime:         oss.Ptr(true), // Set to true for a rule based on last access time.
							ReturnToStdWhenVisit: oss.Ptr(false),
						},
					},
				},
				{
					// In lifecycle rule "rule2", transition all objects with the prefix "log/"
					// to the Infrequent Access (IA) storage class 120 days after they are last accessed.
					// In the same rule, transition these objects to the Archive storage class 250 days after they are last accessed.
					// When these objects are accessed again, they remain in their current storage class.
					ID:     oss.Ptr("rule2"),
					Status: oss.Ptr("Enabled"),
					Prefix: oss.Ptr("log/"),
					Transitions: []oss.LifecycleRuleTransition{
						{
							Days:                 oss.Ptr(int32(120)),
							StorageClass:         oss.StorageClassIA,
							IsAccessTime:         oss.Ptr(true), // Set to true for a rule based on last access time.
							ReturnToStdWhenVisit: oss.Ptr(false),
						},
						{
							Days:                 oss.Ptr(int32(250)),
							StorageClass:         oss.StorageClassArchive,
							IsAccessTime:         oss.Ptr(true),
							ReturnToStdWhenVisit: oss.Ptr(false),
						},
					},
				},
			},
		},
	}

	// Set the lifecycle rules for the bucket.
	result, err := client.PutBucketLifecycle(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket lifecycle %v", err)
	}

	// Print the result of setting the lifecycle rules.
	log.Printf("put bucket lifecycle result:%#v\n", result)
}

PHP

<?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;

// Specify descriptions for 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 list of long options to parse the command-line parameters
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon after 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"; // Prompt the user for missing required parameters
        exit(1); 
    }
}

// Obtain the values of the command-line parameters
$region = $options["region"]; // The region in which the bucket is located
$bucket = $options["bucket"]; // The name of the bucket

// Use environment variables to load the AccessKey ID and AccessKey secret
$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);

// Specify the endpoint if an endpoint is provided
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance
$client = new Oss\Client($cfg);

// Define a lifecycle rule to convert objects whose names contain the log/ prefix to the IA storage class after 30 days
$lifecycleRule = new Oss\Models\LifecycleRule(
    prefix: 'log/', // The prefix of the object
    transitions: array(
        new Oss\Models\LifecycleRuleTransition(
            days: 30, // The conversion time is 30 days
            storageClass: 'IA', // The target storage class is IA
            IsAccessTime: 'true', // Whether to trigger the conversion based on the access time
            ReturnToStdWhenVisit: 'false' // Keep as IA storage when accessed again
        )
    ),
    id: 'rule', // The ID of the rule
    status: 'Enabled' // The status of the rule is enabled
);

// Create a lifecycle configuration object and add the lifecycle rule
$lifecycleConfiguration = new LifecycleConfiguration(
    rules: array($lifecycleRule)
);

// Create a request object to set the lifecycle of the bucket and pass in the lifecycle configuration
$request = new Oss\Models\PutBucketLifecycleRequest(
    bucket: $bucket,
    lifecycleConfiguration: $lifecycleConfiguration
);

// Call the putBucketLifecycle method to set the lifecycle rules for the bucket
$result = $client->putBucketLifecycle($request);

// Display the returned result
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP response status code
    'request id:' . $result->requestId . PHP_EOL // The unique identifier of the request
);

ossutil

You can use ossutil to configure lifecycle rules. For more information about how to install ossutil, see Install ossutil.

The following example shows how to configure a lifecycle rule for the examplebucket bucket:

ossutil api put-bucket-lifecycle --bucket examplebucket--lifecycle-configuration "{\"Rule\":{\"ID\":\"rule1\",\"Prefix\":\"tmp/\",\"Status\":\"Enabled\",\"Expiration\":{\"Days\":\"10\"},\"Transition\":{\"Days\":\"5\",\"StorageClass\":\"IA\",\"IsAccessTime\":true,\"ReturnToStdWhenVisit\":true},\"AbortMultipartUpload\":{\"Days\":\"10\"}}}"

For more information about this command, see put-bucket-lifecycle.

API reference

The preceding operations are based on API calls. If you require a high degree of customization, you can send REST API requests directly. This requires you to write your own code to calculate signatures. For more information, see PutBucketLifecycle.

FAQ

What happens if I create two lifecycle rules for objects that have the same prefix in a bucket, where one rule is based on the last modified time and the other is based on the last access time?

For example, you create two lifecycle rules for the destination bucket named examplebucket. Rule 1 specifies that all objects with the doc prefix are deleted 30 days after their last modified time. Rule 2 specifies that all objects with the doc prefix are transitioned to the Infrequent Access storage class 30 days after their last access time.

OSS runs lifecycle rules based on the principle of minimizing user costs. Therefore, only Rule 1 takes effect. This is because Rule 1 specifies that the matching objects are deleted after 30 days, after which no fees are incurred. In contrast, Rule 2 transitions objects to the Infrequent Access storage class, which still incurs storage fees and data retrieval fees.

When does a change to a configured lifecycle rule take effect, and how is the data that matched the original rule handled?

For example, you have configured a lifecycle rule for objects with the prefix er to be transitioned to the Infrequent Access storage class 30 days after the last access and then to be transitioned back to the Standard storage class if accessed after an additional 30 days. However, 35 days after the last access, you change the prefix in the lifecycle rule from er to re. In this case, the original objects only transition to the Infrequent Access storage class. The subsequent transition to the Standard storage class does not occur. The last access time for objects that match the new rule is also counted from when access tracking was enabled for the bucket.

If Intelligent Tiering is enabled in a versioning-enabled bucket, how do storage tiers apply to different versions of an object?

Each object in a versioning-enabled bucket has a unique version ID, and objects with different version IDs are independent of each other. Therefore, a noncurrent version of an object may be in the Infrequent Access storage class while the current version is in the Standard storage class.

Can I disable access tracking?

Yes, provided that no lifecycle rules based on last access time exist in the bucket. After access tracking is disabled, the system stops tracking the last access time of objects. The next time you enable access tracking, the system refreshes the last access time for all objects.

References

The last access time (LastAccessTime) is an important attribute of an object and is used in scenarios such as billing and lifecycle rules. After access tracking is enabled for a bucket, some operations on an object may update its LastAccessTime. For more information, see How common operations affect the last access time of objects.