分片上传、对象锁定与 STS 分片上传、保留期与法律保留,以及临时凭据。
说明
分片上传、S3 桶事件通知与 IAM 服务账号在 MVP 范围内属于受支持 功能;对象锁定(保留期与法律保留)、基于 silo_api 的 SQL 事务 outbox 以及 Basic AssumeRole STS 属于预览 功能。
本教程演示五项多步骤工作流:带失败清理的分片上传、对象锁定保留期与法律保留(legal hold)、S3 桶 Webhook 通知、与对象同事务提交的 SQL outbox,以及服务账号与 Basic AssumeRole STS 临时凭据。开始前请先完成使用 S3 SDK 。
分片上传与失败清理 除最后一个分片外,每个分片大小至少为 5 MiB;合并后的对象总大小不得超过存储的对象大小上限(默认 256 MiB,初始化时最高可设为 1 GiB)。
以下脚本上传一个 5 MiB 首片和一个短尾片,列举已上传分片,按分片号顺序完成合并,并在未完成时通过 finally 终止上传以清理残留分片:
import os
import boto3
from botocore.config import Config
session = boto3 . Session ( profile_name = "silo-admin" , region_name = "us-east-1" )
s3 = session . client (
"s3" ,
endpoint_url = os . environ [ "SILO_ENDPOINT" ],
verify = os . environ [ "AWS_CA_BUNDLE" ],
config = Config ( signature_version = "s3v4" , s3 = { "addressing_style" : "path" }),
)
bucket , key = "attachments" , "workflows/multipart.bin"
chunks = [ b "A" * ( 5 * 1024 * 1024 ), b "last part \n " ]
upload_id = s3 . create_multipart_upload ( Bucket = bucket , Key = key )[ "UploadId" ]
completed = False
try :
parts = []
for number , chunk in enumerate ( chunks , start = 1 ):
part = s3 . upload_part (
Bucket = bucket , Key = key , UploadId = upload_id , PartNumber = number , Body = chunk
)
parts . append ({ "PartNumber" : number , "ETag" : part [ "ETag" ]})
listed = s3 . list_parts ( Bucket = bucket , Key = key , UploadId = upload_id )
assert [ p [ "PartNumber" ] for p in listed [ "Parts" ]] == [ 1 , 2 ]
s3 . complete_multipart_upload (
Bucket = bucket , Key = key , UploadId = upload_id , MultipartUpload = { "Parts" : parts }
)
completed = True
finally :
if not completed :
s3 . abort_multipart_upload ( Bucket = bucket , Key = key , UploadId = upload_id )
response = s3 . get_object ( Bucket = bucket , Key = key )
try :
assert response [ "Body" ] . read () == b "" . join ( chunks )
print ( "Multipart upload verified" )
finally :
response [ "Body" ] . close () 除 s3:PutObject 与 s3:GetObject 外,应用策略还需要 s3:AbortMultipartUpload(清理未完成上传)和 s3:ListMultipartUploadParts(列举分片),列举桶内所有进行中的上传任务则需授予桶级 s3:ListBucketMultipartUploads。由于进程崩溃可能跳过 finally,建议同时配置 AbortIncompleteMultipartUpload 生命周期规则(见版本控制 )。
对象锁定、保留期与法律保留 建桶时启用对象锁定会同时启用版本控制。以下脚本创建带 1 天默认 GOVERNANCE 保留期的 lock-demo 桶,写入一个版本后将其保留期延长至 2 天并开启法律保留(legal hold),验证删除该版本会返回 AccessDenied,最后解除法律保留:
import base64
import hashlib
import os
from datetime import datetime , timedelta , timezone
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
session = boto3 . Session ( profile_name = "silo-admin" , region_name = "us-east-1" )
s3 = session . client (
"s3" ,
endpoint_url = os . environ [ "SILO_ENDPOINT" ],
verify = os . environ [ "AWS_CA_BUNDLE" ],
config = Config ( signature_version = "s3v4" , s3 = { "addressing_style" : "path" }),
)
bucket , key = "lock-demo" , "retained.txt"
s3 . create_bucket ( Bucket = bucket , ObjectLockEnabledForBucket = True )
s3 . put_object_lock_configuration (
Bucket = bucket ,
ObjectLockConfiguration = {
"ObjectLockEnabled" : "Enabled" ,
"Rule" : { "DefaultRetention" : { "Mode" : "GOVERNANCE" , "Days" : 1 }},
},
)
body = b "retain this version \n "
created = s3 . put_object (
Bucket = bucket ,
Key = key ,
Body = body ,
ContentMD5 = base64 . b64encode ( hashlib . md5 ( body , usedforsecurity = False ) . digest ()) . decode ( "ascii" ),
)
version = created [ "VersionId" ]
s3 . put_object_retention (
Bucket = bucket ,
Key = key ,
VersionId = version ,
Retention = {
"Mode" : "GOVERNANCE" ,
"RetainUntilDate" : datetime . now ( timezone . utc ) + timedelta ( days = 2 ),
},
)
s3 . put_object_legal_hold (
Bucket = bucket , Key = key , VersionId = version , LegalHold = { "Status" : "ON" }
)
print ( s3 . get_object_retention ( Bucket = bucket , Key = key , VersionId = version )[ "Retention" ])
print ( s3 . get_object_legal_hold ( Bucket = bucket , Key = key , VersionId = version )[ "LegalHold" ])
try :
s3 . delete_object ( Bucket = bucket , Key = key , VersionId = version )
except ClientError as error :
if error . response [ "Error" ][ "Code" ] != "AccessDenied" :
raise
print ( "Protected version deletion denied" )
else :
raise AssertionError ( "Protected version was unexpectedly deleted" )
s3 . put_object_legal_hold (
Bucket = bucket , Key = key , VersionId = version , LegalHold = { "Status" : "OFF" }
) 不指定 VersionId 的 delete_object 只会插入删除标记,不会删除受保护的版本。绕过 GOVERNANCE 保留期需要显式传入绕过请求头并具备 s3:BypassGovernanceRetention 权限;处于有效期内的 COMPLIANCE 保留期不可绕过。silo_api SQL 接口同样强制执行保留期与法律保留约束,且不提供治理保留绕过参数。
S3 桶事件通知 如需将 S3 请求路径上的事件发送到 HTTPS Webhook 接收端,请在所有可写网关的 /etc/default/silo 中配置相同的目标 ID(APP)并重启网关:
MINIO_NOTIFY_WEBHOOK_ENABLE_APP = "on"
MINIO_NOTIFY_WEBHOOK_ENDPOINT_APP = "https://events.example.net/silo"
MINIO_NOTIFY_WEBHOOK_AUTH_TOKEN_APP = "REPLACE_WITH_RECEIVER_TOKEN" 随后使用格式为 arn:minio:sqs:<region>:<target-id>:webhook 的 QueueArn 为桶配置通知规则:
import os
import boto3
from botocore.config import Config
session = boto3 . Session ( profile_name = "silo-admin" , region_name = "us-east-1" )
s3 = session . client (
"s3" ,
endpoint_url = os . environ [ "SILO_ENDPOINT" ],
verify = os . environ [ "AWS_CA_BUNDLE" ],
config = Config ( signature_version = "s3v4" , s3 = { "addressing_style" : "path" }),
)
bucket = "notification-demo"
s3 . create_bucket ( Bucket = bucket )
s3 . put_bucket_notification_configuration (
Bucket = bucket ,
NotificationConfiguration = {
"QueueConfigurations" : [
{
"Id" : "application-events" ,
"QueueArn" : "arn:minio:sqs:us-east-1:APP:webhook" ,
"Events" : [ "s3:ObjectCreated:*" , "s3:ObjectRemoved:*" ],
"Filter" : { "Key" : { "FilterRules" : [{ "Name" : "suffix" , "Value" : ".txt" }]}},
}
],
},
)
s3 . put_object ( Bucket = bucket , Key = "event.txt" , Body = b "notification example \n " )
s3 . delete_object ( Bucket = bucket , Key = "event.txt" ) S3 Webhook 通知在 S3 HTTP 请求提交后异步投递,接收端应当容忍重试与重复事件。通过 silo_api 直接执行的 SQL 写入不会触发 S3 桶通知。
SQL outbox 与对象共同提交 如果业务事件必须与业务行及对象在同一个事务里共同提交或回滚,可以在同一个 Read Committed SQL 事务中写入业务自有的 outbox 表(沿用用 SQL 操作对象 中的 app_sql 会话):
CREATE TABLE app_demo . outbox (
event_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY ,
event_type text NOT NULL ,
payload jsonb NOT NULL ,
created_at timestamptz NOT NULL DEFAULT clock_timestamp (),
delivered_at timestamptz
);
BEGIN ISOLATION LEVEL READ COMMITTED ;
WITH written AS (
SELECT * FROM silo_api . put_object (
'attachments' , 'invoices/1003.txt' ,
convert_to ( 'invoice 1003 amount 399.00' , 'UTF8' ), 'text/plain'
)
), invoice AS (
INSERT INTO app_demo . invoices
( invoice_id , object_key , object_id , object_version , amount )
SELECT 1003 , 'invoices/1003.txt' , object_id , version_id , 399 . 00 FROM written
RETURNING invoice_id , object_key , object_version
)
INSERT INTO app_demo . outbox ( event_type , payload )
SELECT 'invoice.ready' , jsonb_build_object (
'invoice_id' , invoice_id , 'bucket' , 'attachments' ,
'key' , object_key , 'version_id' , object_version
) FROM invoice ;
COMMIT ; 外部消费者轮询 app_demo.outbox,按 event_id 幂等投递事件后更新 delivered_at。
服务账号与短期 STS 身份 在不暴露父用户主密钥的前提下,为 app-s3 创建服务账号并将凭据保存到受限文件:
(
umask 077
set -o noclobber
mcli_pg --json admin user svcacct add pg-admin app-s3 --name attachments-service > " $SILO_CLIENT_CONFIG /attachments-service.json"
)
mcli_pg admin user svcacct list pg-admin app-s3 如需通过 Basic AssumeRole STS 获取 15 分钟(900 秒)有效期的临时凭据,请使用普通 IAM 用户(silo-app)签名调用 AssumeRole。服务账号与已有 STS 临时凭据不能再次调用 Basic AssumeRole,且低于 900 秒的有效期请求会被拒绝:
import json
import os
import boto3
from botocore.config import Config
parent = boto3 . Session ( profile_name = "silo-app" , region_name = "us-east-1" )
endpoint , ca = os . environ [ "SILO_ENDPOINT" ], os . environ [ "AWS_CA_BUNDLE" ]
sts = parent . client (
"sts" , endpoint_url = endpoint , verify = ca , config = Config ( signature_version = "v4" )
)
limited_policy = {
"Version" : "2012-10-17" ,
"Statement" : [
{
"Effect" : "Allow" ,
"Action" : [ "s3:GetObject" ],
"Resource" : [ "arn:aws:s3:::attachments/sdk.txt" ],
}
],
}
credentials = sts . assume_role (
RoleArn = "arn:aws:iam::123456789012:role/silo-session" ,
RoleSessionName = "read-sdk-object" ,
DurationSeconds = 900 ,
Policy = json . dumps ( limited_policy ),
)[ "Credentials" ]
temporary = boto3 . client (
"s3" ,
endpoint_url = endpoint ,
region_name = "us-east-1" ,
verify = ca ,
aws_access_key_id = credentials [ "AccessKeyId" ],
aws_secret_access_key = credentials [ "SecretAccessKey" ],
aws_session_token = credentials [ "SessionToken" ],
config = Config ( signature_version = "s3v4" , s3 = { "addressing_style" : "path" }),
)
response = temporary . get_object ( Bucket = "attachments" , Key = "sdk.txt" )
try :
print ( response [ "Body" ] . read () . decode ( "utf-8" ))
finally :
response [ "Body" ] . close ()
print ( "Expires:" , credentials [ "Expiration" ] . isoformat ()) 内联会话策略(Policy)只能在父用户权限范围内进一步收窄权限,不能扩大父用户权限。RoleArn 仅为兼容 S3/STS 请求参数格式而保留,不会连接或创建外部 AWS IAM 角色。
扫码打开此页 https://mimus.pgsty.com/zh/docs/s3/tutorial/workflows/
复制链接