boto v2.15.0 版本详解:Elastic Transcoder 音频转码、新区域扩展与 SQS/EC2 参数增强
boto v2.15.0 版本详解:Elastic Transcoder 音频转码、新区域扩展与 SQS/EC2 参数增强
boto v2.15.0(发布于 2013 年 10 月 17 日)是 Python 接口到 Amazon Web Services 的经典 SDK(即当前仓库 boto v2 系列)的一个中期能力增强版本。本次发布聚焦于五条主线:为 Amazon Elastic Transcoder 引入音频转码支持、为 S3 / Glacier / Redshift 增加以 ap-southeast-2 为代表的新区域、为 SQS 的 get_queue 与 EC2 的 create_image 增加新参数、为 lss3 工具加入 marker 分页能力,并修复了 DynamoDB、SWF、MWS、S3 等模块的多处缺陷。阅读本文后,你将掌握这些新特性在 boto/sqs/connection.py、boto/ec2/connection.py、boto/elastictranscoder/layer1.py 等源码中的真实调用方式,以及 v2.15.0 在网络重试、SSH 超时等运维细节上的改进。
版本概览:一个面向媒体转码与全球区域覆盖的增量版本
v2.15.0 的发布说明(docs/source/releasenotes/v2.15.0.rst)概括了该版本的核心变化:
- 功能(Features):Elastic Transcoder 音频转码、S3 / Glacier / Redshift 新区域、SQS
get_queue新增owner_acct_id、EC2create_image新增block_device_mapping、lss3支持 marker 分页、SSH 超时选项、SWF 教程与示例代码。 - 缺陷修复(Bugfixes):DynamoDB item
attrs初始化、MWS 空成员列表解析、S3 复制 key 时不再校验 bucket、HTTP 502/504 错误重试、VPC / ELB 文档修复等。
从版本演进的节奏看,该版本与前后版本(v2.14.0、v2.16.0 等)共同构成了 boto v2 在 2013 年下半年对 AWS 新服务和新区域持续跟进的过程。如果你正在维护基于 boto v2 的存量脚本,本文所列的特性均可直接对照源码确认其实现位置。
新区域扩展:S3 网站端点、Glacier 与 Redshift
S3 网站端点的 ap-southeast-2 映射
该版本为 S3WebsiteEndpointTranslate 增加了 ap-southeast-2(悉尼)区域,使其在生成 S3 静态网站端点时能够正确映射主机名。相关实现位于 boto/s3/bucket.py:
class S3WebsiteEndpointTranslate(object):
trans_region = defaultdict(lambda: 's3-website-us-east-1')
trans_region['eu-west-1'] = 's3-website-eu-west-1'
trans_region['eu-central-1'] = 's3-website.eu-central-1'
trans_region['us-west-1'] = 's3-website-us-west-1'
trans_region['us-west-2'] = 's3-website-us-west-2'
trans_region['sa-east-1'] = 's3-website-sa-east-1'
trans_region['ap-northeast-1'] = 's3-website-ap-northeast-1'
trans_region['ap-southeast-1'] = 's3-website-ap-southeast-1'
trans_region['ap-southeast-2'] = 's3-website-ap-southeast-2'
trans_region['cn-north-1'] = 's3-website.cn-north-1'
其中 trans_region 是一个以 defaultdict 为底层的映射,未列出的区域会回退到 s3-website-us-east-1;translate_region 类方法被 Bucket 对象在生成网站端点时调用(见 boto/s3/bucket.py)。同时在 boto/s3/connection.py 中定义了 APSoutheast2 = 'ap-southeast-2' 连接区域常量,配合 boto/auth.py 中的区域字符串,共同保证签名与请求目标主机的一致性。
S3 连接区域常量的典型用法:
from boto.s3.connection import S3Connection, Location
conn = S3Connection()
# 在 ap-southeast-2 区域创建 bucket
bucket = conn.create_bucket('my-bucket-sydney', location=Location.APSoutheast2)
Glacier 与 Redshift 新增区域
与 S3 类似,该版本把 ap-southeast-2 加入了 Glacier,并把 ap-southeast-1、ap-southeast-2 加入了 Redshift。这些区域在 boto/endpoints.json 中有完整声明(该文件中 ap-southeast-2 出现在 S3、Glacier、Redshift 等多个服务的端点映射中,例如 S3 的 hostname: s3-ap-southeast-2.amazonaws.com,见 boto/endpoints.json)。
在代码中连接新区域的方式是显式传入区域参数,例如:
from boto.glacier.layer2 import Layer2
from boto.redshift.layer1 import RedshiftConnection
glacier = Layer2(region_name='ap-southeast-2')
redshift = RedshiftConnection(region_name='ap-southeast-2')
如果区域未在 endpoints.json 中出现,boto 会依据 regioninfo.py 的默认逻辑进行解析;因此新增区域后,任何依赖区域名查找端点的调用(如 boto.connect_s3、boto.connect_glacier)都能无缝使用新区域。
SQS 新参数:跨账号获取队列的 owner_acct_id
v2.15.0 为 SQS 的 get_queue 增加了 owner_acct_id 参数,用于在需要访问其他 AWS 账号创建的队列时指定队列所属账号 ID。实现位于 boto/sqs/connection.py:
def get_queue(self, queue_name, owner_acct_id=None):
"""
Retrieves the queue with the given name, or ``None`` if no match
was found.
:param str queue_name: The name of the queue to retrieve.
:param str owner_acct_id: Optionally, the AWS account ID of the account that created the queue.
:rtype: :py:class:`boto.sqs.queue.Queue` or ``None``
:returns: The requested queue, or ``None`` if no match was found.
"""
params = {'QueueName': queue_name}
if owner_acct_id:
params['QueueOwnerAWSAccountId']=owner_acct_id
try:
return self.get_object('GetQueueUrl', params, Queue)
except SQSError:
return None
关键细节:
- 当
owner_acct_id为空时,get_queue行为与旧版完全一致,只发送QueueName; - 传入该参数后,请求中会带上
QueueOwnerAWSAccountId,从而向 SQS 表明要查找的队列归属账号; - 函数在
SQSError时返回None,因此“队列不存在”与“无权限”等错误在调用侧都表现为空结果,需要调用方注意区分; - 该函数同时以别名
lookup暴露(lookup = get_queue),旧代码中通过lookup获取队列的用法依然有效。
实际使用示例(跨账号读取队列):
from boto.sqs.connection import SQSConnection
conn = SQSConnection(aws_access_key_id='...', aws_secret_access_key='...')
# 对方账号授予了读取权限的前提下
q = conn.get_queue('shared-queue', owner_acct_id='123456789012')
if q is not None:
print('Queue URL:', q.url)
else:
print('Queue not found or inaccessible')
EC2 create_image 支持块设备映射
v2.15.0 为 EC2 的 create_image(由实例创建 AMI)新增了 block_device_mapping 参数,允许在制作镜像时直接描述要附加的 EBS 卷。实现见 boto/ec2/connection.py:
def create_image(self, instance_id, name,
description=None, no_reboot=False,
block_device_mapping=None, dry_run=False):
...
params = {'InstanceId': instance_id,
'Name': name}
if description:
params['Description'] = description
if no_reboot:
params['NoReboot'] = 'true'
if block_device_mapping:
block_device_mapping.ec2_build_list_params(params)
if dry_run:
params['DryRun'] = 'true'
img = self.get_object('CreateImage', params, Image, verb='POST')
return img.id
参数说明:
instance_id:要制作为镜像的实例 ID(运行中或已停止状态均可);name:新镜像的名称;description:可选的镜像描述文本;no_reboot:为 True 时,打包过程不尝试在打包前关闭实例,文件系统完整性由实例所有者负责(适合对数据一致性要求不高的场景,以减少停机);block_device_mapping:一个boto.ec2.blockdevicemapping.BlockDeviceMapping数据结构,用于描述与镜像关联的 EBS 卷;传入后通过其ec2_build_list_params方法把块设备列表序列化为请求参数(见 boto/ec2/blockdevicemapping.py);dry_run:为 True 时只做校验,不真正执行创建。
典型用法:为镜像附加一块 20GB 的 EBS 根卷后创建 AMI:
from boto.ec2.connection import EC2Connection
from boto.ec2.blockdevicemapping import BlockDeviceMapping, BlockDeviceType
conn = EC2Connection()
bdt = BlockDeviceType(size=20, delete_on_termination=True)
bdm = BlockDeviceMapping()
bdm['/dev/sda1'] = bdt
image_id = conn.create_image(
instance_id='i-12345678',
name='my-app-ami',
description='AMI with 20GB root volume',
block_device_mapping=bdm,
)
print('Created AMI:', image_id)
值得注意的是,同文件中的 register_image(第 384 行附近)同样会遍历 image.block_device_mapping 读取每个块的 snapshot_id,说明块设备映射数据结构在整个镜像相关 API 中是一致的。
Elastic Transcoder 音频转码支持
该版本为 Amazon Elastic Transcoder 的预设(preset)创建接口引入了 audio 参数,用于定义音频转码参数。相关代码位于 boto/elastictranscoder/layer1.py:
def create_preset(self, name=None, description=None, container=None,
video=None, audio=None, thumbnails=None):
...
uri = '/2012-09-25/presets'
params = {}
if name is not None:
params['Name'] = name
if description is not None:
params['Description'] = description
if container is not None:
params['Container'] = container
if video is not None:
params['Video'] = video
if audio is not None:
params['Audio'] = audio
if thumbnails is not None:
params['Thumbnails'] = thumbnails
return self.make_request('POST', uri, expected_status=201,
data=json.dumps(params))
从实现看,audio 是以字典形式传递的请求体片段,与 video、thumbnails 并列,最终整体 JSON 序列化后 POST 到 /2012-09-25/presets。这意味着音频转码参数(如编码格式、采样率、码率等)以嵌套字典的方式表达,例如:
from boto.elastictranscoder.layer1 import ElastictranscoderConnection
et = ElastictranscoderConnection()
preset = et.create_preset(
name='mp3-192k',
description='MP3 192kbps audio preset',
container='mp3',
audio={
'Codec': 'mp3',
'BitRate': '192',
'SampleRate': '44100',
},
)
与音频转码相配合的还有同文件中 create_job、create_pipeline 等接口,它们共同构成了 Elastic Transcoder 的媒体处理流水线:先建 pipeline(管道)、再建 preset(预设)、最后提交 job(作业)。v2.15.0 补齐音频参数后,boto 可以完整表达纯音频或音视频混合的转码预设。
运维与工具链改进:lss3 marker 分页、SSH 超时与 HTTP 502/504 重试
lss3 支持 marker 分页
lss3 是 boto 自带的命令行工具(位于 scripts/ 目录),用于以 ls 风格列出 S3 对象。v2.15.0 为其加入 marker 支持(对应 issue #1783),使超大 bucket 的列举不再受单次请求返回条数限制。marker 语义与 S3 的 ListObjects 分页一致:上一次返回的最后一条 key 作为下一次请求的起始位置。该能力让 lss3 可以配合 shell 脚本做分批拉取或断点续列。
SSH 超时选项(pyami/manage)
v2.15.0 为基于 pyami 的实例管理(boto/pyami/)增加了 SSH 超时选项(issue #1755),用于控制远程执行命令时 SSH 连接/读取的等待上限,避免在网络抖动或远端无响应时脚本长时间挂起。该选项通过配置或调用参数传入 cmdssh 等管理入口,适合批量运维场景。
HTTP 502/504 错误自动重试
此前 boto 的 _mexe 重试逻辑仅覆盖 500、503 等状态码,v2.15.0 将 502(Bad Gateway)与 504(Gateway Timeout)一并纳入自动重试列表,见 boto/connection.py:
if response.status in [500, 502, 503, 504]:
msg = 'Received %d response. ' % response.status
msg += 'Retrying in %3.1f seconds' % next_sleep
boto.log.debug(msg)
body = response.read()
if isinstance(body, bytes):
body = body.decode('utf-8')
配套的重试次数机制在 boto/connection.py:默认 num_retries = 6,可通过 Boto 配置节中的 num_retries 项(config.getint('Boto', 'num_retries', self.num_retries))覆盖,各高层 layer1 客户端(如 CloudTrail、CloudHSM、CodeDeploy 等)在构造时也常显式传入 override_num_retries=10。这意味着面对网关层瞬时故障,boto 会自动按退避策略重试,提升脚本在弱网或服务波动下的健壮性。
缺陷修复盘点
v2.15.0 的 Bugfix 列表同样值得关注,它们解决的都是实际使用中的痛点:
- DynamoDB item
attrs初始化(issue #1776):修复boto.dynamodb.item.Item的属性字典初始化问题,避免在部分构造路径下attrs未被正确建立而抛异常; - MWS 空成员列表解析(issue #1785):修复 Amazon Marketplace Web Service 响应中空成员列表的解析,防止空列表被错误处理;
- S3 复制 key 时不再校验 bucket(issue #1763):
copy_key等复制操作此前会对源 bucket 做额外校验,在跨账号或特殊权限场景下会误报错误,本次修复移除了该多余校验; - 文档修复(issue #1770、#1797):修正 VPC 模块文档、ELB 文档的格式问题,并更新 SWF 教程与示例代码(issue #1769、#1797),同时修复了版本发布说明之间的链接。
这些修复与 S3、DynamoDB、SWF、MWS 模块直接相关,与前述新特性共同构成了 v2.15.0 的完整变更集。
升级与兼容性建议
- 升级后如需使用新区域,请确认使用的 boto 版本包含 boto/endpoints.json 中对应的区域条目;若为自定义 endpoint 场景,也可通过显式传入
host覆盖; get_queue的owner_acct_id是纯增量参数,旧调用不受影响;但注意函数对任何SQSError都返回None,跨账号权限不足与队列不存在无法从返回值直接区分;create_image新增的block_device_mapping需要构造BlockDeviceMapping对象,若你的脚本此前通过register_image管理块设备,可复用同一数据结构;- 502/504 自动重试的加入会改变失败场景下的等待时长,若对重试节奏敏感,可通过配置节
[Boto] num_retries调整。
总体而言,boto v2.15.0 是一次典型的“新服务能力 + 区域覆盖 + 参数增强 + 健壮性修复”组合发布。对于媒体转码、悉尼区域部署、跨账号 SQS 访问和自定义 AMI 制作等场景,该版本提供了直接的 API 与命令行支持,其实现均可在上文列出的源码路径中逐一核对。