低頻度アクセス (IA) 、アーカイブ、コールドアーカイブ、およびディープコールドアーカイブオブジェクトには、最小保存期間があります。 オブジェクトのストレージクラスが変換された場合、またはオブジェクトが最小保存期間内に削除された場合、保存期間が最小保存期間に満たなかったオブジェクトのストレージ使用量に対して課金されます。 不要な料金の発生を回避するには、さまざまなストレージクラスのオブジェクトが最小保存期間要件を満たしているかどうかを判断し、オブジェクトのストレージクラスを変換またはオブジェクトを削除する前に、最小保存期間要件が満たされていることを確認する方法を理解しておく必要があります。
ストレージクラス別のオブジェクトの最小保存期間
ストレージクラス | 最短保存期間 | 計算方法 |
標準 | 非該当 | 非該当 |
IA | 30 | オブジェクトの最終変更時刻に基づきます。 |
アーカイブ | 60 | オブジェクトの最終変更時刻に基づきます。 |
コールドアーカイブ | 180 | オブジェクトのストレージクラスがコールドアーカイブに変換された時間に基づきます。 |
ディープコールドアーカイブ | 180 | オブジェクトのストレージクラスがディープコールドアーカイブに変換された時間に基づきます。 |
例
以下のサンプルコードでは、オブジェクトのメタデータをクエリし、オブジェクトの LastModified パラメーターと TransitionTime パラメーターの値を現在の時刻と比較して、オブジェクトが最小保存期間要件を満たしているかどうかを判断する方法の例を示します。
Java
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.HeadObjectRequest;
import com.aliyuncs.exceptions.ClientException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Demo {
public static void main(String[] args) throws ClientException {
// バケットが配置されているリージョンのエンドポイントを指定します。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// エンドポイントにマップするリージョンのIDを指定します。例:cn-hangzhou。
String region = "cn-hangzhou";
// 環境変数からアクセス認証情報を取得します。サンプルコードを実行する前に、OSS_ACCESS_KEY_IDおよびOSS_ACCESS_KEY_SECRET環境変数が設定されていることを確認してください。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// バケットの名前を指定します。
String bucketName = "examplebucket";
// OSSClientインスタンスを作成します。
// OSSClientが使用されなくなったときにリソースを解放するには、shutdownメソッドを呼び出します。
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// V4署名アルゴリズムの使用を明示的に宣言します。
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
// オブジェクトの完全なパスを指定します。
String[] objectNames = {"example.txt"};
// ストレージクラスと最小ストレージ期間のマッピング。単位:日。
Map<String, Integer> minimumRetentionPeriod = new HashMap<>();
minimumRetentionPeriod.put("Standard", 0);
minimumRetentionPeriod.put("IA", 30);
minimumRetentionPeriod.put("Archive", 60);
minimumRetentionPeriod.put("ColdArchive", 180);
minimumRetentionPeriod.put("DeepColdArchive", 180);
for (String objectName : objectNames) {
objectName = objectName.trim();
try {
// オブジェクトメタデータをクエリします。
HeadObjectRequest headObjectRequest = new HeadObjectRequest(bucketName, objectName);
ObjectMetadata objectMetadata = ossClient.headObject(headObjectRequest);
// オブジェクトのストレージクラスと最終更新時刻をクエリします。
String storageClass = String.valueOf(objectMetadata.getObjectStorageClass());
String lastModifiedStr = objectMetadata.getLastModified().toString();
Date lastModified = objectMetadata.getLastModified();
if ("ColdArchive".equals(storageClass) || "DeepColdArchive".equals(storageClass)) {
Object transitionTimeObj = objectMetadata.getRawMetadata().get("x-oss-transition-time");
String transitionTimeStr = String.valueOf(transitionTimeObj);
Date transitionTime = DateUtil.parseRfc822Date(transitionTimeStr);
if (transitionTime != null) {
lastModified = transitionTime;
} else {
throw new Exception("オブジェクト '" + objectName + "' のストレージクラス: " + storageClass
+ ", x-oss-transition-time" + transitionTimeStr + ". ");
}
}
// 現在の時刻をクエリします。
Date currentTime = new Date();
// オブジェクトのストレージ期間を計算します。単位:日。
long storageDuration = (currentTime.getTime() - lastModified.getTime()) / (1000 * 60 * 60 * 24);
// オブジェクト情報を表示します。
System.out.println("オブジェクト名: " + objectName);
System.out.println("ストレージクラス: " + storageClass);
System.out.println("作成日時: " + lastModifiedStr);
System.out.println("ストレージ期間: " + storageDuration + "日");
// オブジェクトが最小ストレージ期間の要件を満たしているかどうかを判断します。
if (minimumRetentionPeriod.containsKey(storageClass)) {
int minRetention = minimumRetentionPeriod.get(storageClass);
if (storageDuration < minRetention) {
int daysRemaining = minRetention - (int) storageDuration;
System.out.println(objectName + " は最小ストレージ期間の要件を満たしていません。オブジェクトはさらに " + daysRemaining + " 日間保存する必要があります。オブジェクトを削除すると、最小ストレージ期間未満保存されているオブジェクトのストレージ使用量の "
+ daysRemaining + " 日間が課金されます。");
} else {
int daysExceeded = (int) storageDuration - minRetention;
System.out.println(objectName + " は最小ストレージ期間の要件を満たしています。オブジェクトは最小ストレージ期間よりも " + daysExceeded + " 日多く保存されています。最小ストレージ期間未満保存されているオブジェクトのストレージ使用量は課金されません。");
}
} else {
System.out.println(objectName + " のストレージクラスが認識されません。");
}
System.out.println("----------------------------------------"); // デリミタ。
} catch (Exception e) {
e.printStackTrace();
System.out.println(objectName + " のメタデータをクエリ中にエラーが発生しました: " + e.getMessage());
System.out.println("----------------------------------------"); // デリミタ。
}
}
// OSSClientインスタンスをシャットダウンします。
ossClient.shutdown();
}
}Python
import datetime
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# 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.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Specify the full path of the single object.
object_names = ['example.txt']
# The mapping between the storage class and the minimum storage duration. Unit: days.
minimum_retention_period = {
'Standard': 0,
'IA': 30,
'Archive': 60,
'ColdArchive': 180,
'DeepColdArchive': 180
}
for object_name in object_names:
object_name = object_name.strip()
try:
# Query all object metadata by using the head_object method.
object_info = bucket.head_object(object_name)
# Query the storage class and last modified time of the object.
storage_class = object_info.headers['x-oss-storage-class']
last_modified = object_info.headers['Last-Modified']
# Change the last modified time to the datetime object.
last_modified_time = datetime.datetime.strptime(last_modified, '%a, %d %b %Y %H:%M:%S GMT')
transition_time_str = object_info.headers.get('x-oss-transition-time')
transition_time = None
if storage_class == 'ColdArchive' or storage_class == 'DeepColdArchive':
if transition_time_str:
last_modified_time = datetime.datetime.strptime(transition_time_str, "%a, %d %b %Y %H:%M:%S %Z")
else:
raise Exception(f"Storage class of '{object_name}': {storage_class}. x-oss-transition-time: {transition_time_str}.")
# Query the current time.
current_time = datetime.datetime.now()
# Calculate the storage duration of the object. Unit: days.
storage_duration = (current_time - last_modified_time).days
# Display the object information.
print(f "Object name: {object_name}")
print(f "Storage class: {storage_class}")
print(f "Created at: {last_modified}")
print(f "Storage duration: {storage_duration} days")
# Determine whether the object meets the minimum storage duration requirements.
if storage_class in minimum_retention_period:
min_retention = minimum_retention_period[storage_class]
if storage_duration < min_retention:
days_remaining = min_retention - storage_duration
print(f"{object_name} does not meet the minimum storage duration requirements. The object needs to be stored for another {days_remaining} days. If you delete the object, you are charged {days_remaining} days of the storage usage for the object that is stored for less than the minimum storage duration.")
else:
days_exceeded = storage_duration - min_retention
print(f"{object_name} meets the minimum storage duration requirements. The object is stored {days_exceeded} days more than the minimum storage duration. You are not charged for the storage usage for the object that is stored for less than the minimum storage duration.")
else:
print(f"The storage class of {object_name} is not recognized.")
print("-" * 40) # The delimiter.
except Exception as e:
print(f "An error occurred when I query the metadata of {object_name}: {str(e)}")
print("-" * 40) # The delimiter Node. js
const OSS = require("ali-oss");
// 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.
const config = {
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// 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 oss-cn-hangzhou.
region: "oss-cn-hangzhou",
// Specify the name of the bucket.
bucket: "examplebucket",
};
const client = new OSS(config);
// The mapping between the storage class and the minimum storage duration. Unit: days.
const minimum_retention_period = {
Standard: 0,
IA: 30,
Archive: 60,
ColdArchive: 180,
DeepColdArchive: 180,
};
// Calculate the time difference in days.
function getDays(date1, date2) {
if (!(date1 instanceof Date) || !(date2 instanceof Date)) {
throw new Error("Need to pass valid Date objects");
}
const timestamp1 = date1.getTime();
const timestamp2 = date2.getTime();
const diffInMilliseconds = Math.abs(timestamp2 - timestamp1);
const diffInDays = diffInMilliseconds / (1000 * 60 * 60 * 24);
return Math.round(diffInDays);
}
// Specify the full path of the object.
const object_names = ["example.jpg"];
(async () => {
for (const object_name of object_names) {
try {
// Query all metadata of the object by using the head method.
const object_info = await client.head(object_name);
const { headers } = object_info.res;
// Query the storage class and last modified time of the object.
const storage_class = headers["x-oss-storage-class"];
const last_modified = headers["last-modified"];
let last_modified_time = new Date(last_modified);
const transition_time_str = headers["x-oss-transition-time"];
if (["ColdArchive", "DeepColdArchive"].includes(storage_class)) {
if (transition_time_str)
last_modified_time = new Date(transition_time_str);
else {
const errorStr = Storage class of 'Object '${object_name}': ${storage_class}. x-oss-transition-time: ${transition_time_str}. x-oss-transition-time is available only for objects whose storage class is converted to Cold Archive or Deep Cold Archive based on lifecycle rules.
throw new Error(errorStr);
}
}
const current_time=new Date(); // Query the current time.
const storage_duration=getDays (current_time, last_modified_time); // Calculate the storage duration of the object. Unit: days.
// Display the object information.
console.log ('Object name: ${object_name}');
console.log ('Storage class: ${storage_class}');
console.log ('Created at: ${last_modified}');
console.log ('Storage duration: ${storage_duration} days ');
// Determine whether the object meets the minimum storage duration requirements.
if (Object.keys(minimum_retention_period).includes(storage_class)) {
min_retention = minimum_retention_period[storage_class];
if (storage_duration < min_retention) {
const days_remaining = min_retention - storage_duration;
console.log(
'${object_name} does not meet the minimum storage duration requirements. The object needs to be stored for another ${days_remaining} days. If you delete the object, you are charged ${days_remaining} days of the storage usage for the object that is stored for less than the minimum storage duration. `
);
} else {
const days_exceeded = storage_duration - min_retention;
console.log(
'${object_name} meets the minimum storage duration requirements. The object is stored ${days_exceeded} days more than the minimum storage duration. You are not charged for the storage usage for the object that is stored for less than the minimum storage duration. `
);
}
} else console.log(The storage class of the '${object_name} is not recognized. `);
} catch (e) {
console.log ('An error occurred when I query the metadata of ${object_name}:', e);
}
}
})();
PHP
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = 'http://oss-cn-hangzhou.aliyuncs.com';
// Specify the name of the bucket.
$bucketName = 'examplebucket';
// Create an OSSClient instance.
try {
// 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.
$provider = new EnvironmentVariableCredentialsProvider();
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
);
$ossClient = new OssClient($config);
// Specify the full path of the object.
$objectNames = ['example.txt'];
$minimumRetentionPeriod = [
'Standard' => 0,
'IA' => 30,
'Archive' => 60,
'ColdArchive' => 180,
'DeepColdArchive' => 180,
];
foreach ($objectNames as $objectName) {
$objectName = trim($objectName);
try {
// Query all metadata of an object by using the headObject method.
$objectInfo = $ossClient->getObjectMeta($bucketName, $objectName);
// Query the storage class and last modified time of the object.
$storageClass = $objectInfo['x-oss-storage-class'];
$lastModified = $objectInfo['last-modified'];
// Convert the last modified time of the object to a timestamp.
$lastModifiedTime = strtotime($lastModified);
if (in_array($storageClass, array("ColdArchive", "DeepColdArchive")) && isset($objectInfo["x-oss-transition-time"])) {
$lastModifiedTime = strtotime($objectInfo["x-oss-transition-time"]);
}
// Query the current time.
$currentTime = time();
// Calculate the storage duration of the object. Unit: days.
$storageDuration = floor(($currentTime - $lastModifiedTime) / (60 * 60 * 24));
// Display the object information.
echo "Object name: $objectName\n";
echo "Storage class: $storageClass\n";
echo "Created at: $lastModified\n";
echo "Storage duration: $storageDuration days\n";
// Determine whether the object meets the minimum storage duration requirements.
if (isset($minimumRetentionPeriod[$storageClass])) {
$minRetention = $minimumRetentionPeriod[$storageClass];
if ($storageDuration < $minRetention) {
$daysRemaining = $minRetention - $storageDuration;
echo "$objectName does not meet the minimum storage duration requirements. The object needs to be stored for another $daysRemaining days. If you delete the object, you are charged $daysRemaining days of the storage usage for the object that is stored for less than the minimum storage duration. \n";
} else {
$daysExceeded = $storageDuration - $minRetention;
System.out.println(echo "$objectName meets the minimum storage duration requirements. The object is stored $daysExceeded days more than the minimum storage duration. You are not charged for the storage usage for the object that is stored for less than the minimum storage duration. \n";
}
} else {
The storage class of echo "$objectName is not recognized. \n";
}
echo str_repeat("-", 40) . "\n"; // The delimiter.
} catch (OssException $e) {
echo "An error occurred when I query the metadata of $objectName: " . $e->getMessage() . "\n";
echo str_repeat("-", 40) . "\n"; // The delimiter.
}
}
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
Go
package main
import (
"context"
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
func main() {
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion("cn-hangzhou").
WithEndpoint("https://oss-cn-hangzhou.aliyuncs.com")
client := oss.NewClient(cfg)
// チェックするオブジェクトの完全なパスを指定します。
objectNames := []string{"example.txt"}
// 各ストレージクラスの最小保存期間(日数)を定義します。
minimumRetentionPeriod := map[string]int{
"Standard": 0,
"IA": 30,
"Archive": 60,
"ColdArchive": 180,
"DeepColdArchive": 180,
}
// バケット名を指定します。
bucketName := "examplebucket"
for _, objectName := range objectNames {
objectName = strings.TrimSpace(objectName)
if objectName == "" {
continue
}
// オブジェクトのメタデータを取得します。
objectInfo, err := client.HeadObject(context.TODO(), &oss.HeadObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
})
if err != nil {
log.Printf("%s のメタデータを取得する際にエラーが発生しました: %v\n", objectName, err)
continue
}
// storageClassがnilかどうかを確認します。
if objectInfo.StorageClass == nil {
log.Printf("警告: %s のストレージクラスがnilです。このオブジェクトをスキップします。\n", objectName)
continue
}
storageClass := *objectInfo.StorageClass
currentTime := time.Now().Unix()
// 保存期間を日数で計算します。
storageDuration := (currentTime - objectInfo.LastModified.Unix()) / (60 * 60 * 24)
// Cold ArchiveおよびDeep Cold Archiveの場合、移行時間が利用可能であればそれを使用します。
if storageClass == "ColdArchive" || storageClass == "DeepColdArchive" {
transitionTimeStr := objectInfo.Headers.Get("x-oss-transition-time")
if transitionTimeStr != "" {
transitionTime, err := time.Parse(http.TimeFormat, transitionTimeStr)
if err != nil {
log.Printf("警告: %s のx-oss-transition-timeの解析に失敗しました: %v。作成時間を使用します。\n", objectName, err)
} else {
storageDuration = (currentTime - transitionTime.Unix()) / (60 * 60 * 24)
}
}
}
// オブジェクトの基本情報を出力します。
fmt.Printf("オブジェクト名: %s\n", objectName)
fmt.Printf("ストレージクラス: %s\n", storageClass)
fmt.Printf("作成日時: %s\n", objectInfo.LastModified.Format("2006-01-02 15:04:05"))
fmt.Printf("保存期間: %d 日\n", storageDuration)
// 最小保存期間の要件を満たしているかどうかを確認します。
minRetention, exists := minimumRetentionPeriod[storageClass]
if !exists {
fmt.Printf("%s のストレージクラスは認識されません。\n", objectName)
fmt.Println("----------------------------------------")
continue
}
if minRetention == 0 {
// Standardストレージクラスには最小保存期間の要件がありません。
fmt.Printf("%s はStandardストレージクラスを使用しており、最小保存期間の要件がありません。オブジェクトを削除しても、最小保存期間未満の容量料金は発生しません。\n", objectName)
} else {
daysRemaining := minRetention - int(storageDuration)
if daysRemaining > 0 {
// オブジェクトは最小保存期間の要件を満たしていません。
fmt.Printf("%s は最小保存期間の要件を満たしていません。オブジェクトをさらに %d 日間保存する必要があります。今オブジェクトを削除すると、最小保存期間未満で保存されたオブジェクトの %d 日分のストレージ使用料金が発生します。\n",
objectName, daysRemaining, daysRemaining)
} else {
// オブジェクトは最小保存期間の要件を満たしています。
fmt.Printf("%s は最小保存期間の要件を満たしています(%d 日間保存、要件 %d 日)。オブジェクトを削除しても、最小保存期間未満の容量料金は発生しません。\n",
objectName, int(storageDuration), minRetention)
}
}
fmt.Println("----------------------------------------")
}
}関連ドキュメント
上記のサンプルコードでは、head_object メソッドを使用してオブジェクトのメタデータをクエリし、オブジェクトの LastModified および TransitionTime パラメーターの値を現在の時刻と比較して、オブジェクトが最小保存期間要件を満たしているかどうかを判断する方法の例を示しています。複数のオブジェクトに対して最小保存期間要件を満たしているかどうかを判断する必要がある場合は、GetBucket (ListObjects)、ListObjectVersions (GetBucketVersions)、および ListBucketInventory API 操作を呼び出します。