Misc

访问控制列表

swift.common.middleware.acl.acls_from_account_info(info)

从给定的 account_info 中提取账户 ACL,并返回 ACL。

参数:

info – 一个字典,其格式由 get_account_info 返回

返回值:

None(未设置 ACL 系统元数据),或一个字典,格式如下:{‘admin’: […], ‘read-write’: […], ‘read-only’: […]}

引发:

ValueError – 当头部语法无效时

swift.common.middleware.acl.clean_acl(name, value)

返回一个清理后的 ACL 头部值,验证它是否符合标准 Swift ACL 字符串的格式要求。

ACL 格式为

[item[,item...]]

每个条目都可以是授予访问权限的组名,或基于 HTTP Referer 头部授予或拒绝访问的引用者标识。

引用者标识格式为

.r:[-]value

.r 也可以是 .ref.referer.referrer;但为了减少字符数,它会被缩短为 .r

值可以是 * 来指定允许任何引用者主机访问,也可以是特定主机名,如 www.example.com;如果它以句点 .*. 开头,则表示域名规范,如 .example.com*.example.com。 前导减号 - 表示应拒绝访问的引用者主机。

引用者访问按照指定的顺序应用。例如,`.r:.example.com,.r:-thief.example.com` 将允许所有以 `.example.com` 结尾的主机访问,但拒绝特定主机 `thief.example.com`。

示例有效 ACL

.r:*
.r:*,.r:-.thief.com
.r:*,.r:.example.com,.r:-thief.example.com
.r:*,.r:-.thief.com,bobs_account,sues_account:sue
bobs_account,sues_account:sue

示例无效 ACL

.r:
.r:-

默认情况下,通过 `.r` 允许读取访问不会允许列出容器中的对象 – 仅允许从容器中检索对象。要启用列表功能,请使用 `.rlistings` 指令。

此外,`.r` 标识不允许出现在名称中包含“write”一词的头部中。

“杂乱”的 ACL 将被清理。示例

原始

清理后

bob, sue

bob,sue

bob , sue

bob,sue

bob,,,sue

bob,sue

.referrer : *

.r:*

.ref:*.example.com

.r:.example.com

.r:*, .rlistings

.r:*,.rlistings

参数:
  • name – 要清理的头部的名称,例如 X-Container-Read 或 X-Container-Write。

  • value – 要清理的头部的值。

返回值:

经过多余格式清理后的值。

引发:

ValueError – 如果值不符合 ACL 格式要求;错误消息将说明原因。

swift.common.middleware.acl.format_acl(version=1, **kwargs)

兼容性包装器,用于帮助将 ACL 语法从版本 1 迁移到版本 2。委托给适当的版本特定 format_acl 方法,默认使用版本 1 以实现向后兼容。

参数:

kwargs – 适用于所选 ACL 语法版本的关键字参数(参见 format_acl_v1()format_acl_v2()

swift.common.middleware.acl.format_acl_v1(groups=None, referrers=None, header_name=None)

为给定的输入返回一个标准的 Swift ACL 字符串。

调用者负责确保仅在生成 X-Container-Read 的 ACL 时才提供 :referrers: 参数。(X-Container-Write 和账户 ACL 头部不支持引用者。)

参数:
  • groups – 要授予访问权限的组(以及大多数身份验证系统中的成员)列表

  • referrers – 引用者标识列表(不含前导 .r:)

  • header_name – (可选) 正在准备的 ACL 的头部名称,用于 clean_acl;如果为 None,则返回的 ACL 不会被清理

返回值:

可用于 X-Container-{Read,Write}、X-Account-Access-Control 等的 Swift ACL 字符串。

swift.common.middleware.acl.format_acl_v2(acl_dict)

返回版本 2 的 Swift ACL JSON 字符串。

版本 2 ACL 的 HTTP 头部格式如下:

Header-Name: {“arbitrary”:”json”,”encoded”:”string”}

JSON 将强制为 ASCII(包含六位数的 uNNNN 序列,而不是 UTF-8;UTF-8 是有效的 JSON,但客户端对 UTF-8 头部支持程度不一),并且不包含多余的空格。

与 V1 相比的优点:向前兼容性(新键不会导致解析异常);Unicode 支持;没有保留字(你可以有一个名为 `.rlistings` 的用户)。

参数:

acl_dict – 要放入 ACL 的任意数据的字典;请参阅特定身份验证系统(如 tempauth)以获取支持的值

返回值:

编码 ACL 的 JSON 字符串

swift.common.middleware.acl.parse_acl(*args, **kwargs)

兼容性包装器,用于帮助将 ACL 语法从版本 1 迁移到版本 2。委托给适当的版本特定 parse_acl 方法,并尝试从 args/kwargs 的类型中确定版本。

参数:
返回值:

parse_acl_v1()parse_acl_v2() 的返回值

swift.common.middleware.acl.parse_acl_v1(acl_string)

将标准的 Swift ACL 字符串解析为引用者列表和组列表。

有关标准 Swift ACL 格式的文档,请参阅 clean_acl()

参数:

acl_string – 要解析的标准 Swift ACL 字符串。

返回值:

一个元组 (referrers, groups),其中 referrers 是引用者标识列表(不含前导 .r:),groups 是允许访问的组列表。

swift.common.middleware.acl.parse_acl_v2(data)

解析版本 2 的 Swift ACL 字符串并返回一个 ACL 信息字典。

参数:

data – 包含 JSON 格式 ACL 数据的字符串

返回值:

一个字典(可能为空),包含 ACL 信息,例如:{“groups”: […], “referrers”: […]}

返回值:

如果 data 为 None、不是有效的 JSON 或无法解析为字典,则返回 None。

返回值:

如果 data 为空字符串,则返回空字典。

swift.common.middleware.acl.referrer_allowed(referrer, referrer_acl)

根据 referrer_acl 列表(由 parse_acl() 返回)判断是否应允许引用者访问。返回 True 或 False。

有关标准 Swift ACL 格式的文档,请参阅 clean_acl()

参数:
  • referrer – HTTP Referer 头部的值。

  • referrer_acl – 由 parse_acl() 返回的引用者标识列表。

返回值:

如果应允许引用者访问,则返回 True;否则返回 False。

Buffered HTTP

Monkey Patch httplib.HTTPResponse 以缓冲头部读取。当大量进行小型 HTTP 请求时,这可以提高性能。此模块还提供使用 BufferedHTTPResponse 创建 HTTP 连接的辅助函数。

警告

如果您使用此功能,请确保您使用的库不直接访问套接字(xmlrpclib,我就是说你 :)),而是通过 httplib 进行所有调用。

class swift.common.bufferedhttp.BufferedHTTPConnection(host, port=None, timeout=<object object>, source_address=None)

Bases: HTTPConnection

使用 BufferedHTTPResponse 的 HTTPConnection 类

connect()

连接到 __init__ 中指定的服务器和端口。

getresponse()

从服务器获取响应。

如果 HTTPConnection 处于正确状态,则返回 HTTPResponse 实例或 response_class 变量返回的任何对象。

如果尚未发送请求或尚未处理前一个响应,则会引发 ResponseNotReady。如果 HTTP 响应指示应关闭连接,则在返回响应之前会关闭连接。关闭连接时,会关闭底层套接字。

putheader(header, value)

向服务器发送请求头部行。

例如:h.putheader(‘Accept’, ‘text/html’)

putrequest(method, url, skip_host=0, skip_accept_encoding=0)

向服务器发送请求。

参数:
  • method – 指定 HTTP 请求方法,例如 ‘GET’。

  • url – 指定请求的对象,例如 ‘/index.html’。

  • skip_host – 如果为 True,则不自动添加 ‘Host:’ 头部

  • skip_accept_encoding – 如果为 True,则不自动添加 ‘Accept-Encoding:’ 头部

response_class

BufferedHTTPResponse 的别名 (BufferedHTTPResponse)

class swift.common.bufferedhttp.BufferedHTTPResponse(sock, debuglevel=0, strict=0, method=None)

Bases: HTTPResponse

缓冲读取头部的 HTTPResponse 类

close()

刷新并关闭 IO 对象。

如果文件已关闭,此方法无效。

nuke_from_orbit()

以极大的偏见终止套接字。

无论是否有人拥有该套接字的其他引用,都会关闭底层套接字。当您确定您关心的任何人都没有对该套接字拥有引用时,请使用此方法。

read(amt=None)

读取并返回最多 n 个字节。

如果省略大小参数,则为 None 或负数,则读取并返回直到 EOF 的所有数据。

如果大小参数为正,并且底层原始流不是“交互式的”,则可能发出多个原始读取来满足字节数(除非首先达到 EOF)。但是,对于交互式原始流(以及套接字和管道),最多只会发出一个原始读取,并且结果短不意味着 EOF 即将到来。

在 EOF 时返回一个空字节对象。

如果底层原始流以非阻塞模式打开且当前没有可用数据,则返回 None。

swift.common.bufferedhttp.http_connect(ipaddr, port, device, partition, method, path, headers=None, query_string=None, ssl=False)

创建 HTTPConnection 对象的辅助函数。如果 ssl 设置为 True,则使用 HTTPSConnection。但是,如果 ssl=False,则使用 BufferedHTTPConnection,它针对后端 Swift 服务进行了缓冲。

参数:
  • ipaddr – 要连接的 IPv4 地址

  • port – 要连接的端口

  • device – 要查询的节点的设备

  • partition – 设备上的分区

  • method – 请求的 HTTP 方法(‘GET’、‘PUT’、‘POST’ 等)

  • path – 请求路径

  • headers – 头部字典

  • query_string – 请求查询字符串

  • ssl – 如果使用 SSL,则设置为 True(默认值:False)

返回值:

HTTPConnection 对象

swift.common.bufferedhttp.http_connect_raw(ipaddr, port, method, path, headers=None, query_string=None, ssl=False)

创建 HTTPConnection 对象的辅助函数。如果 ssl 设置为 True,则使用 HTTPSConnection。但是,如果 ssl=False,则使用 BufferedHTTPConnection,它针对后端 Swift 服务进行了缓冲。

参数:
  • ipaddr – 要连接的 IPv4 地址

  • port – 要连接的端口

  • method – 请求的 HTTP 方法(‘GET’、‘PUT’、‘POST’ 等)

  • path – 请求路径

  • headers – 头部字典

  • query_string – 请求查询字符串

  • ssl – 如果使用 SSL,则设置为 True(默认值:False)

返回值:

HTTPConnection 对象

Config

class swift.common.utils.config.NicerInterpolation

Bases: BasicInterpolation

swift.common.utils.config.affinity_key_function(affinity_str)

将关联性配置值转换为适合传递给 sort() 的函数。执行此操作后,数组将根据给定的顺序进行排序。

例如,如果 affinity_str 是“r1=1, r2z7=2, r2z8=2”,则数组将首先按区域 1(r1=1)的所有节点排序,然后按区域 2 的区域 7 和 8(r2z7=2 和 r2z8=2)的所有节点排序,最后按其余节点排序。

请注意,affinity_str 中各部分的顺序无关紧要;优先级值是等号后面的内容。

如果 affinity_str 为空或全为空格,则生成的函数不会更改节点的排序。

参数:

affinity_str – 关联性配置值,例如“r1z2=3”或“r1=1, r2z1=2, r2z2=2”

返回值:

单参数函数

引发:

ValueError – 参数无效时

swift.common.utils.config.affinity_locality_predicate(write_affinity_str)

将写关联性配置值转换为节点的谓词函数。返回的值将是一个接受节点字典并返回真值(如果节点是“本地”的)或假值(否则)的一元函数。“本地”的定义来自此处传递的 affinity_str 参数。

例如,如果 affinity_str 是“r1, r2z2”,则仅当区域=1 或(区域=2 且区域=2)时,节点才被视为本地。

如果 affinity_str 为空或全为空格,则生成的函数会将所有内容视为本地。

参数:

write_affinity_str – 关联性配置值,例如“r1z2”或“r1, r2z1, r2z2”

返回值:

单参数函数,如果 affinity_str 为空则为 None。

引发:

ValueError – 参数无效时

swift.common.utils.config.config_auto_int_value(value, default)

如果 value 为 None 或 ‘auto’,则返回 default。否则,返回 value 的 int 值或引发 ValueError。

swift.common.utils.config.config_fallocate_value(reserve_value)

返回 fallocate reserve_value 作为 int 或 float。返回 is_percent 作为布尔值。对于无效的 fallocate 值,引发 ValueError。

swift.common.utils.config.config_positive_int_value(value)

如果 value 可以通过 int() 转换为整数且大于 0(不包括零),则返回正整数值。否则引发 ValueError。

swift.common.utils.config.config_read_prefixed_options(conf, prefix_name, defaults)

从配置中读取带前缀的选项

参数:
  • conf – 配置

  • prefix_name – 前缀(如果需要,包括下划线)

  • defaults – 默认值字典。该字典提供选项名称和类型(字符串或逗号分隔的字符串)

返回值:

包含选项的字典

swift.common.utils.config.config_read_reseller_options(conf, defaults)

从配置中读取 reseller_prefix 选项及相关选项

读取 reseller_prefix 选项,然后读取可能与特定 reseller prefix 关联的选项。读取选项,使得没有前缀的选项适用于所有 reseller prefix,除非选项具有显式前缀。

参数:
  • conf – 配置

  • defaults – 默认值字典。键是选项名。值是字符串数组或字符串

返回值:

一对(reseller prefix 数组和选项值字典)

swift.common.utils.config.config_true_value(value)

如果值为 True 或 TRUE_VALUES 中的字符串,则返回 True。否则返回 False。

swift.common.utils.config.non_negative_float(value)

检查该值是否可转换为浮点数且非负。

参数:

value – 要检查的值

引发:

ValueError – 如果该值无法转换为浮点数或为负数。

返回值:

一个浮点数

swift.common.utils.config.non_negative_int(value)

检查该值是否可转换为整数且为整数。

参数:

value – 要检查的值

引发:

ValueError – 如果该值无法转换为整数或不代表整数。

返回值:

一个整数

swift.common.utils.config.parse_prefixed_conf(conf_file, prefix)

搜索配置文件中任何通用前缀的节,并将这些节加载到映射到策略选项的 after-prefix 引用字典中。

参数:
  • conf_file – 要解析的配置文件的名称

  • prefix – 节的通用前缀

返回值:

一个映射策略引用 -> 策略选项字典的字典

引发:

ValueError – 如果策略配置节的名称无效

swift.common.utils.config.readconf(conf_path, section_name=None, log_name=None, defaults=None, raw=False)

读取配置文件并以字典形式返回配置项

参数:
  • conf_path – 配置文件/目录的路径,或文件类对象(具有 readline 属性)

  • section_name – 要读取的配置节(如果未定义,则返回所有节)

  • log_name – 用于日志记录的名称(如果未定义,则使用 section_name)

  • defaults – 用于预填充配置的默认值字典

返回值:

配置项字典

引发:
  • ValueError – section_name 不存在时

  • IOError – 读取文件失败时

Constraints

swift.common.constraints.check_account_format(req, name, *, target_type='Account')

验证头部是否包含有效的账户或容器名称。

参数:
  • req – HTTP 请求对象

  • name – 要验证的头部值

  • target_type – 正在验证哪个头部(Account 或 Container)

返回值:

正确编码的账户名或容器名

引发:

HTTPPreconditionFailed – 如果账户头部格式不正确。

swift.common.constraints.check_container_format(req, name, *, target_type='Container')

验证头部是否包含有效的账户或容器名称。

参数:
  • req – HTTP 请求对象

  • name – 要验证的头部值

  • target_type – 正在验证哪个头部(Account 或 Container)

返回值:

正确编码的账户名或容器名

引发:

HTTPPreconditionFailed – 如果账户头部格式不正确。

swift.common.constraints.check_delete_headers(request)

检查 ‘x-delete-after’ 和 ‘x-delete-at’ 头部的值是否有效。值应为正整数,且大于请求时间戳。

如果找到 ‘x-delete-after’ 头部,则其值用于计算 ‘x-delete-at’ 值,该值优先于任何现有的 ‘x-delete-at’ 头部。

参数:

request – swob 请求对象

引发:

无效值时为 HTTPBadRequest

返回值:

swob 请求对象

swift.common.constraints.check_dir(root, drive)

验证设备路径是否为目录,并且是一个较小的约束,当无法进行完整的 mount_check 时(例如,使用回环或分区的 VM)会强制执行。

参数:
  • root – 目录所在的基路径

  • drive – 要检查的驱动器名称

返回值:

设备的完整路径

引发:

ValueError – 如果驱动器验证失败

swift.common.constraints.check_drive(root, drive, mount_check)

验证 root 和 drive 提供的路径是一个有效存在的目录。

参数:
  • root – 设备挂载的基路径

  • drive – 要检查的驱动器名称

  • mount_check – 此外,需要路径已挂载

返回值:

设备的完整路径

引发:

ValueError – 如果驱动器验证失败

swift.common.constraints.check_float(string)

用于检查字符串是否可以转换为浮点数的辅助函数。

参数:

string – 要验证为浮点数的字符串

返回值:

如果字符串可以转换为浮点数,则返回 True,否则返回 False。

swift.common.constraints.check_metadata(req, target_type)

检查请求头部中发送的元数据。这应该只检查给定请求中的元数据是否有效。对账户/容器总体元数据的检查应转发到其各自的服务器进行检查。

参数:
  • req – 请求对象

  • target_type – str:以下之一:object、container 或 account:表示元数据的目标存储类型

返回值:

否则为 HTTPBadRequest(元数据错误),否则为 None。

swift.common.constraints.check_mount(root, drive)

验证设备路径是否为挂载点并已挂载。这使我们能够快速失败那些由于问题而未挂载的驱动器,并防止我们意外填满根分区。

参数:
  • root – 设备挂载的基路径

  • drive – 要检查的驱动器名称

返回值:

设备的完整路径

引发:

ValueError – 如果驱动器验证失败

swift.common.constraints.check_name_format(req, name, target_type)

验证头部是否包含有效的账户或容器名称。

参数:
  • req – HTTP 请求对象

  • name – 要验证的头部值

  • target_type – 正在验证哪个头部(Account 或 Container)

返回值:

正确编码的账户名或容器名

引发:

HTTPPreconditionFailed – 如果账户头部格式不正确。

swift.common.constraints.check_object_creation(req, object_name)

检查以确保将要创建的对象的一切都正常。

参数:
  • req – HTTP 请求对象

  • object_name – 要创建的对象的名称

返回值:

HTTPEntityTooLarge – 对象过大

返回值:

HTTPLengthRequired – 缺少 content-length 头部且不是分块请求

返回值:

HTTPBadRequest – 缺少或错误的 content-type 头部,或元数据错误

返回值:

HTTPNotImplemented – 不支持的 transfer-encoding 头部值

swift.common.constraints.check_utf8(string, internal=False)

验证字符串是否为有效的 UTF-8 字符串或 Unicode,并且不包含任何保留字符。

参数:
  • string – 要验证的字符串

  • internal – 布尔值,如果为 True,则允许保留字符

返回值:

如果字符串是有效的 utf-8 字符串或 unicode 且不包含空字符,则返回 True,否则返回 False。

swift.common.constraints.reload_constraints()

解析 SWIFT_CONF_FILE 并重置模块级全局约束属性,同时填充 OVERRIDE_CONSTRAINTS 和 EFFECTIVE_CONSTRAINTS。

swift.common.constraints.valid_api_version(version)

检查请求的版本是否有效。

目前 Swift 只支持“v1”和“v1.0”。

swift.common.constraints.valid_timestamp(request)

用于从需要时间戳的请求中提取时间戳的辅助函数。

参数:

request – swob 请求对象

返回值:

有效的 Timestamp 实例

引发:

HTTPBadRequest – 缺少或无效的 X-Timestamp

Container Sync Realms

class swift.common.container_sync_realms.ContainerSyncRealms(conf_path, logger)

基类: object

加载并解析 container-sync-realms.conf,并偶尔检查文件修改时间以确定是否需要重新加载。

clusters(realm)

返回该区域的集群列表。

endpoint(realm, cluster)

返回区域中集群的端点。

get_sig(request_method, path, x_timestamp, nonce, realm_key, user_key)

返回给定信息的 HMAC-SHA1(RFC 2104)的十六进制摘要字符串。

参数:
  • request_method – 请求的 HTTP 方法。

  • path – 资源的路径(URL 编码)。

  • x_timestamp – 请求的 X-Timestamp 头部值。

  • nonce – 请求的唯一值。

  • realm_key – 集群运营商级别的共享密钥。

  • user_key – 用户容器级别的共享密钥。

返回值:

请求的 HMAC-SHA1 的十六进制摘要字符串。

key(realm)

返回该区域的密钥。

key2(realm)

返回该区域的 key2。

realms()

返回区域列表。

reload()

强制重新加载 conf 文件。

Digest

swift.common.digest.extract_digest_and_algorithm(value)

从客户端提供的格式字符串中返回 (digest_algorithm, hex_encoded_digest) 元组。

<hex-encoded digest>

或者

<algorithm>:<base64-encoded digest>

注意,十六进制编码的字符串必须使用 sha1、sha256 或 sha512 中的一个。

引发:

解析失败时引发 ValueError

swift.common.digest.get_allowed_digests(conf_digests, logger=None)

从提供的 conf 中提取 ‘allowed_digests’。然后将其与支持和已弃用的摘要列表进行比较,并返回剩余的摘要。

当某项不受支持或已弃用时,将记录警告。

参数:
  • conf_digests – 允许的摘要的可迭代对象。如果为空,则默认为 DEFAULT_ALLOWED_DIGESTS。

  • logger – 可选的日志记录器;如果提供,则用于发出弃用警告

返回值:

一组允许的摘要,以及一组已弃用的摘要。

引发:

ValueError,如果没有任何摘要可供返回。

swift.common.digest.get_hmac(request_method, path, expires, key, digest='sha1', ip_range=None)

返回请求的 HMAC(参见 RFC 2104)的十六进制摘要字符串。

参数:
  • request_method – 允许的请求方法。

  • path – 要允许访问的资源的路径。

  • expires – URL 过期的 Unix 时间戳(int 类型)。

  • key – HMAC 共享密钥。

  • digest – 用于计算 HMAC 的摘要的构造函数或字符串名称。默认为 SHA1。

  • ip_range – 允许访问该资源的 IP 范围。我们需要将 ip_range 作为 hmac 的第一个参数,以避免由于换行符在路径中有效(例如 /v1/a/c/on127.0.0.1)而导致的路径操纵。

返回值:

使用指定摘要算法的请求的 HMAC 的十六进制摘要字符串。

Direct Client

内部客户端库,用于直接向服务器发出调用,而不是通过代理。

exception swift.common.direct_client.DirectClientException(stype, method, node, part, path, resp, host=None)

Bases: ClientException

exception swift.common.direct_client.DirectClientReconException(method, node, path, resp)

Bases: ClientException

swift.common.direct_client.direct_delete_account(node, part, account, conn_timeout=5, response_timeout=15, headers=None)
swift.common.direct_client.direct_delete_container(node, part, account, container, conn_timeout=5, response_timeout=15, headers=None)

直接从容器服务器删除容器。

参数:
  • node – 环中的节点字典

  • part – 容器所在的区域

  • account – 账户名称

  • container – 容器名称

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

  • headers – 将包含在 HTTPConnection 头部中的字典

引发:

ClientException – HTTP DELETE 请求失败

swift.common.direct_client.direct_delete_container_object(node, part, account, container, obj, conn_timeout=5, response_timeout=15, headers=None)
swift.common.direct_client.direct_delete_object(node, part, account, container, obj, conn_timeout=5, response_timeout=15, headers=None)

直接从对象服务器删除对象。

参数:
  • node – 环中的节点字典

  • part – 容器所在的区域

  • account – 账户名称

  • container – 容器名称

  • obj – 对象名称

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

引发:

ClientException – HTTP DELETE 请求失败

swift.common.direct_client.direct_get_account(node, part, account, marker=None, limit=None, prefix=None, delimiter=None, conn_timeout=5, response_timeout=15, end_marker=None, reverse=None, headers=None)

直接从账户服务器获取列表。

参数:
  • node – 环中的节点字典

  • part – 账户所在的区域

  • account – 账户名称

  • marker – marker 查询

  • limit – 查询限制

  • prefix – prefix 查询

  • delimiter – 查询分隔符

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

  • end_marker – end_marker 查询

  • reverse – 反转返回的列表

返回值:

一个元组 (response headers, a list of containers),其中 response headers 将是 HeaderKeyDict。

swift.common.direct_client.direct_get_container(node, part, account, container, marker=None, limit=None, prefix=None, delimiter=None, conn_timeout=5, response_timeout=15, end_marker=None, reverse=None, headers=None, extra_params=None)

直接从容器服务器获取容器列表。

参数:
  • node – 环中的节点字典

  • part – 容器所在的区域

  • account – 账户名称

  • container – 容器名称

  • marker – marker 查询

  • limit – 查询限制

  • prefix – prefix 查询

  • delimiter – 查询分隔符

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

  • end_marker – end_marker 查询

  • reverse – 反转返回的列表

  • headers – 请求中包含的头部

  • extra_params – 要包含在请求中的额外参数字典。可用于传递其他参数,例如,{‘states’:’updating’} 可与 shard_range/namespace listing 一起使用。也可用于传递现有的关键字参数,如 ‘marker’ 或 ‘limit’,但如果同一参数在关键字参数(非 None)和 extra_params 中都出现,则此函数将引发 TypeError。

返回值:

一个元组 (response headers, a list of objects),其中 response headers 将是 HeaderKeyDict。

swift.common.direct_client.direct_get_object(node, part, account, container, obj, conn_timeout=5, response_timeout=15, resp_chunk_size=None, headers=None)

直接从对象服务器获取对象。

参数:
  • node – 环中的节点字典

  • part – 容器所在的区域

  • account – 账户名称

  • container – 容器名称

  • obj – 对象名称

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

  • resp_chunk_size – 如果已定义,则为要读取的数据的块大小。

  • headers – 将包含在 HTTPConnection 头部中的字典

返回值:

一个元组 (response headers, the object’s contents),其中 response headers 将是 HeaderKeyDict。

引发:

ClientException – HTTP GET 请求失败

swift.common.direct_client.direct_get_recon(node, recon_command, conn_timeout=5, response_timeout=15, headers=None)

直接从存储服务器获取 recon json。

参数:
  • node – 环中的节点字典

  • recon_command – recon 字符串(post /recon/)

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

  • headers – 将包含在 HTTPConnection 头部中的字典

返回值:

反序列化的 json 响应

引发:

DirectClientReconException – HTTP GET 请求失败

swift.common.direct_client.direct_get_suffix_hashes(node, part, suffixes, conn_timeout=5, response_timeout=15, headers=None)

直接从对象服务器获取后缀哈希。

注意,与其他 direct_client 函数不同,此函数默认使用复制网络进行请求。

参数:
  • node – 环中的节点字典

  • part – 容器所在的区域

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

  • headers – 将包含在 HTTPConnection 头部中的字典

返回值:

后缀哈希字典

引发:

ClientException – HTTP REPLICATE 请求失败

swift.common.direct_client.direct_head_container(node, part, account, container, conn_timeout=5, response_timeout=15, headers=None)

直接从容器服务器请求容器信息。

参数:
  • node – 环中的节点字典

  • part – 容器所在的区域

  • account – 账户名称

  • container – 容器名称

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

返回值:

包含响应头部信息的字典,以 HeaderKeyDict 格式。

引发:

ClientException – HTTP HEAD 请求失败

swift.common.direct_client.direct_head_object(node, part, account, container, obj, conn_timeout=5, response_timeout=15, headers=None)

直接从对象服务器请求对象信息。

参数:
  • node – 环中的节点字典

  • part – 容器所在的区域

  • account – 账户名称

  • container – 容器名称

  • obj – 对象名称

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

  • headers – 将包含在 HTTPConnection 头部中的字典

返回值:

包含响应头部信息的字典,以 HeaderKeyDict 格式。

引发:

ClientException – HTTP HEAD 请求失败

swift.common.direct_client.direct_post_container(node, part, account, container, conn_timeout=5, response_timeout=15, headers=None)

向容器服务器发送 POST 请求。

参数:
  • node – 环中的节点字典

  • part – 容器所在的区域

  • account – 账户名称

  • container – 容器名称

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

  • headers – 要包含在请求中的附加标头

引发:

ClientException – HTTP PUT 请求失败

swift.common.direct_client.direct_post_object(node, part, account, container, name, headers, conn_timeout=5, response_timeout=15)

直接在对象服务器上更新对象元数据。

参数:
  • node – 环中的节点字典

  • part – 容器所在的区域

  • account – 账户名称

  • container – 容器名称

  • name – 对象名称

  • headers – 要存储为元数据的标头

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

引发:

ClientException – HTTP POST 请求失败

swift.common.direct_client.direct_put_container(node, part, account, container, conn_timeout=5, response_timeout=15, headers=None, contents=None, content_length=None, chunk_size=65535)

向容器服务器发送 PUT 请求。

参数:
  • node – 环中的节点字典

  • part – 容器所在的区域

  • account – 账户名称

  • container – 容器名称

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

  • headers – 要包含在请求中的附加标头

  • contents – 要在请求正文中发送的可迭代对象或字符串(可选)

  • content_length – 要作为 content-length 标头发送的值(可选)

  • chunk_size – 要发送的数据的块大小(可选)

引发:

ClientException – HTTP PUT 请求失败

swift.common.direct_client.direct_put_container_object(node, part, account, container, obj, conn_timeout=5, response_timeout=15, headers=None)
swift.common.direct_client.direct_put_object(node, part, account, container, name, contents, content_length=None, etag=None, content_type=None, headers=None, conn_timeout=5, response_timeout=15, chunk_size=65535)

直接从对象服务器上传对象。

参数:
  • node – 环中的节点字典

  • part – 容器所在的区域

  • account – 账户名称

  • container – 容器名称

  • name – 对象名称

  • contents – 要从中读取对象数据的可迭代对象或字符串

  • content_length – 要作为 content-length 标头发送的值

  • etag – 内容的 etag

  • content_type – 要作为 content-type 标头发送的值

  • headers – 要包含在请求中的附加标头

  • conn_timeout – 建立连接的超时时间(秒)

  • response_timeout – 获取响应的超时时间(秒)

  • chunk_size – 如果定义了,则为要发送的数据的块大小。

返回值:

服务器响应中的 etag

引发:

ClientException – HTTP PUT 请求失败

swift.common.direct_client.gen_headers(hdrs_in=None, add_ts=True)

准备请求的标头。所有请求都应具有 User-Agent 字符串,但如果已提供,则不覆盖它。并非所有请求都需要 X-Timestamp,但如果已提供,则不覆盖它。

参数:
  • headers – 字典或 None,HTTP 标头的基准

  • add_ts – 布尔值,对于任何“不安全”的 HTTP 请求,应为 True

返回值:

基于标头并为请求准备好的 HeaderKeyDict

swift.common.direct_client.retry(func, *args, **kwargs)

用于多次重试给定函数的辅助函数。

参数:
  • func – 要调用的可调用对象

  • retries – 重试次数

  • error_log – 错误日志记录器

  • args – 要发送到 func 的参数

  • kwargs – 要发送到 func 的关键字参数(如果发送了 retries 或 error_log,它们将被删除,然后再发送到 func)

返回值:

func 的结果

引发:

ClientException – 所有重试都失败了

异常

exception swift.common.exceptions.APIVersionError

Bases: SwiftException

exception swift.common.exceptions.ChunkReadError

Bases: SwiftException

exception swift.common.exceptions.ChunkReadTimeout(seconds=None, exception=None)

Bases: Timeout

exception swift.common.exceptions.ChunkWriteTimeout(seconds=None, exception=None)

Bases: Timeout

exception swift.common.exceptions.ClientException(msg, http_scheme='', http_host='', http_port='', http_path='', http_query='', http_status=None, http_reason='', http_device='', http_response_content='', http_headers=None)

基础: Exception

exception swift.common.exceptions.ConnectionTimeout(seconds=None, exception=None)

Bases: Timeout

exception swift.common.exceptions.DatabaseAuditorException

Bases: SwiftException

exception swift.common.exceptions.DevIdBytesTooSmall

Bases: ValueError

exception swift.common.exceptions.DeviceUnavailable

Bases: SwiftException

exception swift.common.exceptions.DiskFileBadMetadataChecksum

Bases: DiskFileError

exception swift.common.exceptions.DiskFileCollision

Bases: DiskFileError

exception swift.common.exceptions.DiskFileDeleted(metadata=None)

Bases: DiskFileNotExist

exception swift.common.exceptions.DiskFileDeviceUnavailable

Bases: DiskFileError

exception swift.common.exceptions.DiskFileError

Bases: SwiftException

exception swift.common.exceptions.DiskFileExpired(metadata=None)

Bases: DiskFileDeleted

exception swift.common.exceptions.DiskFileNoSpace

Bases: DiskFileError

exception swift.common.exceptions.DiskFileNotExist

Bases: DiskFileError

exception swift.common.exceptions.DiskFileNotOpen

Bases: DiskFileError

exception swift.common.exceptions.DiskFileQuarantined

Bases: DiskFileError

exception swift.common.exceptions.DiskFileStateChanged

Bases: DiskFileError

当 DiskFile 在打开时其状态发生更改时(例如,磁盘文件列表发生更改)引发。重试 DiskFile 接口可能会成功。

exception swift.common.exceptions.DiskFileXattrNotSupported

Bases: DiskFileError

exception swift.common.exceptions.DriveNotMounted

Bases: SwiftException

exception swift.common.exceptions.DuplicateDeviceError

Bases: RingBuilderError

exception swift.common.exceptions.EmptyRingError

Bases: RingBuilderError

exception swift.common.exceptions.EncryptionException

Bases: SwiftException

exception swift.common.exceptions.FileNotFoundError

Bases: SwiftException

exception swift.common.exceptions.FooterNotSupported

Bases: SwiftException

exception swift.common.exceptions.InsufficientStorage

Bases: SwiftException

exception swift.common.exceptions.InvalidAccountInfo

Bases: DatabaseAuditorException

exception swift.common.exceptions.InvalidPidFileException

基础: Exception

exception swift.common.exceptions.InvalidTimestamp

Bases: SwiftException

exception swift.common.exceptions.LinkIterError

Bases: SwiftException

exception swift.common.exceptions.ListingIterError

Bases: SwiftException

exception swift.common.exceptions.ListingIterNotAuthorized(aresp)

Bases: ListingIterError

exception swift.common.exceptions.ListingIterNotFound

Bases: ListingIterError

exception swift.common.exceptions.LockTimeout(seconds=None, msg=None)

Bases: MessageTimeout

exception swift.common.exceptions.MemcacheConnectionError

基础: Exception

exception swift.common.exceptions.MemcacheIncrNotFoundError

Bases: MemcacheConnectionError

exception swift.common.exceptions.MemcachePoolTimeout(seconds=None, exception=None)

Bases: Timeout

exception swift.common.exceptions.MessageTimeout(seconds=None, msg=None)

Bases: Timeout

exception swift.common.exceptions.MimeInvalid

Bases: SwiftException

exception swift.common.exceptions.MultiphasePUTNotSupported

Bases: SwiftException

exception swift.common.exceptions.PartitionLockTimeout(seconds=None, msg=None)

Bases: LockTimeout

exception swift.common.exceptions.PathNotDir

Bases: OSError

exception swift.common.exceptions.PermissionError

Bases: SwiftException

exception swift.common.exceptions.PutterConnectError(status=None)

基础: Exception

exception swift.common.exceptions.QuarantineRequest

Bases: SwiftException

exception swift.common.exceptions.RangeAlreadyComplete

Bases: SwiftException

exception swift.common.exceptions.ReplicationException

基础: Exception

exception swift.common.exceptions.ReplicationLockTimeout(seconds=None, msg=None)

Bases: LockTimeout

exception swift.common.exceptions.ResponseTimeout(seconds=None, exception=None)

Bases: Timeout

exception swift.common.exceptions.RingBuilderError

Bases: SwiftException

exception swift.common.exceptions.RingLoadError

Bases: SwiftException

exception swift.common.exceptions.RingValidationError

Bases: RingBuilderError

exception swift.common.exceptions.SegmentError

Bases: SwiftException

exception swift.common.exceptions.ShortReadError

Bases: SwiftException

exception swift.common.exceptions.SuffixSyncError

Bases: SwiftException

exception swift.common.exceptions.SwiftException

基础: Exception

exception swift.common.exceptions.UnPicklingError

Bases: SwiftException

exception swift.common.exceptions.UnknownSecretIdError

Bases: EncryptionException

内部客户端

class swift.common.internal_client.CompressingFileReader(file_obj, compresslevel=9, chunk_size=4096)

基类: object

用于压缩对象的同时读取的文件对象包装器。

可用于包装传递给 InternalClient.upload_object() 的文件对象。

在 InternalClient 的测试中使用。

参数:
  • file_obj – 要包装的文件对象。

  • compresslevel – 压缩级别,默认为 9。

  • chunk_size – 迭代对象时读取的块大小,默认为 4096。

read(*a, **kw)

从文件对象读取一个块。

参数直接传递给底层文件对象的 read()。

返回值:

来自文件对象的压缩块。

seek(offset, whence=0)
set_initial_state()

将对象设置为第一次读取所需的状态。

class swift.common.internal_client.InternalClient(conf_path, user_agent, request_tries, use_replication_network=False, global_conf=None, app=None, **kwargs)

基类: object

使用 swift 代理应用程序向 Swift 发出请求的内部客户端。

此客户端将为重试指数级减慢速度。

参数:
  • conf_path – 代理配置的完整路径。

  • user_agent – 发送给 Swift 请求的用户代理。

  • request_tries – InternalClient.make_request() 放弃之前的重试次数。

  • use_replication_network – 强制客户端使用集群上的复制网络。

  • global_conf – 更新已加载代理配置的选项字典。global_conf 中的选项将覆盖 conf_path 中的选项,除非 conf_path 选项前面带有 set

  • app – 可选地提供一个 WSGI 应用程序供内部客户端使用。

static check_gatekeeper_not_loaded(app)
container_exists(account, container)

检查容器是否存在。

参数:
  • account – 容器所属的账户。

  • container – 要检查的容器。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

返回值:

如果容器存在,则为 True,否则为 False。

create_account(account)

创建账户。

参数:

account – 要创建的账户。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

create_container(account, container, headers=None, acceptable_statuses=(2,))

创建容器。

参数:
  • account – 容器所属的账户。

  • container – 要创建的容器。

  • headers – 默认为空字典。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2,)。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

delete_account(account, acceptable_statuses=(2, 404))

删除账户。

参数:
  • account – 要删除的账户。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2, HTTP_NOT_FOUND)。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

delete_container(account, container, headers=None, acceptable_statuses=(2, 404))

删除容器。

参数:
  • account – 容器所属的账户。

  • container – 要删除的容器。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2, HTTP_NOT_FOUND)。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

delete_object(account, container, obj, acceptable_statuses=(2, 404), headers=None)

删除对象。

参数:
  • account – 对象所属的账户。

  • container – 对象所属的容器。

  • obj – 对象。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2, HTTP_NOT_FOUND)。

  • headers – 请求附带的额外标头

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

get_account_info(account, acceptable_statuses=(2, 404))

返回账户的(容器计数,对象计数)。

参数:
  • account – 要获取信息的账户。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2, HTTP_NOT_FOUND)。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

get_account_metadata(account, metadata_prefix='', acceptable_statuses=(2,), params=None)

获取账户元数据。

参数:
  • account – 要获取元数据的账户。

  • metadata_prefix – 用于过滤返回标头中的值的。将从返回字典中的键中剥离该前缀。默认为 ''。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2,)。

返回值:

返回账户元数据字典。键将为小写。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

get_container_metadata(account, container, metadata_prefix='', acceptable_statuses=(2,), params=None)

获取容器元数据。

参数:
  • account – 容器所属的账户。

  • container – 要获取元数据的容器。

  • metadata_prefix – 用于过滤返回标头中的值的。将从返回字典中的键中剥离该前缀。默认为 ''。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2,)。

返回值:

返回容器元数据字典。键将为小写。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

get_object(account, container, obj, headers=None, acceptable_statuses=(2,), params=None)

获取对象。

参数:
  • account – 对象所属的账户。

  • container – 对象所属的容器。

  • obj – 对象名称。

  • headers – 请求附带的标头,默认为空字典。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2,)。

  • params – 要在请求查询字符串中设置的参数字典,默认为 None。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

返回值:

一个 3 元组(状态码,标头,对象正文的迭代器)

get_object_metadata(account, container, obj, metadata_prefix='', acceptable_statuses=(2,), headers=None, params=None)

获取对象元数据。

参数:
  • account – 对象所属的账户。

  • container – 对象所属的容器。

  • obj – 对象。

  • metadata_prefix – 用于过滤返回标头中的值的。将从返回字典中的键中剥离该前缀。默认为 ''。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2,)。

  • headers – 请求附带的额外标头

返回值:

对象元数据字典。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

handle_request(*args, **kwargs)
iter_containers(account, marker='', end_marker='', prefix='', acceptable_statuses=(2, 404))

从账户返回容器字典的迭代器。

参数:
  • account – 要执行容器列表的账户。

  • marker – 第一个所需项的前缀,默认为 ''。

  • end_marker – 返回的最后一项将“小于”此项,默认为 ''。

  • prefix – 容器的前缀

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2, HTTP_NOT_FOUND)。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

iter_object_lines(account, container, obj, headers=None, acceptable_statuses=(2,))

从未压缩或压缩的文本对象返回对象行迭代器。

如果对象的名称以 '.gz' 结尾,则在读取时解压缩对象。

参数:
  • account – 对象所属的账户。

  • container – 对象所属的容器。

  • obj – 对象。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2,)。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

iter_objects(account, container, marker='', end_marker='', prefix='', acceptable_statuses=(2, 404))

从容器返回对象字典的迭代器。

参数:
  • account – 容器所属的账户。

  • container – 要迭代对象的容器。

  • marker – 第一个所需项的前缀,默认为 ''。

  • end_marker – 返回的最后一项将“小于”此项,默认为 ''。

  • prefix – 对象的名称前缀

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2, HTTP_NOT_FOUND)。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

make_path(account, container=None, obj=None)

返回请求的 swift 路径,根据需要对路径部分进行引用和 UTF-8 编码。

参数:
  • account – swift 账户

  • container – 容器,默认为 None

  • obj – 对象,默认为 None

引发:

ValueError – 如果指定了 obj 但未指定 container,则引发此异常。

make_request(method, path, headers, acceptable_statuses, body_file=None, params=None)

使用重试机制向 Swift 发出请求。

参数:
  • method – 请求的 HTTP 方法。

  • path – 请求的路径。

  • headers – 请求附带的标头。

  • acceptable_statuses – 请求可接受的状态码列表。

  • body_file – 要随请求一起传递的正文文件,默认为 None。

  • params – 要在请求查询字符串中设置的参数字典,默认为 None。

返回值:

成功时的响应对象。

引发:
  • UnexpectedResponse – make_request() 未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

set_account_metadata(account, metadata, metadata_prefix='', acceptable_statuses=(2,))

设置账户元数据。调用此函数将向账户元数据添加内容,而不是用 metadata 字典中的值覆盖所有内容。要清除账户元数据值,请在 metadata 字典中将该键的值传递为空字符串。

参数:
  • account – 要获取元数据的账户。

  • metadata – 要设置的元数据字典。

  • metadata_prefix – 用于设置请求标头中元数据的名称,用于在设置元数据时为元数据字典中的键添加前缀,默认为 ''。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2,)。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

set_container_metadata(account, container, metadata, metadata_prefix='', acceptable_statuses=(2,))

设置容器元数据。调用此函数将向容器元数据添加内容,而不是用 metadata 字典中的值覆盖所有内容。要清除容器元数据值,请在 metadata 字典中将该键的值传递为空字符串。

参数:
  • account – 容器所属的账户。

  • container – 要设置元数据的容器。

  • metadata – 要设置的元数据字典。

  • metadata_prefix – 用于设置请求标头中元数据的名称,用于在设置元数据时为元数据字典中的键添加前缀,默认为 ''。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2,)。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

set_object_metadata(account, container, obj, metadata, metadata_prefix='', acceptable_statuses=(2,))

设置对象的元数据。对象元数据将被 metadata 字典中的值覆盖。

参数:
  • account – 对象所属的账户。

  • container – 对象所属的容器。

  • obj – 对象。

  • metadata – 要设置的元数据字典。

  • metadata_prefix – 用于设置请求标头中元数据的名称,用于在设置元数据时为元数据字典中的键添加前缀,默认为 ''。

  • acceptable_statuses – 有效响应的状态码列表,默认为 (2,)。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

upload_object(fobj, account, container, obj, headers=None, acceptable_statuses=(2,), params=None)
参数:
  • fobj – 用于读取对象内容的现有文件对象。

  • account – 对象所属的账户。

  • container – 对象所属的容器。

  • obj – 对象。

  • headers – 请求附带的标头,默认为空字典。

  • acceptable_statuses – 请求可接受的状态码列表。

  • params – 要在请求查询字符串中设置的参数字典,默认为 None。

引发:
  • UnexpectedResponse – 在请求未能获得可接受状态的响应时引发的异常

  • Exception – 代码以意外方式失败时引发的异常。

class swift.common.internal_client.SimpleClient(url=None, token=None, starting_backoff=1, max_backoff=5, retries=5)

基类: object

在 bin/swift-dispersion-* 和 container sync 中使用的简单客户端

base_request(method, container=None, name=None, prefix=None, headers=None, proxy=None, contents=None, full_listing=None, logger=None, additional_info=None, timeout=None, marker=None)
get_account(*args, **kwargs)
get_container(container, **kwargs)
put_container(container, **kwargs)
put_object(container, name, contents, **kwargs)
retry_request(method, **kwargs)
exception swift.common.internal_client.UnexpectedResponse(message, resp)

基础: Exception

Exception raised on invalid responses to InternalClient.make_request().

参数:
  • message – Exception message.

  • resp – The unexpected response.

swift.common.internal_client.delete_object(url, **kwargs)

For usage with container sync

swift.common.internal_client.get_auth(url, user, key, auth_version='1.0', **kwargs)
swift.common.internal_client.head_object(url, **kwargs)

For usage with container sync

swift.common.internal_client.put_object(url, **kwargs)

For usage with container sync

IPAddrs

swift.common.utils.ipaddrs.expand_ipv6(address)

Expand ipv6 address. :param address: a string indicating valid ipv6 address :returns: a string indicating fully expanded ipv6 address

class swift.common.utils.ipaddrs.ifaddrs

Bases: Structure

swift.common.utils.ipaddrs.is_valid_ip(ip)

Return True if the provided ip is a valid IP-address

swift.common.utils.ipaddrs.is_valid_ipv4(ip)

Return True if the provided ip is a valid IPv4-address

swift.common.utils.ipaddrs.is_valid_ipv6(ip)

Returns True if the provided ip is a valid IPv6-address

swift.common.utils.ipaddrs.parse_socket_string(socket_string, default_port)

Given a string representing a socket, returns a tuple of (host, port). Valid strings are DNS names, IPv4 addresses, or IPv6 addresses, with an optional port. If an IPv6 address is specified it must be enclosed in [], like [::1] or [::1]:11211. This follows the accepted prescription for IPv6 host literals.

示例

server.org
server.org:1337
127.0.0.1:1337
[::1]:1337
[::1]
class swift.common.utils.ipaddrs.sockaddr_in4

Bases: Structure

class swift.common.utils.ipaddrs.sockaddr_in6

Bases: Structure

swift.common.utils.ipaddrs.whataremyips(ring_ip=None)

Get “our” IP addresses (“us” being the set of services configured by one *.conf file). If our REST listens on a specific address, return it. Otherwise, if listens on ‘0.0.0.0’ or ‘::’ return all addresses, including the loopback.

参数:

ring_ip (str) – Optional ring_ip/bind_ip from a config file; may be IP address or hostname.

返回值:

list of Strings of ip addresses

Libc

Functions Swift uses to interact with libc and other low-level APIs.

swift.common.utils.libc.NR_ioprio_set()

Give __NR_ioprio_set value for your system.

swift.common.utils.libc.drop_buffer_cache(fd, offset, length)

Drop ‘buffer’ cache for the given range of the given file.

参数:
  • fd – file descriptor

  • offset – start offset

  • length – length

swift.common.utils.libc.get_md5_socket()

Get an MD5 socket file descriptor. One can MD5 data with it by writing it to the socket with os.write, then os.read the 16 bytes of the checksum out later.

NOTE: It is the caller’s responsibility to ensure that os.close() is called on the returned file descriptor. This is a bare file descriptor, not a Python object. It doesn’t close itself.

swift.common.utils.libc.load_libc_function(func_name, log_error=True, fail_if_missing=False, errcheck=False)

Attempt to find the function in libc, otherwise return a no-op func.

参数:
  • func_name – name of the function to pull from libc.

  • log_error – log an error when a function can’t be found

  • fail_if_missing – raise an exception when a function can’t be found. Default behavior is to return a no-op function.

  • errcheck – boolean, if true install a wrapper on the function to check for a return values of -1 and call ctype.get_errno and raise an OSError

swift.common.utils.libc.modify_priority(conf, logger)

Modify priority by nice and ionice.

class swift.common.utils.libc.sockaddr_alg

Bases: Structure

日志

class swift.common.utils.logs.LogLevelFilter(level=10)

基类: object

Drop messages for the logger based on level.

This is useful when dependencies log too much information.

参数:

level – All messages at or below this level are dropped (DEBUG < INFO < WARN < ERROR < CRITICAL|FATAL) Default: DEBUG

class swift.common.utils.logs.NoopMutex

基类: object

“Mutex” that doesn’t lock anything.

We only allow our syslog logging to be configured via UDS or UDP, neither of which have the message-interleaving trouble you’d expect from TCP or file handlers.

class swift.common.utils.logs.NullLogger

基类: object

A no-op logger for eventlet wsgi.

class swift.common.utils.logs.PipeMutex

基类: object

Mutex using a pipe. Works across both greenlets and real threads, even at the same time.

acquire(blocking=True)

Acquire the mutex.

If called with blocking=False, returns True if the mutex was acquired and False if it wasn’t. Otherwise, blocks until the mutex is acquired and returns True.

This lock is recursive; the same greenthread may acquire it as many times as it wants to, though it must then release it that many times too.

close()

Close the mutex. This releases its file descriptors.

You can’t use a mutex after it’s been closed.

release()

Release the mutex.

class swift.common.utils.logs.StrAnonymizer(data, method, salt)

Bases: str

Class that permits to get a string anonymized or simply quoted.

class swift.common.utils.logs.StrFormatTime(ts)

基类: object

Class that permits to get formats or parts of a time.

class swift.common.utils.logs.SwiftLogAdapter(logger, server, prefix='')

Bases: LoggerAdapter, object

A LogAdapter that modifies the adapted Logger instance in the following ways

  • Performs some reformatting on calls to exception().

  • Provides threadlocal txn_id and client_ip attributes.

  • Adds the txn_id, client_ip and server attributes to the extras dict when a message is processed.

  • Adds the given prefix to the start of each log message.

  • Provides a notice method for logging at NOTICE level.

exception(msg, *args, **kwargs)

Delegate an exception call to the underlying logger.

notice(msg, *args, **kwargs)

Convenience function for syslog priority LOG_NOTICE. The python logging lvl is set to 25, just above info. SysLogHandler is monkey patched to map this log lvl to the LOG_NOTICE syslog priority.

process(msg, kwargs)

Add extra info to message

class swift.common.utils.logs.SwiftLogFormatter(fmt=None, datefmt=None, max_line_length=0)

Bases: Formatter

Custom logging.Formatter will append txn_id to a log message if the record has one and the message does not. Optionally it can shorten overly long log lines.

format(record)

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

class swift.common.utils.logs.ThreadSafeSysLogHandler(address=('localhost', 514), facility=1, socktype=None)

Bases: SysLogHandler

createLock()

Acquire a thread lock for serializing access to the underlying I/O.

swift.common.utils.logs.capture_stdio(logger, **kwargs)

Log unhandled exceptions, close stdio, capture stdout and stderr.

param logger: Logger object to use

swift.common.utils.logs.get_log_line(req, res, trans_time, additional_info, fmt, anonymization_method, anonymization_salt)

Make a line for logging that matches the documented log line format for backend servers.

参数:
  • req – the request.

  • res – the response.

  • trans_time – the time the request took to complete, a float.

  • additional_info – a string to log at the end of the line

返回值:

a properly formatted line for logging.

swift.common.utils.logs.get_policy_index(req_headers, res_headers)

Returns the appropriate index of the storage policy for the request from a proxy server

参数:
  • req_headers – dict of the request headers.

  • res_headers – dict of the response headers.

返回值:

string index of storage policy, or None

swift.common.utils.logs.get_prefixed_swift_logger(swift_logger, prefix)

Return a clone of the given swift_logger with a new prefix string that replaces the prefix string of the given swift_logger.

参数:
  • swift_logger – an instance of SwiftLogAdapter.

  • prefix – a string prefix.

返回值:

a new instance of SwiftLogAdapter.

swift.common.utils.logs.get_swift_logger(conf, name=None, log_to_console=False, log_route=None, fmt='%(server)s: %(message)s')

Get the current system logger using config settings.

Log config and defaults:

log_facility = LOG_LOCAL0
log_level = INFO
log_name = swift
log_max_line_length = 0
log_udp_host = (disabled)
log_udp_port = logging.handlers.SYSLOG_UDP_PORT
log_address = /dev/log
参数:
  • conf – Configuration dict to read settings from

  • name – This value is used to populate the server field in the log format, as the default value for log_route; defaults to the log_name value in conf, if it exists, or to ‘swift’.

  • log_to_console – Add handler which writes to console on stderr

  • log_route – Route for the logging, not emitted to the log, just used to separate logging configurations; defaults to the value of name or whatever name defaults to. This value is used as the name attribute of the logging.LogAdapter that is returned.

  • fmt – Override log format

返回值:

an instance of SwiftLogAdapter

Manager

class swift.common.manager.Manager(servers, run_dir='/var/run/swift')

基类: object

Main class for performing commands on groups of servers.

参数:

servers – list of server names as strings

force_reload(**kwargs)

alias for reload

get_command(cmd)

Find and return the decorated method named like cmd

参数:

cmd – the command to get, a string, if not found raises UnknownCommandError

kill(**kwargs)

stop a server (no error if not running)

kill_child_pids(**kwargs)

kill child pids, optionally servicing accepted connections

classmethod list_commands()

Get all publicly accessible commands

返回值:

a list of string tuples (cmd, help), the method names who are decorated as commands

no_daemon(**kwargs)

start a server interactively

no_wait(**kwargs)

spawn server and return immediately

once(**kwargs)

start server and run one pass on supporting daemons

reload(**kwargs)

graceful shutdown then restart on supporting servers

reload_seamless(**kwargs)

seamlessly re-exec, then shutdown of old listen sockets on supporting servers

restart(**kwargs)

stops then restarts server

run_command(cmd, **kwargs)

Find the named command and run it

参数:

cmd – the command name to run

shutdown(**kwargs)

allow current requests to finish on supporting servers

start(**kwargs)

starts a server

status(**kwargs)

display status of tracked pids for server

stop(**kwargs)

stops a server

class swift.common.manager.Server(server, run_dir='/var/run/swift')

基类: object

Manage operations on a server or group of servers of similar type

参数:

server – name of server

conf_files(**kwargs)

Get conf files for this server

参数:

number – if supplied will only lookup the nth server

返回值:

list of conf files

get_conf_file_name(pid_file)

Translate pid_file to a corresponding conf_file

参数:

pid_file – a pid_file for this server, a string

返回值:

the conf_file for this pid_file

get_pid_file_name(conf_file)

Translate conf_file to a corresponding pid_file

参数:

conf_file – an conf_file for this server, a string

返回值:

the pid_file for this conf_file

get_running_pids(**kwargs)

Get running pids

返回值:

a dict mapping pids (ints) to pid_files (paths)

interact(**kwargs)

wait on spawned procs to terminate

iter_pid_files(**kwargs)

Generator, yields (pid_file, pids)

kill_child_pids(**kwargs)

Kill child pids, leaving server overseer to respawn them

参数:
  • graceful – if True, attempt SIGHUP on supporting servers

  • seamless – if True, attempt SIGUSR1 on supporting servers

返回值:

a dict mapping pids (ints) to pid_files (paths)

kill_running_pids(**kwargs)

Kill running pids

参数:
  • graceful – if True, attempt SIGHUP on supporting servers

  • seamless – if True, attempt SIGUSR1 on supporting servers

返回值:

a dict mapping pids (ints) to pid_files (paths)

launch(**kwargs)

Collect conf files and attempt to spawn the processes for this server

pid_files(**kwargs)

Get pid files for this server

参数:

number – if supplied will only lookup the nth server

返回值:

list of pid files

signal_children(sig, **kwargs)

Send a signal to child pids for this server

参数:

sig – signal to send

返回值:

a dict mapping pids (ints) to pid_files (paths)

signal_pids(sig, **kwargs)

Send a signal to pids for this server

参数:

sig – signal to send

返回值:

a dict mapping pids (ints) to pid_files (paths)

spawn(conf_file, once=False, wait=True, daemon=True, additional_args=None, **kwargs)

Launch a subprocess for this server.

参数:
  • conf_file – path to conf_file to use as first arg

  • once – boolean, add once argument to command

  • wait – boolean, if true capture stdout with a pipe

  • daemon – boolean, if false ask server to log to console

  • additional_args – list of additional arguments to pass on the command line

返回值:

the pid of the spawned process

status(pids=None, **kwargs)

Display status of server

参数:
  • pids – if not supplied pids will be populated automatically

  • number – if supplied will only lookup the nth server

返回值:

1 if server is not running, 0 otherwise

stop(**kwargs)

Send stop signals to pids for this server

返回值:

a dict mapping pids (ints) to pid_files (paths)

wait(**kwargs)

wait on spawned procs to start

exception swift.common.manager.UnknownCommandError

基础: Exception

swift.common.manager.command(func)

Decorator to declare which methods are accessible as commands, commands always return 1 or 0, where 0 should indicate success.

参数:

func – function to make public

swift.common.manager.format_server_name(servername)

Formats server name as swift compatible server names E.g. swift-object-server

参数:

servername – server name

返回值:

swift compatible server name and its binary name

swift.common.manager.get_child_pids(pid)

Get the current set of all child PIDs for a PID.

参数:

pid – process id

swift.common.manager.kill_group(pid, sig)

Send signal to process group

: param pid: process id : param sig: signal to send

swift.common.manager.safe_kill(pid, sig, name)

Send signal to process and check process name

: param pid: process id : param sig: signal to send : param name: name to ensure target process

swift.common.manager.setup_env()

Try to increase resource limits of the OS. Move PYTHON_EGG_CACHE to /tmp

swift.common.manager.verify_server(server)

Check whether the server is among swift servers or not, and also checks whether the server’s binaries are installed or not.

参数:

server – name of the server

返回值:

True, when the server name is valid and its binaries are found. False, otherwise.

swift.common.manager.watch_server_pids(server_pids, interval=1, **kwargs)

Monitor a collection of server pids yielding back those pids that aren’t responding to signals.

参数:

server_pids – a dict, lists of pids [int,…] keyed on Server objects

MemCacheD

Why our own memcache client? By Michael Barton

python-memcached doesn’t use consistent hashing, so adding or removing a memcache server from the pool invalidates a huge percentage of cached items.

If you keep a pool of python-memcached client objects, each client object has its own connection to every memcached server, only one of which is ever in use. So you wind up with n * m open sockets and almost all of them idle. This client effectively has a pool for each server, so the number of backend connections is hopefully greatly reduced.

python-memcache uses pickle to store things, and there was already a huge stink about Swift using pickles in memcache (http://osvdb.org/show/osvdb/86581). That seemed sort of unfair, since nova and keystone and everyone else use pickles for memcache too, but it’s hidden behind a “standard” library. But changing would be a security regression at this point.

Also, pylibmc wouldn’t work for us because it needs to use python sockets in order to play nice with eventlet.

Lucid comes with memcached: v1.4.2. Protocol documentation for that version is at

http://github.com/memcached/memcached/blob/1.4.2/doc/protocol.txt

class swift.common.memcached.MemcacheCommand(method, key)

基类: object

Helper class that encapsulates common parameters of a command.

参数:
  • method – the name of the MemcacheRing method that was called.

  • key – the memcached key.

class swift.common.memcached.MemcacheConnPool(server, size, connect_timeout, tls_context=None)

Bases: Pool

Connection pool for Memcache Connections

The server parameter can be a hostname, an IPv4 address, or an IPv6 address with an optional port. See swift.common.utils.parse_socket_string() for details.

create()

Generate a new pool item. In order for the pool to function, either this method must be overriden in a subclass or the pool must be constructed with the create argument. It accepts no arguments and returns a single instance of whatever thing the pool is supposed to contain.

In general, create() is called whenever the pool exceeds its previous high-water mark of concurrently-checked-out-items. In other words, in a new pool with min_size of 0, the very first call to get() will result in a call to create(). If the first caller calls put() before some other caller calls get(), then the first item will be returned, and create() will not be called a second time.

get()

Return an item from the pool, when one is available. This may cause the calling greenthread to block.

class swift.common.memcached.MemcacheRing(servers, connect_timeout=0.3, io_timeout=2.0, pool_timeout=1.0, tries=3, max_conns=2, tls_context=None, logger=None, error_limit_count=10, error_limit_time=60, error_limit_duration=60, item_size_warning_threshold=-1)

基类: object

Simple, consistent-hashed memcache client.

decr(key, delta=1, time=0)

Decrements a key which has a numeric value by delta. Calls incr with -delta.

参数:
  • key – key

  • delta – amount to subtract to the value of key (or set the value to 0 if the key is not found) will be cast to an int

  • time – the time to live

返回值:

result of decrementing

引发:

MemcacheConnectionError

delete(key, server_key=None)

Deletes a key/value pair from memcache.

参数:
  • key – key to be deleted

  • server_key – key to use in determining which server in the ring is used

get(key, raise_on_error=False)

Gets the object specified by key. It will also unserialize the object before returning if it is serialized in memcache with JSON.

参数:
  • key – key

  • raise_on_error – if True, propagate Timeouts and other errors. By default, errors are treated as cache misses.

返回值:

value of the key in memcache

get_multi(keys, server_key)

Gets multiple values from memcache for the given keys.

参数:
  • keys – keys for values to be retrieved from memcache

  • server_key – key to use in determining which server in the ring is used

返回值:

list of values

incr(key, delta=1, time=0)

Increments a key which has a numeric value by delta. If the key can’t be found, it’s added as delta or 0 if delta < 0. If passed a negative number, will use memcached’s decr. Returns the int stored in memcached Note: The data memcached stores as the result of incr/decr is an unsigned int. decr’s that result in a number below 0 are stored as 0.

参数:
  • key – key

  • delta – amount to add to the value of key (or set as the value if the key is not found) will be cast to an int

  • time – the time to live

返回值:

result of incrementing

引发:

MemcacheConnectionError

set(key, value, serialize=True, time=0, min_compress_len=0, raise_on_error=False)

Set a key/value pair in memcache

参数:
  • key – key

  • value – value

  • serialize – if True, value is serialized with JSON before sending to memcache

  • time – the time to live

  • min_compress_len – minimum compress length, this parameter was added to keep the signature compatible with python-memcached interface. This implementation ignores it.

  • raise_on_error – if True, propagate Timeouts and other errors. By default, errors are ignored.

set_multi(mapping, server_key, serialize=True, time=0, min_compress_len=0)

Sets multiple key/value pairs in memcache.

参数:
  • mapping – dictionary of keys and values to be set in memcache

  • server_key – key to use in determining which server in the ring is used

  • serialize – if True, value is serialized with JSON before sending to memcache.

  • time – the time to live

Min_compress_len:

minimum compress length, this parameter was added to keep the signature compatible with python-memcached interface. This implementation ignores it

swift.common.memcached.load_memcache(conf, logger)

Build a MemcacheRing object from the given config. It will also use the passed in logger.

参数:
  • conf – a dict, the config options

  • logger – 一个 logger

swift.common.memcached.sanitize_timeout(timeout)

Sanitize a timeout value to use an absolute expiration time if the delta is greater than 30 days (in seconds). Note that the memcached server translates negative values to mean a delta of 30 days in seconds (and 1 additional second), client beware.

Middleware Registry

swift.common.registry.get_sensitive_headers()

Returns the set of registered sensitive headers.

Used by swift.common.middleware.proxy_logging to perform redactions prior to logging.

swift.common.registry.get_sensitive_params()

Returns the set of registered sensitive query parameters.

Used by swift.common.middleware.proxy_logging to perform redactions prior to logging.

swift.common.registry.get_swift_info(admin=False, disallowed_sections=None)

Returns information about the swift cluster that has been previously registered with the register_swift_info call.

参数:
  • admin – boolean value, if True will additionally return an ‘admin’ section with information previously registered as admin info.

  • disallowed_sections – list of section names to be withheld from the information returned.

返回值:

dictionary of information about the swift cluster.

swift.common.registry.register_sensitive_header(header)

Register a header as being “sensitive”.

Sensitive headers are automatically redacted when logging. See the reveal_sensitive_prefix option in the proxy-server sample config for more information.

参数:

header – The (case-insensitive) header name which, if present, may contain sensitive information. Examples include X-Auth-Token and (if s3api is enabled) Authorization. Limited to ASCII characters.

swift.common.registry.register_sensitive_param(query_param)

Register a query parameter as being “sensitive”.

Sensitive query parameters are automatically redacted when logging. See the reveal_sensitive_prefix option in the proxy-server sample config for more information.

参数:

query_param – The (case-sensitive) query parameter name which, if present, may contain sensitive information. Examples include temp_url_signature and (if s3api is enabled) X-Amz-Signature. Limited to ASCII characters.

swift.common.registry.register_swift_info(name='swift', admin=False, **kwargs)

Registers information about the swift cluster to be retrieved with calls to get_swift_info.

NOTE: Do not use “.” in the param: name or any keys in kwargs. “.” is used

in the disallowed_sections to remove unwanted keys from /info.

参数:
  • name – string, the section name to place the information under.

  • admin – boolean, if True, information will be registered to an admin section which can optionally be withheld when requesting the information.

  • kwargs – key value arguments representing the information to be added.

引发:

ValueError – if name or any of the keys in kwargs has “.” in it

Request Helpers

Miscellaneous utility functions for use in generating responses.

Why not swift.common.utils, you ask? Because this way we can import things from swob in here without creating circular imports.

class swift.common.request_helpers.SegmentedIterable(req, app, listing_iter, max_get_time, logger, ua_suffix, swift_source, name='<not specified>', response_body_length=None)

基类: object

Iterable that returns the object contents for a large object.

参数:
  • req – original request object

  • app – WSGI application from which segments will come

  • listing_iter

    iterable yielding the object segments to fetch, along with the byte sub-ranges to fetch. Each yielded item should be a dict with the following keys: path or raw_data, first-byte, last-byte, hash (optional), bytes (optional).

    If hash is None, no MD5 verification will be done.

    If bytes is None, no length verification will be done.

    If first-byte and last-byte are None, then the entire object will be fetched.

  • max_get_time – maximum permitted duration of a GET request (seconds)

  • logger – logger object

  • swift_source – value of swift.source in subrequest environ (just for logging)

  • ua_suffix – string to append to user-agent.

  • name – name of manifest (used in logging only)

  • response_body_length – optional response body length for the response being sent to the client.

app_iter_range(*a, **kw)

swob.Response will only respond with a 206 status in certain cases; one of those is if the body iterator responds to .app_iter_range().

However, this object (or really, its listing iter) is smart enough to handle the range stuff internally, so we just no-op this out for swob.

app_iter_ranges(ranges, content_type, boundary, content_size)

This method assumes that iter(self) yields all the data bytes that go into the response, but none of the MIME stuff. For example, if the response will contain three MIME docs with data “abcd”, “efgh”, and “ijkl”, then iter(self) will give out the bytes “abcdefghijkl”.

This method inserts the MIME stuff around the data bytes.

close()

Called when the client disconnect. Ensure that the connection to the backend server is closed.

validate_first_segment()

开始获取对象数据,以确保第一个片段(如果存在)有效。这可以捕获诸如“第一个片段丢失”或“第一个片段的ETag与清单不匹配”之类的场景。

注意:这并不验证您是否拥有任何片段。零片段的大对象并无错误;它只是空的。

swift.common.request_helpers.append_log_info(environ, log_info)
swift.common.request_helpers.check_path_header(req, name, length, error_msg)

验证类路径的头部的格式是否正确。我们假设调用者已确保该特定头部存在于 req.headers 中。

参数:
  • req – HTTP 请求对象

  • name – 头部名称

  • length – 路径片段检查的长度

  • error_msg – 客户端的错误消息

返回值:

一个元组,包含根据长度划分的路径部分

引发:

如果头部值格式不正确,则引发 HTTPPreconditionFailed。

swift.common.request_helpers.constrain_req_limit(req, constrained_limit)
swift.common.request_helpers.copy_header_subset(from_r, to_r, condition)

将所需的部分头部从 from_r 复制到 to_r。

参数:
  • from_r – swob 的 Request 或 Response

  • to_r – swob 的 Request 或 Response

  • condition – 一个函数,它将接收头部键作为单个参数,并应返回 True 如果该头部需要被复制。

swift.common.request_helpers.get_container_update_override_key(key)

返回完整的 X-Object-Sysmeta-Container-Update-Override-* 头部键。

参数:

key – 您要在容器更新中覆盖的键

返回值:

完整的头部键

swift.common.request_helpers.get_heartbeat_response_body(data_format, data_dict, error_list, root_tag)

根据格式返回心跳的响应体。

处理 json 和 xml,否则将返回 text/plain。注意:xml 响应不包含 xml 声明。

Params data_format:

结果格式

Params data_dict:

结果的生成数据。

Params error_list:

失败的引用文件名的列表

Params root_tag:

返回 XML 时用作根元素的标签名称;例如 ‘extract’ 或 ‘delete’

swift.common.request_helpers.get_ip_port(node, headers)

获取用于给定 node 的 IP 地址和端口。正常 IP 地址和端口将被返回,除非 nodeheaders 表明应使用复制 IP 地址和端口。

如果 headers 字典中包含键为 x-backend-use-replication-network 且值为真的项,则返回复制 IP 地址和端口。否则,如果 node 字典中包含键为 use_replication 且值为真的项,则返回复制 IP 地址和端口。否则,返回正常 IP 地址和端口。

参数:
  • node – 描述节点的字典

  • headers – 头部字典

返回值:

(IP 地址, 端口) 的元组

swift.common.request_helpers.get_log_info(environ)
swift.common.request_helpers.get_name_and_placement(request, minsegs=1, maxsegs=None, rest_with_last=False)

实用函数,用于分割和验证请求路径和存储策略。存储策略索引从请求头部中提取,并转换为 StoragePolicy 实例。其余参数将传递给 split_and_validate_path()

返回值:

一个列表,是 split_and_validate_path() 的结果,并在末尾附加了 BaseStoragePolicy 实例

引发:

HTTPServiceUnavailable – 如果路径无效或不存在具有已提取的 policy_index 的策略。

swift.common.request_helpers.get_object_transient_sysmeta(key)

返回用于键的对象瞬态系统元数据头部。对象瞬态系统元数据命名空间将由后端对象服务器持久化。这些头部与用户对象元数据一样处理,即在此命名空间中的所有头部将在每次 POST 请求时被替换。

参数:

key – 元数据键

返回值:

用于键的整个对象瞬态系统元数据头部

swift.common.request_helpers.get_param(req, name, default=None)

从 HTTP 请求中获取参数,确保正确处理 UTF-8 编码。

参数:
  • req – 请求对象

  • name – 参数名称

  • default – 如果找不到参数时返回的结果

返回值:

HTTP 请求参数值,作为原生(非 WSGI)字符串

引发:

HTTPBadRequest – 如果参数不是有效的 UTF-8 字节序列

swift.common.request_helpers.get_reserved_name(*parts)

生成一个有效的保留名称,该名称连接了各个部分。

返回值:

一个字符串

swift.common.request_helpers.get_sys_meta_prefix(server_type)

返回给定服务器类型的系统元数据头部的前缀。

此前缀定义了将由后端服务器持久化的头部的命名空间。

参数:

server_type – 后端服务器的类型,即 [account|container|object]

返回值:

服务器类型系统元数据头部的 prefix 字符串

swift.common.request_helpers.get_user_meta_prefix(server_type)

返回给定服务器类型的用户元数据头部的 prefix。

此前缀定义了将由后端服务器持久化的头部的命名空间。

参数:

server_type – 后端服务器的类型,即 [account|container|object]

返回值:

服务器类型用户元数据头部的 prefix 字符串

swift.common.request_helpers.get_valid_part_num(req)

对于 SLO 对象,任何非范围 GET 或 HEAD 请求都可以在查询字符串中包含 part-number 参数。如果传入的请求包含 part-number 参数,它将被解析为有效的整数并返回。如果传入的请求不包含 part-number 参数,我们将返回 None。如果 part-number 参数对于给定的请求无效,我们将引发适当的 HTTP 异常。

参数:

req – 请求对象

返回值:

已验证的 part-number 值或 None

引发:

HTTPBadRequest – 如果请求或 part-number 参数无效

swift.common.request_helpers.http_response_to_document_iters(response, read_chunk_size=4096)

将成功的对象 GET HTTP 响应转换为 (first-byte, last-byte, length, headers, body-file) 的 5 元组迭代器。

响应必须是 200 或 206;如果您输入 204 或类似内容,这可能行不通。

参数:

response – HTTP 响应,例如来自 bufferedhttp.http_connect() 的响应,而不是 swob.Response。

swift.common.request_helpers.is_backend_open_expired(request)

辅助函数,用于检查请求是否具有“x-backend-open-expired”或“x-backend-replication”头部,以便后端可以访问已过期的对象。

参数:

request – 请求对象

swift.common.request_helpers.is_object_transient_sysmeta(key)

测试头部键是否以对象瞬态系统元数据的前缀开头且长度大于前缀。

参数:

key – 头部键

返回值:

如果键满足测试,则为 True,否则为 False

swift.common.request_helpers.is_open_expired(app, req)

辅助函数,用于根据 allow_open_expired 全局配置检查带有“x-open-expired”头部的请求是否可以访问尚未被 object-expirer 收回的对象。

参数:
  • app – 应用程序实例

  • req – 请求对象

swift.common.request_helpers.is_sys_meta(server_type, key)

测试头部键是否以给定服务器类型的系统元数据前缀开头且长度大于前缀。

参数:
  • server_type – 后端服务器的类型,即 [account|container|object]

  • key – 头部键

返回值:

如果键满足测试,则为 True,否则为 False

swift.common.request_helpers.is_sys_or_user_meta(server_type, key)

测试头部键是否以给定服务器类型的用户或系统元数据前缀开头且长度大于前缀。

参数:
  • server_type – 后端服务器的类型,即 [account|container|object]

  • key – 头部键

返回值:

如果键满足测试,则为 True,否则为 False

swift.common.request_helpers.is_use_replication_network(headers=None)

确定是否应使用复制网络。

参数:

headers – 头部字典

返回值:

来自 headersx-backend-use-replication-network 项的值。如果没有给出 headers 或未找到该项,则返回 False。

swift.common.request_helpers.is_user_meta(server_type, key)

测试头部键是否以给定服务器类型的用户元数据前缀开头且长度大于前缀。

参数:
  • server_type – 后端服务器的类型,即 [account|container|object]

  • key – 头部键

返回值:

如果键满足测试,则为 True,否则为 False

swift.common.request_helpers.remove_items(headers, condition)

从满足给定条件的键的字典中删除项。

参数:
  • headers – 头部字典

  • condition – 一个函数,它将接收头部键作为单个参数,并应返回 True 如果该头部需要被删除。

返回值:

一个字典,可能为空,包含已删除的头部

swift.common.request_helpers.resolve_etag_is_at_header(req, metadata)

辅助函数,用于解析可能存储在元数据中、具有备用名称的替代 ETags 值。

请求的 X-Backend-Etag-Is-At 头部的值(如果存在)是一个逗号分隔的列表,列出了备用名称,在这些名称下可以找到备用 ETags 值。此列表按顺序处理,直到找到备用 ETags。

最左边的值在 X-Backend-Etag-Is-At 中,如果使用 EC 策略,则由最左边的中间件设置,或者如果没有中间件,则由 ECObjectController 设置。最左边的中间件被假定为对象内容的 ETags 值的权威。

解析器将从左到右处理列表,直到找到作为给定元数据中名称的值。因此,最左边的获胜,前提是它存在于元数据中。

例如,假设安装了加密中间件。如果对象未加密,则解析器将找不到加密中间件的备用 ETags sysmeta (X-Object-Sysmeta-Crypto-Etag),但会找到 EC 备用 ETags(如果使用 EC 策略)。但是,如果对象已加密,则找到并使用 X-Object-Sysmeta-Crypto-Etag,这是正确的,因为它应该优先于 X-Object-Sysmeta-Ec-Etag。

参数:
  • req – swob Request

  • metadata – 包含对象元数据的字典

返回值:

如果找到备用 ETags 值,则为备用 ETags 值,否则为 None

swift.common.request_helpers.resolve_ignore_range_header(req, metadata)

辅助函数,用于在找到匹配 X-Backend-Ignore-Range-If-Metadata-Present 头部的元数据时,从请求中删除 Range 头部。

参数:
  • req – swob Request

  • metadata – 对象元数据字典

swift.common.request_helpers.split_and_validate_path(request, minsegs=1, maxsegs=None, rest_with_last=False)

实用函数,用于分割和验证请求路径。

返回值:

如果一切正常,则为 split_path() 的结果,以原生字符串形式表示

引发:

HTTPBadRequest – 如果某些地方有问题

swift.common.request_helpers.split_reserved_name(name)

将有效的保留名称分离成各个部分。

返回值:

字符串列表

swift.common.request_helpers.strip_object_transient_sysmeta_prefix(key)

从头部键的开头删除对象瞬态系统元数据前缀。

参数:

key – 头部键

返回值:

被剥离的头部键

swift.common.request_helpers.strip_sys_meta_prefix(server_type, key)

从给定服务器类型的系统元数据前缀的开头删除头部键。

参数:
  • server_type – 后端服务器的类型,即 [account|container|object]

  • key – 头部键

返回值:

被剥离的头部键

swift.common.request_helpers.strip_user_meta_prefix(server_type, key)

从给定服务器类型的用户元数据前缀的开头删除头部键。

参数:
  • server_type – 后端服务器的类型,即 [account|container|object]

  • key – 头部键

返回值:

被剥离的头部键

swift.common.request_helpers.update_etag_is_at_header(req, name)

辅助函数,用于更新 X-Backend-Etag-Is-At 头部,其值是一个备用头部名称列表,实际对象 ETags 可能存储在这些名称下。这会通知对象服务器在处理条件请求时到哪里查找实际的对象 ETags。

由于代理服务器和/或中间件可能会设置备用的 ETags 头部名称,X-Backend-Etag-Is-At 的值是一个逗号分隔的列表,对象服务器会按顺序检查该列表,直到找到 ETags 值。

参数:
  • req – swob Request

  • name – 可以在其中找到备用 ETags 的 sysmeta 的名称

swift.common.request_helpers.update_ignore_range_header(req, name)

辅助函数,用于更新 X-Backend-Ignore-Range-If-Metadata-Present 头部,其值是头部名称列表,如果其中任何一个头部存在于对象上,则意味着对象服务器应响应 200 而不是 206 或 416。

参数:
  • req – swob Request

  • name – 如果找到,则表示代理需要整个对象的头部名称

swift.common.request_helpers.validate_container_params(req)
swift.common.request_helpers.validate_internal_account(account)

验证内部帐户名称。

引发:

HTTPBadRequest

swift.common.request_helpers.validate_internal_container(account, container)

验证内部帐户和容器名称。

引发:

HTTPBadRequest

swift.common.request_helpers.validate_internal_obj(account, container, obj)

验证内部帐户、容器和对象名称。

引发:

HTTPBadRequest

swift.common.request_helpers.validate_params(req, names)

从 HTTP 请求中获取参数列表,并验证每个参数的编码。

参数:
  • req – 请求对象

  • names – 参数名称

返回值:

一个字典,将参数名称映射到请求参数中出现的每个名称的值

引发:

HTTPBadRequest – 如果任何参数值不是有效的 UTF-8 字节序列

StatsdClient

Statsd 客户端

class swift.common.statsd_client.AbstractStatsdClient(host, port, default_sample_rate=1, sample_rate_factor=1, logger=None)

基类: object

用于方便地将指标发送到套接字的基础类。子类负责格式化指标行。

参数:
  • host – Statsd 主机名。如果为 None,则不发送指标。

  • port – Statsd 主机端口。

  • default_sample_rate – 如果没有另外指定采样率,则指标应采样的默认速率。应为介于 0 和 1 之间的浮点值。

  • sample_rate_factor – 应用于指标采样速率的乘数。应为介于 0 和 1 之间的浮点值。

  • logger – 一个 stdlib logger 实例。

class swift.common.statsd_client.LabeledStatsdClient(host, port, default_sample_rate=1, sample_rate_factor=1, label_mode='disabled', default_labels=None, logger=None)

Bases: AbstractStatsdClient

支持为指标添加标签的 statsd 客户端。

可以通过在创建客户端时指定相应的 label_mode,以 Graphite、Librato、InfluxDB 或 DogStatsD 的风格发出带标签的指标。如果 label_modedisabled,则客户端不发出任何指标。

标签键应仅包含 ASCII 字母('a-z','A-Z')、数字('0-9')和下划线字符('_')。标签值也可以包含句点('.')字符。

调用者应避免使用具有高基数(value)的标签,因为这可能导致收集器维护数量过多的不同时间序列。例如,标签不应用于对象名称或事务 ID。

参数:
  • host – Statsd 主机名。如果为 None,则不发送指标。

  • port – Statsd 主机端口。

  • default_sample_rate – 如果没有另外指定采样率,则指标应采样的默认速率。应为介于 0 和 1 之间的浮点值。

  • sample_rate_factor – 应用于指标采样速率的乘数。应为介于 0 和 1 之间的浮点值。

  • label_mode – ‘graphite’、‘dogstatsd’、‘librato’、‘influxdb’ 或 ‘disabled’ 之一。

  • default_labels – 将添加到客户端发出的每个指标的标签字典。

  • logger – 一个 stdlib logger 实例。

decrement(metric, *, labels=None, sample_rate=None)

递减计数器,聚合指标减一。

参数:
  • metric – 指标名称

  • labels – 字典,指标标签

  • sample_rate – 浮点数,覆盖默认采样率

increment(metric, *, labels=None, sample_rate=None)

递增计数器,聚合指标加一。

参数:
  • metric – 指标名称

  • labels – 字典,指标标签

  • sample_rate – 浮点数,覆盖默认采样率

timing(metric, timing_ms, *, labels=None, sample_rate=None)

更新计时指标,重新计算聚合百分位数。

参数:
  • metric – 指标名称

  • timing_ms – 浮点数,操作的总计时

  • labels – 字典,指标标签

  • sample_rate – 浮点数,覆盖默认采样率

timing_since(metric, orig_time, *, labels=None, sample_rate=None)

更新计时指标,重新计算聚合百分位数。

这是 timing 的一个替代拼写,它会为您计算 timing_ms=(time.time() - orig_time)。

参数:
  • metric – 指标名称

  • orig_time – 浮点数,操作开始时间的 time.time()

  • labels – 字典,指标标签

  • sample_rate – 浮点数,覆盖默认采样率

transfer_rate(metric, elapsed_time, byte_xfer, *, labels=None, sample_rate=None)

更新计时指标,重新计算聚合百分位数。

这是一个计时指标,但它会调整每传输的 kB 的计时数据(ms/kB),用于每个非零字节的更新。据称这可以用于监控有问题设备,值越高越差。

参数:
  • metric – 指标名称

  • elapsed_time – 浮点数,操作的总计时

  • byte_xfer – 整数,传输的字节数

  • labels – 字典,指标标签

  • sample_rate – 浮点数,覆盖默认采样率

update_stats(metric, value, *, labels=None, sample_rate=None)

更新计数器,聚合指标按值更改。

参数:
  • metric – 指标名称

  • value – 整数,计数器增量

  • labels – 字典,指标标签

  • sample_rate – 浮点数,覆盖默认采样率

class swift.common.statsd_client.StatsdClient(host, port, base_prefix='', tail_prefix='', default_sample_rate=1, sample_rate_factor=1, emit_legacy=True, logger=None)

Bases: AbstractStatsdClient

一个传统的 statsd 客户端。此客户端不支持带标签的指标。

可以使用 base_prefixtail_prefix 参数指定前缀。前缀会添加到每个指标的名称中,以便发出的指标名称格式为

[<base_prefix>.][tail_prefix.]<metric name>

参数:
  • host – Statsd 主机名。如果为 None,则不发送指标。

  • port – Statsd 主机端口。

  • base_prefix – (可选) 一个字符串,它将构成添加到每个指标名称的前缀的第一部分。前缀与指标名称之间用 '.' 字符分隔。

  • tail_prefix – (可选) 一个字符串,它将构成添加到每个指标名称的前缀的第二部分。前缀与指标名称之间用 '.' 字符分隔。

  • default_sample_rate – 如果没有另外指定采样率,则指标应采样的默认速率。应为介于 0 和 1 之间的浮点值。

  • sample_rate_factor – 应用于指标采样速率的乘数。应为介于 0 和 1 之间的浮点值。

  • emit_legacy – 如果为 True,则客户端将发出指标;如果为 False,则客户端将不发出任何指标。

  • logger – 一个 stdlib logger 实例。

decrement(metric, sample_rate=None)

递减计数器,聚合指标减一。

参数:
  • metric – 指标名称

  • sample_rate – 浮点数,覆盖默认采样率

increment(metric, sample_rate=None)

递增计数器,聚合指标加一。

参数:
  • metric – 指标名称

  • sample_rate – 浮点数,覆盖默认采样率

set_prefix(tail_prefix)

此方法已弃用;在实例化类时,请改用构造函数中的 tail_prefix 参数。

timing(metric, timing_ms, sample_rate=None)

更新计时指标,重新计算聚合百分位数。

参数:
  • metric – 指标名称

  • timing_ms – 浮点数,操作的总计时

  • sample_rate – 浮点数,覆盖默认采样率

timing_since(metric, orig_time, sample_rate=None)

更新计时指标,重新计算聚合百分位数。

这是 timing 的一个替代拼写,它会为您计算 timing_ms=(time.time() - orig_time)。

参数:
  • metric – 指标名称

  • orig_time – 浮点数,操作开始时间的 time.time()

  • sample_rate – 浮点数,覆盖默认采样率

transfer_rate(metric, elapsed_time, byte_xfer, sample_rate=None)

更新计时指标,重新计算聚合百分位数。

这是一个计时指标,但它会调整每传输的 kB 的计时数据(ms/kB),用于每个非零字节的更新。据称这可以用于监控有问题设备,值越高越差。

参数:
  • metric – 指标名称

  • elapsed_time – 浮点数,操作的总计时

  • byte_xfer – 整数,传输的字节数

  • sample_rate – 浮点数,覆盖默认采样率

update_stats(metric, value, sample_rate=None)

更新计数器,聚合指标按值更改。

参数:
  • metric – 指标名称

  • value – 整数,计数器增量

  • sample_rate – 浮点数,覆盖默认采样率

swift.common.statsd_client.get_labeled_statsd_client(conf=None, logger=None)

使用配置设置获取 LabeledStatsdClient 的实例。

配置和默认值:

log_statsd_host = (disabled)
log_statsd_port = 8125
log_statsd_default_sample_rate = 1.0
log_statsd_sample_rate_factor = 1.0
statsd_label_mode = disabled
参数:
  • conf – Configuration dict to read settings from

  • logger – statsd 客户端用于日志记录的 stdlib logger 实例

返回值:

LabeledStatsdClient 的一个实例

swift.common.statsd_client.get_statsd_client(conf=None, tail_prefix='', logger=None)

使用配置设置获取 StatsdClient 的实例。

配置和默认值:

log_statsd_host = (disabled)
log_statsd_port = 8125
log_statsd_default_sample_rate = 1.0
log_statsd_sample_rate_factor = 1.0
log_statsd_metric_prefix = (empty-string)
statsd_emit_legacy = true
参数:
  • conf – Configuration dict to read settings from

  • tail_prefix – 要传递给 statsd 客户端的尾部前缀

  • logger – statsd 客户端用于日志记录的 stdlib logger 实例

返回值:

StatsdClient 的一个实例

swift.common.statsd_client.random() x 区间 [0, 1).

存储策略

class swift.common.storage_policy.BaseStoragePolicy(idx, name='', is_default=False, is_deprecated=False, object_ring=None, aliases='', diskfile_module='egg:swift#replication.fs')

基类: object

表示存储策略。不应直接实例化;实现派生子类(例如 StoragePolicy、ECStoragePolicy 等)或使用 reload_storage_policies()swift.conf 加载 POLICIES。

object_ring 属性将在服务已知其 swift_dir 后惰性加载(通过 get_object_ring()),但可以通过 object_ring 关键字参数在创建时覆盖,用于测试或通过 load_ring() 主动加载。

add_name(name)

向存储策略添加一个别名。不应直接从存储策略调用此方法,而应通过存储策略集合类调用,以便按名称查找能够正确解析。

参数:

name – 存储策略的新别名

change_primary_name(name)

将策略的主名称/默认名称更改为指定的名称。

参数:

name – 要替换当前主名称的字符串名称。

get_diskfile_manager(*args, **kwargs)

返回为该存储策略配置的 diskfile manager 类的实例。

参数:
  • args – 要传递给 diskfile manager 构造函数的 positional 参数。

  • kwargs – 要传递给 diskfile manager 构造函数的 keyword 参数。

返回值:

一个 disk file manager 实例。

get_info(config=False)

返回此策略的信息字典和 conf 文件选项。

参数:

config – 布尔值,如果为 True,则返回所有配置选项

load_ring(swift_dir, reload_time=None)

立即加载此策略的 ring。

参数:
  • swift_dir – ring 的路径

  • reload_time – 检查 ring 更改的秒数间隔

property quorum

代理认为客户端请求成功的所需成功后端请求数。

classmethod register(policy_type)

用于 Storage Policy 实现的装饰器,用于注册它们的 StoragePolicy 类。这还将设置已注册实现上的 policy_type 属性。

remove_name(name)

从存储策略中移除一个别名。不应直接从存储策略调用此方法,而应通过存储策略集合类调用,以便按名称查找能够正确解析。如果移除的名称是主名称,则下一个可用的别名将成为新的主名称。

参数:

name – 分配给存储策略的名称

validate_ring_data(ring_data)

加载 ring 时使用的验证钩子;目前仅用于 EC

class swift.common.storage_policy.ECStoragePolicy(idx, name='', aliases='', is_default=False, is_deprecated=False, object_ring=None, diskfile_module='egg:swift#erasure_coding.fs', ec_segment_size=1048576, ec_type=None, ec_ndata=None, ec_nparity=None, ec_duplication_factor=1)

Bases: BaseStoragePolicy

表示“erasure_coding”类型的存储策略。

不应直接实例化;使用 reload_storage_policies()swift.conf 加载 POLICIES。

property ec_scheme_description

EC schema 中重要部分的这种简写形式存储在 EC 片段存档的对象系统元数据中,用于调试。

property fragment_size

片段的最大长度,包括头部。

注意:片段存档是由 0 个或多个最大长度片段后跟一个可能较短的片段组成的序列。

get_backend_index(node_index)

PyECLib 的后端索引

参数:

node_index – 节点索引的整数

返回值:

实际片段索引的整数。如果参数不是整数,则返回 None。

get_info(config=False)

返回此策略的信息字典和 conf 文件选项。

参数:

config – 布尔值,如果为 True,则返回所有配置选项

property quorum

代理认为客户端 PUT 请求成功的所需成功后端请求数。

EC 策略的仲裁大小定义了保证所需容错能力的最小数据+奇偶校验元素数量,该数量是数据元素的数量加上所选擦除编码方案所需的最小奇偶校验元素数量。

例如,对于 Reed-Solomon,所需的最小奇偶校验元素数量是 1,因此仲裁大小要求是 ec_ndata + 1。

鉴于所需奇偶校验元素的数量对于每种擦除编码方案并非相同,请查阅 PyECLib 中的 min_parity_fragments_needed()。

validate_ring_data(ring_data)

EC 特定验证

副本计数检查 - 我们至少需要配置(#data + #parity)个副本。此外,如果副本计数大于确切数字,则对于考虑 ring 中的主列表节点数的代码存在非零风险。

exception swift.common.storage_policy.PolicyError(msg, index=None)

Bases: ValueError

class swift.common.storage_policy.StoragePolicy(idx, name='', is_default=False, is_deprecated=False, object_ring=None, aliases='', diskfile_module='egg:swift#replication.fs')

Bases: BaseStoragePolicy

表示“replication”类型的存储策略。除非从 swift.conf 覆盖,否则为默认存储策略类。

不应直接实例化;使用 reload_storage_policies()swift.conf 加载 POLICIES。

property quorum
复制情况下的仲裁概念

floor(副本数量 / 2) + 1

class swift.common.storage_policy.StoragePolicyCollection(pols)

基类: object

此类表示集群的有效存储策略的集合,并在 swift.confparse_storage_policies() 解析时,将 StoragePolicy 对象添加到该集合中。

创建 StoragePolicyCollection 时,将执行以下验证:

  • 如果未声明索引为 0 的策略且未定义其他策略,Swift 将创建一个。

  • 策略索引必须是非负整数。

  • 如果未声明任何策略为默认策略且未定义其他策略,则索引为 0 的策略将被设置为默认策略。

  • 策略索引必须是唯一的。

  • 策略名称是必需的。

  • 策略名称不区分大小写。

  • 策略名称必须只包含字母、数字或连字符。

  • 策略名称必须是唯一的。

  • 策略名称 'Policy-0' 只能用于索引为 0 的策略。

  • 如果定义了任何策略,则必须声明一个策略作为默认策略。

  • 已弃用的策略不能声明为默认策略。

add_policy_alias(policy_index, *aliases)

向策略添加一个或多个新名称。

参数:
  • policy_index – 此策略集合中某个策略的索引。

  • aliases – 任意数量的字符串策略名称要添加。

change_policy_primary_name(policy_index, new_name)

更改策略的主名称或默认名称。新的主名称可以是已属于该策略的别名,也可以是全新的名称。

参数:
  • policy_index – 此策略集合中某个策略的索引。

  • new_name – 要设置为新默认名称的字符串名称。

get_by_index(index)

按索引查找存储策略。

索引 None 将被视为 0。

参数:

index – 存储策略的数字索引

返回值:

存储策略,如果不存在则为 None

get_by_name(name)

按名称查找存储策略。

参数:

name – 策略的名称

返回值:

存储策略,如果不存在则为 None

get_object_ring(policy_idx, swift_dir)

根据策略获取用于处理请求的环对象。

索引 None 将被视为 0。

参数:
  • policy_idx – 在 swift.conf 中定义的策略索引

  • swift_dir – 调用者使用的 swift_dir

返回值:

相应的环对象

get_policy_info()

为 /info 端点构建关于策略的信息

返回值:

包含相关策略信息的字典列表

remove_policy_alias(*aliases)

从策略中移除一个或多个名称。如果移除的名称是主名称,则下一个可用的别名将成为新的主名称。

参数:

aliases – 要移除的任意数量的现有策略名称。

class swift.common.storage_policy.StoragePolicySingleton

基类: object

此类的一个实例是暴露为模块级别全局变量 POLICIES 的存储策略的主要接口。此全局引用封装了 _POLICIES,后者通常通过解析 swift.conf 来实例化,并将生成 StoragePolicyCollection 类的实例。

您永远不应直接修补此实例,而应修补模块级别的 _POLICIES 实例,以便直接导入 POLICIES 的 swift 代码将引用已修补的 StoragePolicyCollection 类。

swift.common.storage_policy.get_policy_string(base, policy_or_index)

辅助函数,用于从基础字符串和策略构造字符串。用于通过各种模块将策略索引编码为文件名或目录名。

参数:
  • base – 基础字符串

  • policy_or_index – StoragePolicy 实例,或索引(字符串或整数),如果为 None,则假定为传统的 storage Policy-0。

返回值:

带策略索引的基础名称

引发:

PolicyError – 如果给定的 policy_index 不存在对应的策略

swift.common.storage_policy.parse_storage_policies(conf)

解析 swift.conf 中的存储策略 - 请注意,验证是在实例化 StoragePolicyCollection 时完成的。

参数:

conf – swift.conf 的 ConfigParser 解析器对象

swift.common.storage_policy.reload_storage_policies()

swift.conf 重新加载 POLICIES。

swift.common.storage_policy.split_policy_string(policy_string)

辅助函数,用于将表示基础字符串和策略的字符串转换为其他格式。用于通过各种模块从文件名或目录名解码策略。

参数:

policy_string – 带策略索引的基础名称

引发:

PolicyError – 如果给定的索引不映射到有效的策略

返回值:

一个元组,形式为 (base, policy),其中 base 是基础字符串,policy 是 policy_string 中编码的索引对应的 StoragePolicy 实例。

Swob

WSGI Request 和 Response 对象的实现。

该库的 API 与 Webob 非常相似。它将 WSGI 请求环境和响应值封装到更易于交互的对象中。

为什么是 Swob 而不是直接使用 WebOb?作者:Michael Barton

我们使用 webob 已经很多年了。主要问题是其接口不稳定。有一段时间,我们几个测试套件都需要不同版本的 webob 才能运行,而且没有一个与当时最新版本兼容。这带来了巨大的麻烦,所以我们干脆放弃了。

这涉及到大量的代码,但不用在每次 webob 决定某个接口需要更改时,都要到处添加大量代码分支来使 Swift 保持工作状态,这也带来了巨大的解脱。

class swift.common.swob.Accept(headerval)

基类: object

将 Request 的 Accept 头部封装为易于使用的对象。

参数:

headerval – 头部的值,作为字符串

best_match(options)

从“options”中返回最符合accept标头的项。如果没有任何可用选项能被客户端接受,则返回None。

参数:

options – 服务器可以响应的内容类型列表

引发:

ValueError – 如果标头格式错误

exception swift.common.swob.HTTPException(*args, **kwargs)

Bases: Response, Exception

class swift.common.swob.HeaderEnvironProxy(environ)

继承自 MutableMapping

一个类似字典的对象,它代理请求到wsgi environ,并将标头键重写为environ键。

例如,headers[‘Content-Range’]设置和获取headers.environ[‘HTTP_CONTENT_RANGE’]的值

keys() 一个 类似 set 的对象,提供D的键的视图
class swift.common.swob.Match(headerval)

基类: object

将请求的If-[None-]Match标头包装成一个友好的对象。

参数:

headerval – 头部的值,作为字符串

class swift.common.swob.Range(headerval)

基类: object

将请求的Range标头包装成一个友好的对象。初始化后,“range.ranges”将填充一个(start, end)元组列表,表示请求的范围。

如果存在任何语法无效的字节范围规范值,则构造函数将根据相关RFC抛出ValueError。

“接收到一个包含一个或多个语法无效字节范围规范值的字节范围集,必须忽略包含该字节范围集的字段。”

根据RFC 2616规范,以下情况均被视为语法无效,因此会抛出ValueError,以便忽略range标头。如果range值包含以下任何一种情况,则整个range被视为无效,并抛出ValueError以便忽略标头。

  1. 值不以bytes=开头

  2. range值的开始大于结束,例如bytes=5-3

  3. range没有开始或结束,例如bytes=-

  4. range没有连字符,例如bytes=45

  5. range值不是数字

  6. 以上任何组合

每个语法有效的范围都将被添加到ranges列表中,即使有些范围可能无法被底层内容满足。

参数:

headerval – 头部的值,作为字符串

ranges_for_length(length)

此方法用于返回给定长度的多个范围,该长度应表示底层内容的长度。构造函数__init__已确保ranges列表中的任何范围在语法上都是有效的。因此,如果length为None或ranges的大小为零,则应忽略Range标头,这将最终使响应为200。

如果此方法返回一个空列表,则表示在Range标头中找到不可满足的范围,将返回416。

如果返回的列表至少有一个元素,则该列表表示至少有一个范围是有效的,服务器应以206状态码处理请求。

每个范围的开始值表示内容中的起始位置,结束值表示结束位置。此方法故意将结束数字加1,因为规范定义Range是包含性的。

Range规范可以在以下链接找到:http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1

参数:

length – 底层内容的长度

class swift.common.swob.Request(environ)

基类: object

WSGI Request对象。

property accept

以Accept对象的形式检索和设置WSGI environ中的accept属性

property acl

获取和设置WSGI环境中的swob.ACL属性

classmethod blank(path, environ=None, headers=None, body=None, **kwargs)

使用给定的参数创建一个新的请求对象,并使用其他非预期默认值的环境。

参数:
  • path – 编码、解析并从PATH_INFO中取消引号

  • environ – WSGI environ字典

  • headers – HTTP标头

  • body – 填充到WsgiBytesIO中并附加到wsgi.input

  • kwargs – 任何具有属性设置器的environ键

property body

获取和设置请求体字符串

property body_file

获取和设置WSGI环境中的wsgi.input属性

call_application(application)

使用此请求的环境调用应用程序。将响应的状态、标头和app_iter作为元组返回。

参数:

application – 要调用的WSGI应用程序

property content_length

以整数形式检索和设置content-length标头

copy_get()

复制请求,将其转换为GET。

ensure_x_timestamp()

类似于timestamp,但如果X-Timestamp标头不存在,则会将其设置。

引发:

HTTPBadRequest – 如果X-Timestamp已设置但不是有效的Timestamp

返回值:

请求的X-Timestamp标头,作为Timestamp

get_response(application)

使用此请求的环境调用应用程序。返回一个包装应用程序结果的Response对象。

参数:

application – 要调用的WSGI应用程序

property host

获取和设置WSGI环境中的HTTP_HOST属性

property host_url

获取请求/响应到路径的URL

property if_match

以Match对象的形式检索和设置WSGI environ中的if-match属性

property if_modified_since

以datetime的形式检索和设置if-modified-since标头,使用datetime、int或str进行设置

property if_none_match

以Match对象的形式检索和设置WSGI environ中的if-none-match属性

property if_unmodified_since

以datetime的形式检索和设置if-unmodified-since标头,使用datetime、int或str进行设置

message_length()

正确确定此请求的消息长度。如果标头显式包含消息长度,则返回一个整数;如果标头不包含长度,则返回None。如果标头无效,将引发ValueError。

引发:
  • ValueError – 如果transfer-encoding或content-length标头的值不正确

  • AttributeError – 如果transfer-encoding标头的最后一个值不是“chunked”

property method

获取和设置WSGI环境中的REQUEST_METHOD属性

property params

以字典形式提供QUERY_STRING参数

property path

提供请求的完整路径,不包括QUERY_STRING

property path_info

获取和设置WSGI环境中的PATH_INFO属性

path_info_pop()

从path_info中取出一个路径部分(由斜杠分隔),并将其附加到script_name。返回路径段。

property path_qs

请求的路径,不带主机但带查询字符串。

property query_string

获取和设置WSGI环境中的QUERY_STRING属性

property range

以Range对象的形式检索和设置WSGI environ中的range属性

property referer

获取和设置WSGI环境中的HTTP_REFERER属性

property referrer

获取和设置WSGI环境中的HTTP_REFERER属性

property remote_addr

获取和设置WSGI环境中的REMOTE_ADDR属性

property remote_user

获取和设置WSGI环境中的REMOTE_USER属性

property script_name

获取和设置WSGI环境中的SCRIPT_NAME属性

split_path(minsegs=1, maxsegs=None, rest_with_last=False)

验证并分割请求路径。

示例:

['a'] = split_path('/a')
['a', None] = split_path('/a', 1, 2)
['a', 'c'] = split_path('/a/c', 1, 2)
['a', 'c', 'o/r'] = split_path('/a/c/o/r', 1, 3, True)
参数:
  • minsegs – 要提取的最小段数

  • maxsegs – 要提取的最大段数

  • rest_with_last – 如果为True,则将剩余数据作为最后一个段返回。如果为False,并且存在剩余数据,则引发ValueError。

返回值:

段列表,长度为maxsegs(不存在的段将返回None)

引发:

ValueError – 如果给定无效路径

property str_params

以字典形式提供QUERY_STRING参数

property swift_entity_path

提供(原生字符串)帐户/容器/对象路径,不包含API版本。

这在构造要发送到后端服务器的路径时可能很有用,因为该路径需要“/v1”之后的所有内容。

property timestamp

提供HTTP_X_TIMESTAMP作为Timestamp

property url

提供请求的完整URL

property user_agent

获取和设置WSGI环境中的HTTP_USER_AGENT属性

class swift.common.swob.Response(body=None, status=200, headers=None, app_iter=None, request=None, conditional_response=False, conditional_etag=None, **kw)

基类: object

WSGI Response对象。

__call__(env, start_response)

响应WSGI请求。

警告

这将使用WSGI环境的HOST_URL作为前缀,将任何相对的Location标头值转换为绝对URL,如RFC 2616所指定。

然而,使用相对重定向是很常见的,特别是当很难知道实际的HOST_URL在几个CNAME、CDN服务等后面时。所有现代浏览器都支持相对重定向。

要跳过对Location标头值的RFC强制执行,可以在WSGI环境中设置env['swift.leave_relative_location'] = True

absolute_location()

尝试构建一个绝对位置。

property accept_ranges

检索和设置accept-ranges标头

property app_iter

检索和设置响应app_iter

property body

检索和设置Response体字符串

property charset

检索和设置响应的charset

property conditional_etag

Response的conditional_etag关键字参数允许将If-Match请求的条件匹配值与非标准值进行比较。

这对于不将客户端对象数据逐字存储在存储节点上,但仍需要支持条件请求的存储策略是可用的。

它与X-Backend-Etag-Is-At结合使用效果最好,后者将定义一个或多个元数据键,其中可以找到清晰格式客户端请求数据的原始ETag。

property content_length

以整数形式检索和设置content-length标头

property content_range

检索和设置content-range标头

property content_type

检索和设置响应的Content-Type标头

property etag

检索和设置响应的Etag标头

fix_conditional_response()

在设置了整个对象长度的content_length以及body或app_iter之后,您可以调用此方法来重置请求上的content_length属性。

不调用此方法也可以,当您调用响应时,条件响应会为您维护。

property host_url

获取请求/响应到路径的URL

property last_modified

以datetime的形式检索和设置last-modified标头,使用datetime、int或str进行设置

property location

检索和设置location标头

property status

检索和设置Response状态,例如“200 OK”

www_authenticate()

构建WWW-Authenticate响应标头的一个合适的值

如果我们有一个请求和一个看起来有效的路径,那么领域就是帐户;否则,我们将其设置为“unknown”。

class swift.common.swob.StatusMap

基类: object

一个类似字典的对象,它返回HTTPException子类/工厂函数,其中给定的键是状态码。

class swift.common.swob.WsgiBytesIO(initial_bytes=b'')

继承自 BytesIO

此类为BytesIO类添加了对eventlet.wsgi.Input上定义的其他wsgi.input方法的支持,否则BytesIO类将是WSGI环境中类文件对象的良好替代品。

swift.common.swob.wsgify(func)

一个装饰器,用于将接受swob Request对象并返回Response对象的函数转换为WSGI可调用对象。它还会捕获所有引发的HTTPExceptions,并将它们视为返回的Response。

Timestamp

与Swift一起使用的与时间戳相关的函数。

class swift.common.utils.timestamp.Timestamp(timestamp, offset=0, delta=0, check_bounds=True)

基类: object

Swift时间的内部表示。

X-Timestamp标头的规范化形式看起来像一个固定宽度的浮点数,以确保稳定的字符串排序——规范化时间戳看起来像“1402464677.04188”。

为了支持覆盖现有数据而不修改原始时间戳但仍保持一致性,在规范化时间戳格式之后附加了一个第二个内部偏移量向量,该向量比较和排序的优先级高于固定宽度浮点格式,但低于较新的时间戳。时间戳的内部格式看起来像“1402464677.04188_0000000000000000”——下划线之后的部分是偏移量,是一个格式化的十六进制整数。

内部格式不会在Swift的响应中暴露给客户端。常规的客户端操作不会创建带有偏移量的时间戳。

common.utils中的Timestamp类支持时间戳的内部和规范化格式,以及时间戳值的比较。当Timestamp的offset值为0时——它被认为是微不足道的,无需在字符串格式中表示;为了在Swift升级期间支持向后兼容,具有微不足道偏移量的时间戳的内部和规范化格式是相同的。当时间戳包含偏移量时,它将始终以内部格式表示,但仍会从规范化格式中排除。具有等效时间戳部分(浮点部分)的时间戳将根据其偏移量进行比较和排序。具有较大时间戳部分的时间戳将始终与具有较小时间戳的时间戳进行比较和排序,无论其偏移量如何。字符串比较和排序保证是针对内部字符串格式的,并且对于不包含偏移量的时间戳是向后兼容的。

ceil()

返回时间戳的“正常”部分,向上舍入到最近的整数秒。

每当需要资源的秒精度Last-Modified时间时,都应使用此值。

返回值:

秒精度浮点值。

classmethod from_isoformat(date_string)

将时间的isoformat字符串表示形式解析为Timestamp对象。

参数:

date_string – 格式为Timestamp.isoformat属性的字符串。

返回值:

此类的一个实例。

property isoformat

获取“正常”部分Timestamp的isoformat字符串表示形式,具有微秒精度且没有尾随timezone,例如

1970-01-01T00:00:00.000000
返回值:

isoformat字符串

swift.common.utils.timestamp.decode_timestamps(encoded, explicit=False)

解析由encode_timestamps生成的字符串,并返回三个组件时间戳的元组。如果explicit为False,则显式编码的组件时间戳将假定与前一个组件的delta为零,因此具有前一个组件的值。如果explicit为True,则显式未编码的组件时间戳将返回None值。

swift.common.utils.timestamp.encode_timestamps(t1, t2=None, t3=None, explicit=False)

将最多三个时间戳编码为一个字符串。与Timestamp对象不同,编码后的字符串不使用固定宽度字段,因此无法从编码时间戳字符串的字典序排序中推断出时间戳的相对时序。

编码字符串的格式为

<t1>[<+/-><t2 - t1>[<+/-><t3 - t2>]]

即,如果t1 = t2 = t3,则只返回t1的字符串表示形式,否则将附加t2和t3的时间偏移量。如果explicit为True,则总是附加t2和t3的偏移量,即使它们为零。

注意:t1中的任何偏移量都将被保留,但t2和t3上的偏移量不会被保留。在此方法的预期用法(及其反向decode_timestamps方法)中,传递给t2和t3的时间戳预计不会有偏移量,因为它们将是与POST请求相关联的时间戳。在编码用于容器对象表行的情况下,t1可以是PUT或DELETE时间,但t2和t3代表内容类型和元数据时间(如果与数据文件不同),即对应于POST时间戳。在编码形式用于.meta文件名的 mexicana,t1和t2都对应于POST时间戳。

swift.common.utils.timestamp.last_modified_date_to_timestamp(last_modified_date_str)

将上次修改日期(如容器列表中的日期,例如2014-02-28T23:22:36.698390)转换为浮点数。

swift.common.utils.timestamp.normalize_delete_at_timestamp(timestamp, high_precision=False)

将时间戳(字符串或数字)格式化为标准化的xxxxxxxxxx(10位)或xxxxxxxxxx.xxxxx(10.5位)格式。

请注意,小于0000000000的时间戳将被提升到0000000000,而大于2286年11月20日17:46:39 UTC的值将被限制在此时,导致返回值不超过9999999999.99999(或9999999999,如果使用低精度)。

此上限是因为expirer已经在处理一个由10位数的字符串组成的排序列表。添加另一个数字会扰乱排序,导致expirer提前停止处理。到2286年,这个问题将需要解决,可能通过创建一个额外的.expiring_objects帐户来处理11位(或更多)数字的容器名称。

参数:

timestamp – unix时间戳

返回值:

规范化后的时间戳(字符串格式)

swift.common.utils.timestamp.normalize_timestamp(timestamp)

将时间戳(字符串或数字)格式化为标准化的xxxxxxxxxx.xxxxx(10.5位)格式。

请注意,大于或等于2286年11月20日17:46 UTC的时间戳将使用11位数字来表示秒数。

参数:

timestamp – unix时间戳

返回值:

规范化后的时间戳(字符串格式)

Utils Base

可以在其他utils模块中使用的杂项实用函数。

此模块被其他utils模块导入。此模块不应从其他utils模块导入。

swift.common.utils.base.get_valid_utf8_str(str_or_unicode)

从str、unicode甚至无效的utf-8 str获取有效的utf-8 str部分

参数:

str_or_unicode – 一个可能是无效utf-8的字符串或unicode

swift.common.utils.base.md5(string=b'', usedforsecurity=True)

使用usedforsecurity参数返回一个md5 hashlib对象

对于支持usedforsecurity关键字参数的Python发行版,此参数将按预期传递。请参阅https://bugs.python.org/issue9216

swift.common.utils.base.quote(value, safe='/')

修补后的urllib.quote版本,该版本在引用之前编码utf-8字符串

swift.common.utils.base.split_path(path, minsegs=1, maxsegs=None, rest_with_last=False)

验证并分割给定的HTTP请求路径。

示例:

['a'] = split_path('/a')
['a', None] = split_path('/a', 1, 2)
['a', 'c'] = split_path('/a/c', 1, 2)
['a', 'c', 'o/r'] = split_path('/a/c/o/r', 1, 3, True)
参数:
  • path – 要分割的HTTP请求路径

  • minsegs – 要提取的最小段数

  • maxsegs – 要提取的最大段数

  • rest_with_last – 如果为True,则将剩余数据作为最后一个段返回。如果为False,并且存在剩余数据,则引发ValueError。

返回值:

段列表,长度为maxsegs(不存在的段将返回None)

引发:

ValueError – 如果给定无效路径

Utils

用于Swift的杂项实用函数。

swift.common.utils.ATTRIBUTES_RE = re.compile('(\\w+)=(".*?"|[^";]+)(; ?|$)')

匹配表单属性的正则表达式。

class swift.common.utils.CloseableChain(*iterables)

Bases: ClosingIterator

类似于itertools.chain,但有一个close方法,该方法将尝试调用其子迭代器的close方法(如果存在)。

class swift.common.utils.ClosingIterator(iterable, other_closeables=None)

基类: object

包装另一个迭代器,并在完成/异常时关闭它(如果可能)。

如果提供了其他可关闭对象,那么在关闭此迭代器时也会关闭它们。

这对于确保生成器正确关闭其资源特别有用,即使生成器从未启动。

此类可以被子类化以覆盖_get_next_item的行为。

参数:
  • iterable – 要包装的迭代器。

  • other_closeables – 要尝试关闭的其他资源。

class swift.common.utils.ClosingMapper(function, iterable, other_closeables=None)

Bases: ClosingIterator

一个可关闭的迭代器,它在将function应用于iterable的每个项后,产生结果。

请注意,虽然此行为与内置的map函数类似,但other_closeables的语义与mapiterables参数不同。

参数:
  • function – 一个函数,它将在应用到iterable的每个项后被调用,然后产生其结果。

  • iterable – 要包装的迭代器。

  • other_closeables – 要尝试关闭的其他资源。

class swift.common.utils.ContextPool(size=1000)

Bases: GreenPool

GreenPool的子类,当它被垃圾回收时会杀死其协程

class swift.common.utils.CooperativeIterator(iterable, period=5)

Bases: ClosingIterator

包装器,用于在迭代被包装的迭代器时,定期调用sleep(),提供切换协程的机会。

这是为了公平性;如果网络速度超过CPU速度,我们将始终能够读写数据而不会遇到EWOULDBLOCK,因此eventlet不会自己切换协程。我们这样做是为了避免客户端饿死。

这里的数字5是通过胡编乱造选取的。它不是每一个块,但也不是太大,所以看起来可能是一个不错的选择。

请注意,根据网络IO的阻塞程度,我们可能会比每5个块调用一次协程的次数更频繁地进行蹦床;这里的显式sleep只是为蹦床速率提供了一个下限。

参数:
  • iterable – 要包装的迭代器。

  • period – 在调用sleep()之间从此迭代器产生的项数;负值或0表示已禁用协作睡眠。

class swift.common.utils.Everything

基类: object

一个包含一切的容器。如果“e”是Everything的一个实例,那么“x in e”对于所有x都为真。

class swift.common.utils.GreenAsyncPile(size_or_pool)

基类: object

在协程线程池中运行作业,并通过将此对象用作迭代器来检索结果。

这在原则上与eventlet.GreenPile非常相似,但它返回可用结果,而不是按启动顺序返回。

如果需要,将结果与作业关联留给调用者。

spawn(func, *args, **kwargs)

在堆上的协程线程中生成一个作业。

waitall(timeout)

等待timeout秒,直到有结果返回。

参数:

timeout – 等待结果的秒数

返回值:

在此期间累积的结果列表

waitfirst(timeout)

最多等待timeout秒,直到第一个结果返回。

参数:

timeout – 等待结果的秒数

返回值:

第一个返回的项目,或None

exception swift.common.utils.GreenAsyncPileWaitallTimeout(seconds=None, exception=None)

Bases: Timeout

class swift.common.utils.GreenthreadSafeIterator(unsafe_iterable)

基类: object

包装一个迭代器,以确保一次只有一个协程在其next()方法中执行。

这对于迭代器的next()方法可能执行网络IO非常有用,因为这可能会触发协程上下文切换(也称为蹦床),这会给另一个协程切换的机会来调用next()。届时,您会收到类似“ValueError: generator already executing”的错误。通过用互斥锁包装next()的调用,我们可以避免该错误。

class swift.common.utils.InputProxy(wsgi_input)

基类: object

一个类文件对象,用于计算读取的字节数。用于计数目的,替换wsgi.input。

参数:

wsgi_input – 要包装的类文件对象

bytes_received

从包装的输入中读取的总字节数

chunk_update(chunk, eof, *args, **kwargs)

每次从包装的输入中读取字节块时调用。

参数:
  • chunk – 已读取的字节块。

  • eof – 如果从包装的输入中没有更多字节可读,则为True,否则为False。如果已调用read(),则当chunk的大小小于请求的大小或请求大小为None时,此值为True。如果调用了readline,则当读取不完整的行(即不以b'\n'结尾)且其长度小于请求大小或请求大小为None时,此值为True。如果使用恰好等于包装输入剩余字节数的请求大小调用read()readline(),则eof将为False。随后的read()readline()调用,使用非零size,将导致eofTrue。或者,可以通过比较bytes_received与输入的预期长度来推断输入的结束。

client_disconnect

如果read()readline()引发异常,则为True,否则为False

read(size=None, *args, **kwargs)

将读取请求传递给底层类文件对象,并将读取的字节数添加到总数中。

参数:

size – (可选) 要读取的最大字节数;默认的None表示无限制。

readline(size=None, *args, **kwargs)

将readline请求传递给底层类文件对象,并将读取的字节数添加到总数中。

参数:

size – (可选) 要从当前行读取的最大字节数;默认的None表示无限制。

exception swift.common.utils.InvalidHashPathConfigError

Bases: ValueError

class swift.common.utils.LRUCache(maxsize=1000, maxtime=3600)

基类: object

用于大小/时间受限的内存缓存的装饰器,它会逐出最近最少使用的成员。

class swift.common.utils.Namespace(name, lower, upper)

基类: object

Namespace封装了定义对象命名空间范围的参数。

参数:
  • nameNamespace的名称;此名称应采用容器路径的形式,即<account_name>/<container_name>。

  • lower – 命名空间中对象名称的下界;下界*不*包含在命名空间中。

  • upper – 命名空间中对象名称的上界;上界*包含*在命名空间中。

class swift.common.utils.MaxBound

Bases: NamespaceOuterBound

class swift.common.utils.MinBound

Bases: NamespaceOuterBound

entire_namespace()

返回此命名空间是否包含整个命名空间,否则返回False。

expand(donors)

根据需要扩展边界以匹配给定捐助者的最小和最大边界。

参数:

donorsNamespace对象列表

返回值:

如果边界已修改,则返回True,否则返回False。

includes(other)

返回此命名空间是否包含其他命名空间的全部内容,否则返回False。

参数:

otherNamespace的实例

overlaps(other)

返回此命名空间是否与另一个命名空间重叠。

参数:

otherNamespace的实例

class swift.common.utils.NamespaceOuterBound

基类: object

用于Namespace外边界的自定义单例类型。

class swift.common.utils.OverrideOptions(devices, partitions, policies)

基类: tuple

devices

字段编号 0 的别名

partitions

字段编号 1 的别名

policies

字段编号 2 的别名

class swift.common.utils.RateLimitedIterator(iterable, elements_per_second, limit_after=0, ratelimit_if=<function RateLimitedIterator.<lambda>>)

基类: object

包装一个迭代器,使其每秒只产生 N 个元素。

参数:
  • iterable – 要包装的可迭代对象

  • elements_per_second – 产生元素的速率

  • limit_after – 仅在产生此数量的元素后才开始限速;默认为 0(立即限速)

class swift.common.utils.ShardName(account, root_container, parent_container_hash, timestamp, index)

基类: object

封装了 shard 名称的组成部分。

此类的实例通常通过 create() 或 parse() 类方法创建。

Shard 名称的格式为

<account>/<root_container>-<parent_container_hash>-<timestamp>-<index>

注意:ShardRange 的某些实例的名称将无法解析为 ShardName;例如,一个 root container 本身的 shard range 的名称格式为 <account>/<root_container>,将其传递给 parse() 时会引发 ValueError。

classmethod create(account, root_container, parent_container, timestamp, index)

创建 ShardName 的实例。

参数:
  • account – shard container 所属的隐藏内部帐户。

  • root_container – shard 的 root container 的名称。

  • parent_container – shard 的 parent container 的名称;对于最初的第一代 shard,它应该与 root_container 相同;对于 shard 的 shard,它应该是 sharding shard container 的名称。

  • timestampTimestamp 的实例

  • index – 一个唯一索引,用于区分此路径与使用相同的 accountroot_containerparent_containertimestamp 组合生成的任何其他路径。

返回值:

此类的实例。

引发:

ValueError – 如果任何参数为 None

classmethod hash_container_name(container_name)

计算 container 名称的哈希值。

参数:

container_name – 要哈希的名称。

返回值:

container_name 的 md5 哈希值的十六进制摘要。

引发:

ValueError – 如果 container_name 为 None。

classmethod parse(name)

解析 nameShardName 的实例。

参数:

name – shard 名称,格式应为:<account>/ <root_container>-<parent_container_hash>-<timestamp>-<index>

返回值:

此类的实例。

引发:

ValueError – 如果 name 不是有效的 shard 名称。

class swift.common.utils.ShardRange(name, timestamp=0, lower=MinBound, upper=MaxBound, object_count=0, bytes_used=0, meta_timestamp=None, deleted=False, state=None, state_timestamp=None, epoch=None, reported=False, tombstones=-1, **kwargs)

Bases: Namespace

ShardRange 封装了与 container 相关的 sharding 状态,包括定义 container 负责的对象命名空间的 lower 和 upper 边界。

Shard range 可以持久化到 container 数据库中。与 shard range 属性子集关联的时间戳用于在需要将 shard range 合并到现有 shard range 记录时解决冲突,并持久化属性的最新版本。

参数:
  • name – shard range 的名称;此名称必须采用 container 路径的形式,即 <account_name>/<container_name>。

  • timestamp – 表示 shard range 的 lowerupperdeleted 属性上次修改时间的时间戳。

  • lower – shard range 中对象名称的下界;下界包含在 shard range 命名空间中。

  • upper – shard range 中对象名称的上界;上界包含在 shard range 命名空间中。

  • object_count – shard range 中的对象数量;默认为零。

  • bytes_used – shard range 中的字节数;默认为零。

  • meta_timestamp – 表示 shard range 的 object_countbytes_used 上次更新时间的时间戳;默认为 timestamp 的值。

  • deleted – 布尔值;如果为 True,则 shard range 被视为已删除。

  • state – 状态;必须是 ShardRange.STATES 之一;默认为 CREATED。

  • state_timestamp – 表示 state 被强制设置为其当前值的时间戳;默认为 timestamp 的值。通常,此时间戳不会随着 state 的每次更改而更新,因为通常通过选择较大的 state 值来解决 state 属性中的冲突。但是,当此规则不适用时,例如从 SHARDED 更改为 ACTIVE 时,state_timestamp 可能会提前,以便新 state 值优先于任何旧 state 值。

  • epoch – 可选的 epoch 时间戳,表示 container 的 sharding 启用时间。

  • reported – 可选指示器,表示此 shard 及其统计信息已报告给 root container。

  • tombstones – shard range 中的 tombstones 数量;默认为 -1,表示值未知。

copy(timestamp=None, **kwargs)

创建 ShardRange 的副本。

参数:

timestamp – (可选)如果给定,则返回的 ShardRange 将其所有时间戳设置为此值。否则,返回的 ShardRange 将具有原始时间戳。

返回值:

此类的实例。

find_ancestors(shard_ranges)

在给定的 shard_ranges 中查找此 shard range 的祖先 range。

此方法尽最大努力识别此 shard range 的父 shard range、父类的父类等,直至包括 root shard range。只能直接识别某个 shard range 的父类,因此搜索是递归的;如果祖先中的任何一个未找到,则搜索结束,列表中可能存在的旧祖先将不会被识别。但是,如果 root shard range 存在于列表中,它总是会被识别。

例如,给定一个包含父类、祖父类、曾祖父类和 root shard range 的列表,但缺少曾祖父类 shard range,则只会识别父类、祖父类和 root shard range。

参数:

shard_rangesShardRange 实例的列表

返回值:

ShardRange 实例的列表,其中包含在给定的 shard_ranges 中可被识别为此 shard range 祖先的项目。如果祖先有缺口,列表可能不完整,但如果父类和 root shard range 存在于列表中,则保证至少包含它们。

find_root(shard_ranges)

在给定的 shard_ranges 中查找此 shard range 的 root shard range。

参数:

shard_rangesShardRange 实例的列表

返回值:

此 shard range 的 root shard range(如果找到);否则为 None。

classmethod from_dict(params)

使用给定的参数字典返回一个实例。此方法故意比类的 __init__() 方法更灵活,并且需要将 __init__() 的所有参数都包含在参数字典中。

参数:

params – 参数字典

返回值:

此类的实例。

increment_meta(object_count, bytes_used)

将对象统计元数据增加给定的值,并将 meta_timestamp 更新为当前时间。

参数:
  • object_count – 必须是一个整数

  • bytes_used – 必须是一个整数

引发:

ValueError – 如果 object_countbytes_used 无法转换为整数。

is_child_of(parent)

测试此 shard range 是否是另一个 shard range 的子项。父子关系是从 shard range 的名称推断出来的。此方法仅限于在同一用户可见帐户(带或不带 shard 前缀)的范围内工作。

参数:

parentShardRange 的实例。

返回值:

如果 parent 是此 shard range 的父类,则为 True;否则为 False,假设它们在同一帐户内。

classmethod make_path(shards_account, root_container, parent_container, timestamp, index)

返回一个 shard container 的路径,该路径可用作构造 ShardRange 时的名称。

参数:
  • shards_account – shard container 所属的隐藏内部帐户。

  • root_container – shard 的 root container 的名称。

  • parent_container – shard 的 parent container 的名称;对于最初的第一代 shard,它应该与 root_container 相同;对于 shard 的 shard,它应该是 sharding shard container 的名称。

  • timestampTimestamp 的实例

  • index – 一个唯一索引,用于区分此路径与使用相同的 shards_accountroot_containerparent_containertimestamp 组合生成的任何其他路径。

返回值:

格式为 <account_name>/<container_name> 的字符串

classmethod resolve_state(state)

给定一个可能是状态名称或状态编号的值,返回一个 (状态编号, 状态名称) 的元组。

参数:

state – 字符串状态名称或整数状态编号。

返回值:

一个元组 (状态编号, 状态名称)

引发:

ValueError – 如果 state 既不是有效状态名称也不是有效状态编号。

property row_count

返回 shard range 中的总行数,即对象和 tombstones 的总和。

返回值:

行数

set_deleted(timestamp=None)

将 shard range 标记为已删除,并将时间戳设置为当前时间。

参数:

timestamp – 可选要设置的时间戳;如果未给出,则设置为当前时间。

返回值:

如果 deleted 属性或时间戳已更改,则为 True,否则为 False

update_meta(object_count, bytes_used, meta_timestamp=None)

将对象统计元数据设置为给定的值,并将 meta_timestamp 更新为当前时间。

参数:
  • object_count – 必须是一个整数

  • bytes_used – 必须是一个整数

  • meta_timestamp – 元数据的时间戳;如果未给出,则设置为当前时间。

引发:

ValueError – 如果 object_countbytes_used 无法转换为整数,或者如果 meta_timestamp 不是 None 且无法转换为 Timestamp

update_state(state, state_timestamp=None)

将状态设置为给定值,并可选择将 state_timestamp 更新为给定时间。

参数:
  • state – 新状态,必须是整数

  • state_timestamp – 状态的时间戳;如果未给出,则 state_timestamp 不会更改。

返回值:

如果状态或 state_timestamp 已更改,则为 True,否则为 False

update_tombstones(tombstones, meta_timestamp=None)

将 tombstones 元数据设置为给定值,并将 meta_timestamp 更新为当前时间。

参数:
  • tombstones – 必须是一个整数

  • meta_timestamp – 元数据的时间戳;如果未给出,则设置为当前时间。

引发:

ValueError – 如果 tombstones 无法转换为整数,或者如果 meta_timestamp 不是 None 且无法转换为 Timestamp

class swift.common.utils.ShardRangeList(initlist=None)

Bases: UserList

此类提供了一些方便的函数来处理 ShardRange 的列表。

此类不强制列表项的排序或连续性:调用者应确保根据需要按顺序添加项。

property bytes_used

返回列表中所有项的总字节数。

返回值:

总字节使用量

filter(includes=None, marker=None, end_marker=None)

过滤列表,仅保留命名空间包含 includes 名称或 markerend_marker 之间的命名空间任何部分的 shard ranges。如果未指定 includesmarkerend_marker 中的任何一个,则将返回所有 shard ranges。

参数:
  • includes – 字符串;如果非空,则仅返回其命名空间包含此字符串的 shard range(如果存在),并且将忽略 markerend_marker

  • marker – 如果指定,则仅返回其上界大于此值的 shard ranges。

  • end_marker – 如果指定,则仅返回其下界小于此值的 shard ranges。

返回值:

一个新的 ShardRangeList 实例,包含过滤后的 shard ranges。

find_lower(condition)

查找满足给定条件的第一个 shard range 并返回其下界。

参数:

condition – 一个函数,它必须接受类型为 ShardRange 的单个参数,并在 shard range 满足条件时返回 True,否则返回 False。

返回值:

满足条件的第一个 shard range 的下界,或者如果未找到这样的 shard range,则为列表的 upper 值。

includes(other)

检查另一个 ShardRange 命名空间是否包含在列表的 lowerupper 属性之间。注意:只有当列表之前已排序时,列表的 lowerupper 属性才会等于列表中所有项的最外层边界。

注意:为了使此方法返回 True,列表不需要包含与 other 匹配的项,尽管如果列表已排序并且包含与 other 匹配的项,则该方法将返回 True。

参数:

otherShardRange 的实例

返回值:

如果 other 的命名空间被包含,则为 True,否则为 False。

property lower

返回列表中第一项的下界。注意:只有当列表内容已排序时,它才会等于列表中所有项的最低边界。

返回值:

列表中第一项的下界,如果列表为空,则为 Namespace.MIN。

property object_count

返回列表中所有项的总对象数。

返回值:

总对象计数

property row_count

返回列表中所有项的总行数。

返回值:

总行数

property upper

返回列表中最后一项的上界。注意:只有当列表已排序时,它才会等于列表中所有项的最高边界。

返回值:

列表中最后一项的上界,如果列表为空,则为 Namespace.MIN。

class swift.common.utils.Spliterator(source_iterable)

基类: object

接受一个产生可切片对象的迭代器(例如字符串或列表),并产生子迭代器,每个子迭代器从源中产生最多请求数量的项。

>>> si = Spliterator(["abcde", "fg", "hijkl"])
>>> ''.join(si.take(4))
"abcd"
>>> ''.join(si.take(3))
"efg"
>>> ''.join(si.take(1))
"h"
>>> ''.join(si.take(3))
"ijk"
>>> ''.join(si.take(3))
"l"  # shorter than requested; this can happen with the last iterator
class swift.common.utils.StreamingPile(size)

Bases: GreenAsyncPile

在 green thread 池中运行作业,在检索到结果并有可用工作线程时生成更多作业。

用作上下文管理器时,具有与 ContextPool 相同的销毁工作线程的特性。

asyncstarmap(func, args_iter)

这与 itertools.starmap() 相同,不同之处在于,func 在每个项目的一个单独的 green thread 中执行,并且结果的顺序不一定与输入的顺序相同。

class swift.common.utils.StringAlong(iterable, other_iter, unexpected_items_func)

Bases: ClosingIterator

此迭代器包装并迭代第一个迭代器,直到其停止,然后迭代第二个迭代器,期望它立即停止。第二个迭代器的这种“stringing along”在第二个迭代器的退出必须推迟到第一个迭代器停止时非常有用。例如,当第二个迭代器已经产生其项但拥有必须在第一个迭代器停止之前不能被垃圾回收的资源时。

第二个迭代器预计没有更多项,并在调用时引发 StopIteration。如果不是这种情况,则调用 unexpected_items_func

参数:
  • iterable – 一个被包装并迭代的第一个迭代器。

  • other_iter – 一个在第一个迭代器停止后停止的第二个迭代器。

  • unexpected_items_func – 一个无参数函数,当发现第二个迭代器有剩余项时会被调用。

class swift.common.utils.Watchdog

基类: object

实现一个 watchdog 以有效管理并发超时。

与 eventlet.timeouts.Timeout 相比,它通过避免调度操作(抛出异常)然后如果超时被取消则取消调度它们,从而减少了 eventlet 中的上下文切换次数。

  1. 在 T+0 时,请求 timeout(10)

    => watchdog greenlet 休眠 10 秒

  2. 在 T+1 时,请求 timeout(15)
    => 超时将在当前超时之后到期,无需唤醒

    watchdog greenlet

  3. 在 T+2 时,请求 timeout(5)
    => 超时将在第一个超时之前到期,唤醒

    watchdog greenlet 来计算新的睡眠周期

  4. 在 T+7 时,第三个超时到期
    => 抛出异常,然后 greenlet watchdog sleep(3) 以

    在第一个超时到期时唤醒

kill()

停止 watchdog greenthread。

spawn()

启动 watchdog greenthread。

start(timeout, exc, timeout_at=None)

安排一个超时操作

参数:
  • timeout – 超时到期前的持续时间

  • exc – 超时到期时要抛出的异常,必须继承自 eventlet.Timeout

  • timeout_at – 允许强制设置到期时间戳

返回值:

安排的超时的 ID,用于取消它

stop(key)

取消安排的超时

参数:

key – 超时 ID,由 start() 返回

class swift.common.utils.WatchdogTimeout(watchdog, timeout, exc, timeout_at=None)

基类: object

用于在 Watchdog 实例中安排超时的上下文管理器

swift.common.utils.audit_location_generator(devices, datadir, suffix='', mount_check=True, logger=None, devices_filter=None, partitions_filter=None, suffixes_filter=None, hashes_filter=None, hook_pre_device=None, hook_post_device=None, hook_pre_partition=None, hook_post_partition=None, hook_pre_suffix=None, hook_post_suffix=None, hook_pre_hash=None, hook_post_hash=None, error_counter=None, yield_hash_dirs=False)

给定一个设备路径和一个数据目录,为该目录中的所有文件生成 (path, device, partition)。

(devices|partitions|suffixes|hashes)_filter 用于修改将要迭代的元素列表。例如:它们可用于根据调用者定义的自定义条件排除某些元素。

hook_pre_(device|partition|suffix|hash) 在生成元素之前调用,hook_pos_(device|partition|suffix|hash) 在元素生成之后调用。它们用于进行一些预/后处理。例如:保存进度状态。

参数:
  • devices – 要审计的设备的父目录

  • datadir – 位于 self.devices 下的目录。这应该是 account、container 和 object 服务器中定义的 DATADIR 常量之一。

  • suffix – 所有返回的名称所需的路径名后缀(如果 yield_hash_dirs 为 True,则忽略)

  • mount_check – 标志,用于检查是否应在设备上执行挂载检查

  • logger – 一个日志记录器对象

  • devices_filter – 一个可调用对象,接受 (devices, [设备列表]) 作为参数并返回一个 [设备列表]

  • partitions_filter – 一个可调用对象,接受 (datadir_path, [部分列表]) 作为参数并返回一个 [部分列表]

  • suffixes_filter – 一个可调用对象,接受 (part_path, [后缀列表]) 作为参数并返回一个 [后缀列表]

  • hashes_filter – 一个可调用对象,接受 (suff_path, [哈希列表]) 作为参数并返回一个 [哈希列表]

  • hook_pre_device – 一个可调用对象,接受 device_path 作为参数

  • hook_post_device – 一个可调用对象,接受 device_path 作为参数

  • hook_pre_partition – 一个可调用对象,接受 part_path 作为参数

  • hook_post_partition – 一个可调用对象,接受 part_path 作为参数

  • hook_pre_suffix – 一个可调用对象,接受 suff_path 作为参数

  • hook_post_suffix – 一个可调用对象,接受 suff_path 作为参数

  • hook_pre_hash – 一个可调用对象,接受 hash_path 作为参数

  • hook_post_hash – 一个可调用对象,接受 hash_path 作为参数

  • error_counter – 用于累积错误计数的字典;可能会添加键 ‘unmounted’ 和 ‘unlistable_partitions’

  • yield_hash_dirs – 如果为 True,则生成哈希目录而不是单个文件

swift.common.utils.backward(f, blocksize=4096)

一个生成器,从文件返回行,从最后一行开始,然后是倒数第二行,依此类推;即,它向后读取行。在读取(如果存在)第一行时停止。这对于在非常大的文件中搜索最近的活动非常有用。

参数:
  • f – 要读取的文件对象

  • blocksize – 每次向后移动的字符数

swift.common.utils.cache_from_env(env, allow_none=False)

从环境中获取 memcache 连接池(该池先前已由 memcache 中间件设置)。

参数:

env – wsgi 环境字典

返回值:

swift.common.memcached.MemcacheRing 来自环境

swift.common.utils.closing_if_possible(maybe_closable)

与 contextlib.closing() 类似,但如果对象缺少 close() 方法,则不会崩溃。

PEP 333 (WSGI) 说:“如果应用程序返回的可迭代对象具有 close() 方法,服务器或网关必须在当前请求完成后调用该方法。”此函数使此操作更容易。

swift.common.utils.compute_eta(start_time, current_value, final_value)

计算 ETA。现在只能希望也有一个进度条……

参数:
  • start_time – 操作开始时的 Unix 时间戳

  • current_value – 当前值

  • final_value – 最终值

返回值:

ETA,表示为 (时间长度, 时间单位) 的元组,其中时间单位是 ('h', 'm', 's') 之一

swift.common.utils.csv_append(csv_string, item)

将项追加到逗号分隔的字符串。

如果逗号分隔的字符串为空/None,则仅返回项。

swift.common.utils.distribute_evenly(items, num_buckets)

将项尽可能均匀地分配到 N 个桶中。

swift.common.utils.document_iters_to_http_response_body(ranges_iter, boundary, multipart, logger)

接受范围迭代器的迭代器,并将其转换为适当的 HTTP 响应体,无论是 multipart/byteranges 还是非 multipart/byteranges。

这几乎是 request_helpers.http_response_to_document_iters() 的反向操作,但又不完全是。此函数仅生成响应体的块,不生成任何头部。

参数:
  • ranges_iter

    一个字典迭代器,每个字典代表一个范围。每个字典至少必须包含以下键:“part_iter”:一个产生范围中字节的迭代器

    此外,如果 multipart 为 True,则还需要以下其他键

    ”start_byte”:范围中第一个字节的索引 “end_byte”:范围中最后一个字节的索引 “content_type”:范围的 Content-Type 报头的 value

    最后,还有一个可选键用于

    multipart/byteranges 情况

    ”entity_length”:所请求实体的长度(不一定

    等于响应长度)。如果省略,则使用“*”。

    在调用 next(ranges_iter) 之前,每个 part_iter 都将被耗尽。

  • boundary – 要使用的 MIME 分隔符,不带破折号(例如,“boundary”,而不是“–boundary”)。

  • multipart – 如果响应应为 multipart/byteranges,则为 True,否则为 False。只有在有 2 个或更多范围时,此值才应为 True。

  • logger – 一个 logger

swift.common.utils.document_iters_to_multipart_byteranges(ranges_iter, boundary)

接受范围迭代器的迭代器,并生成一个 multipart/byteranges MIME 文档,该文档适合作为多范围 206 响应体的发送。

有关参数说明,请参阅 document_iters_to_http_response_body。

swift.common.utils.drain_and_close(response_or_app_iter, read_limit=None)

排空并关闭 swob 或 WSGI 响应。

这可以防止我们在代理服务器中因简单地忽略错误响应体而记录 499 错误。

swift.common.utils.drop_privileges(user)

设置当前进程的用户 ID/组 ID,获取会话 leader 等。

参数:

user – 要更改为的用户名称

swift.common.utils.dump_recon_cache(cache_dict, cache_file, logger, lock_timeout=2, set_owner=None)

更新 recon 缓存值

参数:
  • cache_dict – 要写入的缓存键/值对字典

  • cache_file – 要更新的缓存文件

  • logger – 用于记录遇到的错误的日志记录器

  • lock_timeout – 超时(以秒为单位)

  • set_owner – 设置 recon 缓存文件的所有者

swift.common.utils.eventlet_monkey_patch()

安装适当的 Eventlet monkey patches。

swift.common.utils.extract_swift_bytes(content_type)
解析 content-type 并返回一个元组,其中包含
  • 不包含 swift_bytes 参数的 content_type 字符串,

  • swift_bytes 值,如果未找到参数,则为 None

参数:

content_type – content-type 字符串

返回值:

一个元组 (content-type, swift_bytes 或 None)

swift.common.utils.fallocate(fd, size, offset=0)

为文件预分配磁盘空间。

可以通过调用 disable_fallocate() 来禁用此函数。如果 libc 中没有合适的 C 函数可用,此函数将无效。

参数:
  • fd – file descriptor

  • size – 分配大小(以字节为单位)

swift.common.utils.fdatasync(fd)

将修改后的文件数据同步到磁盘。

参数:

fd – file descriptor

swift.common.utils.filter_namespaces(namespaces, includes, marker, end_marker)

过滤给定的 Namespaces/ShardRanges,只保留其命名空间包含 includes 名称或 markerend_marker 之间的命名空间任何部分的 Namespace。如果未指定 includesmarkerend_marker 中的任何一个,则将返回所有 Namespace。

参数:
  • namespacesNamespaceShardRange 的列表。

  • includes – 字符串;如果非空,则仅返回其命名空间包含此字符串的 Namespace(如果存在),并将忽略 markerend_marker

  • marker – 如果指定,则仅返回其上界大于此值的 shard ranges。

  • end_marker – 如果指定,则仅返回其下界小于此值的 shard ranges。

返回值:

已过滤的 Namespace 列表。

swift.common.utils.find_namespace(item, namespaces)

在给定的 namespaces 列表中查找一个 Namespace/ShardRange,其命名空间包含 item

参数:
  • item – 要查找 Namespace 的项。

  • ranges – 已排序的 Namespace 列表。

返回值:

其命名空间包含 item 的 Namespace/ShardRange,如果未找到合适的 Namespace,则为 None。

swift.common.utils.friendly_close(resp)

关闭 swob 或 WSGI 响应并可能排空它。

“读取”HEAD 或 HTTPException 响应基本上是免费的——字节很可能已经在我们的网络缓冲区中。对于较大的响应,我们可能会消耗大量 CPU/网络资源来排空未使用的响应。此方法将读取最多 DEFAULT_DRAIN_LIMIT 字节,以避免在代理服务器中记录 499 错误(否则很容易丢弃小/空的响应体)。

swift.common.utils.fs_has_free_space(fs_path_or_fd, space_needed, is_percent)

检查文件系统是否具有给定数量的可用空间。与 fallocate() 不同,此函数不预留任何空间。

参数:
  • fs_path_or_fd – 文件系统上的文件或目录的路径,或已打开的文件描述符;如果是目录,则通常是挂载点的路径

  • space_needed – 最小字节数或可用空间百分比

  • is_percent – 如果为 True,则 space_needed 被视为文件系统容量的百分比;如果为 False,则 space_needed 是可用字节数。

返回值:

如果文件系统至少有这么多可用空间,则为 True,否则为 False

引发:

OSError – 如果 fs_path 不存在

swift.common.utils.fsync(fd)

将修改后的文件数据和元数据同步到磁盘。

参数:

fd – file descriptor

swift.common.utils.fsync_dir(dirpath)

将目录条目同步到磁盘。

参数:

dirpath – 要同步的目录的路径。

swift.common.utils.get_db_files(db_path)

给定一个 db 文件的路径,返回该路径所在目录中实际存在的所有有效 db 文件的排序列表。有效 db 文件名的格式为

<hash>[_<epoch>].db

其中 <hash> 与给定的 db_path 的 <hash> 部分匹配,就像通过 parse_db_filename() 解析一样。

参数:

db_path – 一个不一定存在的 db 文件的路径。

返回值:

db_path 所在目录中存在的有效 db 文件的列表。此列表可能为空。

swift.common.utils.get_hub()

检查 poll 是否可用,如果不可用则回退到 select。

关于 epoll 的注意事项

审查:https://review.opendev.org/#/c/18806/

曾经出现过这样一个问题:每 30 万亿连接中就有一次,一个协程在客户端关闭其端点时不会唤醒。Epoll 没有报告事件,或者事件在某个地方被吞噬了。然后当该文件描述符被重用时,eventlet 会发疯,因为它仍然认为它在另一个协程中等待该文件描述符的活动。

另一条关于 epoll 的注意事项:在 fork 时使用它很困难。epoll 的工作方式如下:

  • 创建 epoll 实例:efd = epoll_create(...)

  • 使用 epoll_ctl(efd, EPOLL_CTL_ADD, fd, ...) 注册感兴趣的文件描述符

  • 使用 epoll_wait(efd, ...) 等待事件

如果你 fork,你和你所有的子进程都会使用同一个 epoll 实例,并且每个人都会感到困惑。只要做正确的事情,就可以使用 epoll 和 fork 并且仍然有一个正确的程序,但 eventlet 没有做那些事情。事实上,它甚至无法尝试做那些事情,因为它没有得到 fork 的通知。

相比之下,poll() 和 select() 都在每次调用时指定感兴趣的文件描述符集,因此 fork 没有问题。

由于 eventlet monkey patching 现在在 wsgi.py 中的 get_hub() 调用之前完成,如果我们使用 'import select',我们会得到 eventlet 版本,但从 0.20.0 版本开始,eventlet 在补丁 select 中删除了 select.poll() 函数(参见:http://eventlet.net/doc/changelog.htmlhttps://github.com/eventlet/eventlet/commit/614a20462)。

我们使用 eventlet.patcher.original 函数来获取 Python select 模块,以测试平台上是否提供了 poll()。

swift.common.utils.get_logger(conf, name=None, log_to_console=False, log_route=None, fmt='%(server)s: %(message)s', statsd_tail_prefix=None)
返回一个 SwiftLogAdapter,该适配器已打补丁以提供一个

接口到 StatsdClient

参数:
  • conf – Configuration dict to read settings from

  • name – 此值用于填充日志格式中的 server 字段,作为 statsd 消息的前缀,以及作为 log_route 的默认值;默认为 conf 中的 log_name 值(如果存在),或者为 ‘swift’。

  • log_to_console – 添加写入 stderr 控制台的处理程序。

  • log_route – 日志记录的路由,不输出到日志,仅用于分隔日志配置;默认为 name 的值或 name 默认值。此值用作返回的 SwiftLogAdapter 的 name 属性。

  • fmt – 覆盖日志格式。

  • statsd_tail_prefix – 传递给 StatsdClient 的尾部前缀;如果为 None,则尾部前缀默认为 name 的值。

返回值:

SwiftLogAdapter 的实例。

swift.common.utils.get_partition_for_hash(hex_hash, part_power)

返回给定十六进制哈希和分区幂的分区号。:param hex_hash: 哈希字符串 :param part_power: 分区幂 :returns: 分区号

swift.common.utils.get_partition_from_path(devices, path)
参数:
  • devices – 设备挂载的目录(例如 /srv/node)

  • path – 对象文件或哈希目录的完整路径

返回值:

来自路径的(整数)分区

swift.common.utils.get_pid_notify_socket(pid=None)

获取一个 pid 特定的抽象通知套接字。

这由 swift-reload 命令使用。

swift.common.utils.get_ppid(pid)

给定子进程的 PID,获取其父进程的 PID。

引发:

OSError – 如果找不到子进程 PID

swift.common.utils.get_prefixed_logger(swift_logger, prefix)

返回给定 swift_logger 的克隆,并带有新的前缀字符串,该字符串替换给定 swift_logger 的前缀字符串。

如果给定的 swift_logger 已打补丁并包含一个 StatsdClient 实例的接口,则返回的 SwiftLogAdapter 也将包含相同 StatsdClient 实例的接口。

参数:
  • swift_logger – an instance of SwiftLogAdapter.

  • prefix – a string prefix.

返回值:

a new instance of SwiftLogAdapter.

swift.common.utils.get_redirect_data(response)

从响应的头部提取重定向位置。

参数:

response – 一个响应

返回值:

如果找到 Location 报头,则返回 (path, Timestamp) 的元组,否则返回 None

引发:

ValueError – 如果找到 Location 报头但未找到 X-Backend-Redirect-Timestamp,或者这两个报头的格式存在问题

swift.common.utils.get_time_units(time_amount)

获取归一化后的时间长度,以最大时间单位(小时、分钟或秒)表示。

参数:

time_amount – 时间长度(以秒为单位)

返回值:

一个元组 (时间长度, 时间单位),其中时间单位是 ('h', 'm', 's') 之一

swift.common.utils.get_zero_indexed_base_string(base, index)

这允许调用者创建一个带有索引的项目列表,其中第一个项(零索引)是原始的基本字符串,后续索引依次追加 '-1', '-2' 等。

例如:

'lock', None => 'lock'
'lock', 0    => 'lock'
'lock', 1    => 'lock-1'
'object', 2  => 'object-2'
参数:
  • base – 一个字符串,基本字符串;当 index 为 0(或 None)时,这是恒等函数。

  • index – 一个数字,通常是整数(或 None);对于 0 或 None 以外的值,此数字将用连字符分隔并附加到基本字符串。

swift.common.utils.hash_path(account, container=None, object=None, raw_digest=False)

获取账户/容器/对象的规范哈希值

参数:
  • account – 账户

  • container – 容器

  • object – 对象

  • raw_digest – 如果为 True,则返回原始版本而不是十六进制摘要

返回值:

哈希字符串

swift.common.utils.human_readable(value)

以人类可读的格式返回数值;例如 1048576 = “1Mi”。

swift.common.utils.is_file_older(path, age)

测试文件 mtime 是否比给定年龄旧,并抑制任何 OSErrors。

参数:
  • path – 传递给 os.stat 的第一个也是唯一一个参数

  • age – 年龄(以秒为单位)

返回值:

如果 age 小于或等于零,或者文件 mtime 在过去的时间超过 age,则为 True;如果 age 大于零,并且文件 mtime 在过去的时间小于或等于 age,或者在 stat 文件时出现 OSError,则为 False。

swift.common.utils.ismount(path)

测试路径是否为挂载点。这将捕获所有异常并将其转换为 False 返回值。使用 ismount_raw 来代替引发异常。

swift.common.utils.ismount_raw(path)

测试路径是否为挂载点。ismount 会捕获所有异常并仅返回 False,而此原始版本不会捕获异常。

这是从 C Python 2.6.8 复制的代码,已修改以移除额外的 lstat() 系统调用。

swift.common.utils.item_from_env(env, item_name, allow_none=False)

从 wsgi 环境中获取一个值

参数:
  • env – wsgi 环境字典

  • item_name – 要获取的项的名称

返回值:

来自环境的值

swift.common.utils.iter_multipart_mime_documents(wsgi_input, boundary, read_chunk_size=4096)

给定一个 multipart-mime 编码的输入文件对象和边界,为每个部分生成文件类对象。请注意,这不会将每个部分拆分为头部和正文;如果需要,调用者负责执行此操作。

参数:
  • wsgi_input – 要从中读取的文件类对象。

  • boundary – 用于分隔新文件类对象的 mime 边界。

返回值:

每个部分的生成器文件类对象。

引发:

MimeInvalid – 如果文档格式错误

创建到文件描述符在 target_path 指定的链接。此方法不会为您关闭 fd。与 rename 不同,由于 linkat() 无法覆盖存在的 target_path,我们会先取消链接然后重试。

尝试通过重试来修复/隐藏类似空对象目录在上传过程中被后端进程删除的竞态条件。

参数:
  • fd – 要链接的文件描述符

  • target_path – 文件系统中要链接 fd 的路径

  • dirs_created – 需要 fsync 的新创建目录的数量。

  • retries – 重试次数

  • fsync – 对 target_path 的包含目录以及所有新创建的目录进行 fsync。

swift.common.utils.list_from_csv(comma_separated_str)

分割给定的字符串并返回一个已正确去除空格的逗号分隔值列表。

swift.common.utils.load_multikey_opts(conf, prefix, allow_none_key=False)

读取形式为“<prefix>_<key> = <value>”的多键选项

参数:
  • conf – 一个配置字典

  • prefix – 要搜索的前缀

  • allow_none_key – 如果为 True,还会解析“<prefix> = <value>”,并将其作为 (None, value) 包含在结果中

返回值:

一个已排序的 (<key>, <value>) 元组列表

引发:

ValueError – 如果选项以 prefix 开头但无法解析

swift.common.utils.load_recon_cache(cache_file)

加载一个 recon 缓存文件。将丢失的文件视为空的。

swift.common.utils.lock_file(filename, timeout=None, append=False, unlink=True)

上下文管理器,用于获取文件锁。这将一直阻塞直到可以获取锁,或者超时时间到期(以先发生的为准)。

参数:
  • filename – 要锁定的文件

  • timeout – 超时时间(秒)。如果为 None,则默认为 DEFAULT_LOCK_TIMEOUT

  • append – 如果文件应以追加模式打开,则为 True

  • unlink – 如果文件应在结束时取消链接,则为 True

swift.common.utils.lock_parent_directory(filename, timeout=None)

上下文管理器,用于获取给定文件路径的父目录锁。这将一直阻塞直到可以获取锁,或者超时时间到期(以先发生的为准)。

参数:
  • filename – 要锁定的父目录的文件路径

  • timeout – 超时时间(秒)。如果为 None,则默认为 DEFAULT_LOCK_TIMEOUT

swift.common.utils.lock_path(directory, timeout=None, timeout_class=None, limit=1, name=None)

上下文管理器,用于获取目录锁。这将一直阻塞直到可以获取锁,或者超时时间到期(以先发生的为准)。

要进行独占锁定,文件或目录必须以写入模式打开。Python 不允许目录以写入模式打开。因此,我们通过锁定目录中的隐藏文件来解决这个问题。

参数:
  • directory – 要锁定的目录

  • timeout – 超时时间(秒)。如果为 None,则默认为 DEFAULT_LOCK_TIMEOUT

  • timeout_class – 如果在超时时间内无法授予锁,则引发异常的类。将实例化为 timeout_class(timeout, lockpath)。默认值:LockTimeout

  • limit – 在调用此方法时,可以对同一目录并发持有的最大锁数。请注意,此限制仅在当前调用此方法时应用,并不阻止后续调用提供更大的限制。默认为 1。

  • name – 用于区分目录中不同类型锁的字符串

引发:
  • TypeError – 如果 limit 不是整数。

  • ValueError – 如果 limit 小于 1。

swift.common.utils.make_db_file_path(db_path, epoch)

给定数据库文件的路径,返回一个修改后的路径,其文件名部分带有给定的 epoch。

数据库文件名形式为 <hash>[_<epoch>].db;此方法将给定的 db_path<epoch> 部分替换为给定的 epoch 值,或者在给定的 epochNone 时删除 epoch 部分。

参数:
  • db_path – 一个不一定存在的 db 文件的路径。

  • epoch – 一个字符串(或 None),将用作新路径文件名中的 epoch;非 None 的值将被标准化为 Timestamp 的普通字符串表示。

返回值:

修改后的数据库文件路径。

引发:

ValueError – 如果 epoch 对于构造 Timestamp 无效。

swift.common.utils.makedirs_count(path, count=0)

与 os.makedirs() 相同,但此方法返回必须创建的新目录的数量。

此外,如果目标目录已存在,此方法不会引发错误。此行为类似于 Python 3.x 的 os.makedirs() 调用 exist_ok=True。也类似于 swift.common.utils.mkdirs()

https://hg.python.org/cpython/file/v3.4.2/Lib/os.py#l212

swift.common.utils.maybe_multipart_byteranges_to_document_iters(app_iter, content_type)

接受一个可能包含 multipart MIME 文档的迭代器以及内容类型,并返回一个 body 迭代器的迭代器。

参数:
  • app_iter – 可能包含 multipart MIME 文档的迭代器

  • content_type – app_iter 的内容类型,用于确定它是否包含 multipart 文档,如果是,则文档之间的边界是什么

swift.common.utils.md5_hash_for_file(fname)

获取文件的 MD5 校验和。

参数:

fname – 文件路径

返回值:

MD5 校验和,十六进制编码

swift.common.utils.memcached_timing_stats(**dec_kwargs)

返回一个装饰器,用于记录 MemcacheRing 类中公共方法的计时事件或错误,例如 memcached set、get 等。

swift.common.utils.mime_to_document_iters(input_file, boundary, read_chunk_size=4096)

接受一个包含 multipart MIME 文档的文件类对象,并返回一个 (headers, body-file) 元组的迭代器。

参数:
  • input_file – 包含 MIME 文档的文件类对象

  • boundary – MIME 边界,不带连字符(例如,“divider”,而不是“–divider”)

  • read_chunk_size – 通过 input_file.read() 读取的字符串大小

swift.common.utils.mkdirs(path)

确保路径是目录,如果不是则创建。如果路径存在但为文件或权限失败,则引发错误。

参数:

path – 要创建的路径

swift.common.utils.monkey_patch()

在一个地方一致地应用所有 swift monkey patching。

swift.common.utils.multipart_byteranges_to_document_iters(input_file, boundary, read_chunk_size=4096)

接受一个包含 multipart/byteranges MIME 文档(参见 RFC 7233,附录 A)的文件类对象,并返回一个 (first-byte, last-byte, length, document-headers, body-file) 5 元组的迭代器。

参数:
  • input_file – 包含 MIME 文档的文件类对象

  • boundary – MIME 边界,不带连字符(例如,“divider”,而不是“–divider”)

  • read_chunk_size – 通过 input_file.read() 读取的字符串大小

swift.common.utils.node_to_string(node_dict, replication=False)

获取节点位置的字符串表示。

参数:
  • node_dict – 描述节点的字典

  • replication – 如果为 True,则使用复制 IP 地址和端口,否则使用普通 IP 地址和端口。

返回值:

形式为 <ip address>:<port>/<device> 的字符串

swift.common.utils.override_bytes_from_content_type(listing_dict, logger=None)

接受来自容器列表的字典,如果设置了 swift_bytes,则覆盖 content_type 和 bytes 字段。

swift.common.utils.pairs(item_list)

返回 item_list 中所有元素对的迭代器。

参数:

item_list – 项(不允许重复)

swift.common.utils.parse_content_disposition(header)

给定类似 Content-Disposition: form-data; name=”somefile”; filename=”test.html” 的头部值

返回类似 (“form-data”, {“name”: “somefile”, “filename”: “test.html”}) 的数据

参数:

header – 头部的值(“: “之后的部分)。

返回值:

解析后的属性数据的(值名称,字典)(见上文)。

swift.common.utils.parse_content_range(content_range)

将 content-range 头部解析为 (first_byte, last_byte, total_size)。

有关头部格式的详细信息,请参见 RFC 7233 第 4.2 节,但它基本上是“Content-Range: bytes ${start}-${end}/${total}”。

参数:

content_range – 要解析的 Content-Range 头部值,例如“bytes 100-1249/49004”

返回值:

3 元组(start, end, total)

引发:

ValueError – 如果格式错误

swift.common.utils.parse_content_type(content_type, strict=True)

解析 content-type 及其参数为值。RFC 2616 第 14.17 和 3.7 节是相关的。

示例:

'text/plain; charset=UTF-8' -> ('text/plain', [('charset, 'UTF-8')])
'text/plain; charset=UTF-8; level=1' ->
    ('text/plain', [('charset, 'UTF-8'), ('level', '1')])
参数:
  • content_type – 要解析的 content_type

  • strict – 忽略参数令牌中的 / 和任何后续字符。如果 strict 为 True,则参数如 x=a/b 将被解析为 x=a。如果 strict 为 False,则参数如 x=a/b 将被解析为 x=a/b。默认为 True。

返回值:

包含(内容类型,k, v 参数元组列表)的元组

swift.common.utils.parse_db_filename(filename)

将数据库文件名分割为三部分:hash、epoch 和 extension。

>>> parse_db_filename("ab2134.db")
('ab2134', None, '.db')
>>> parse_db_filename("ab2134_1234567890.12345.db")
('ab2134', '1234567890.12345', '.db')
参数:

filename – 数据库文件的基本名称或数据库文件的路径。

返回值:

一个 (hash, epoch, extension) 元组。epoch 可能是 None。

引发:

ValueError – 如果 filename 不是文件路径。

swift.common.utils.parse_header(value)

解析头部值以提取第一部分和任何后续参数的字典。

要解析的 value 应为以下形式:

<first part>[;<key>=<value>][; <key>=<value>]...

<first part> 应为 <token>[/<token>] 的形式,<key> 应为 token,而 <value> 应为 tokenquoted-string,其中 tokenquoted-string 由 RFC 2616 第 2.2 节定义。

参数:

value – 要解析的头部值。

返回值:

一个元组(第一部分,dict(params))。

swift.common.utils.parse_mime_headers(doc_file)

接受一个包含 MIME 文档的文件类对象,并返回一个包含头部的 HeaderKeyDict。消息的正文不会被消耗:doc_file 中的位置保留在正文的开头。

此函数受到 Python 标准库 http.client.parse_headers 的启发。

参数:

doc_file – 包含 MIME 文档的二进制文件类对象

返回值:

一个包含头部的 swift.common.swob.HeaderKeyDict

swift.common.utils.parse_options(parser=None, once=False, test_config=False, test_args=None)

使用 optparse.OptionParser 解析标准的 swift 服务器/守护进程选项。

参数:
  • parser – 要使用的 OptionParser。如果未发送,将创建一个。

  • once – 布尔值,指示“once”选项是否可用

  • test_config – 布尔值,指示“test-config”选项是否可用

  • test_args – 覆盖 sys.argv;用于测试

返回值:

元组(config, options);config 是配置文件的绝对路径,options 是解析器选项(字典形式)。

引发:

SystemExit – 第一个参数(CONFIG)是必需的,文件必须存在

swift.common.utils.parse_override_options(**kwargs)

根据 kwargs 确定我们应该操作哪些策略、设备和分区。

如果 kwargs 中已存在“override_policies”,则返回该值。当使用多个工作进程时会发生这种情况;父进程将 override_policies=X 提供给每个子进程。

否则,在 run-once 模式下,查看“policies”关键字参数。这是“–policies”命令行选项的值。在 run-forever 模式下或未提供 –policies 选项时,将返回一个空列表。

设备和分区的处理方式类似。

返回值:

一个具有“devices”、“partitions”和“policies”字段的命名元组。

swift.common.utils.private(func)

装饰器,用于声明哪些方法可以通过带有 X-Backend-Allow-Private-Methods: True 覆盖的 HTTP 请求私有访问

参数:

func – 要设为私有的函数

swift.common.utils.public(func)

装饰器,用于声明哪些方法可以作为 HTTP 请求公开访问

参数:

func – function to make public

swift.common.utils.punch_hole(fd, offset, length)

取消文件中间的磁盘空间分配。

参数:
  • fd – file descriptor

  • offset – 要取消分配的第一个字节的索引

  • length – 要取消分配的字节数

swift.common.utils.put_recon_cache_entry(cache_entry, key, item)

更新一个 recon 缓存条目项。

如果 item 是一个空字典,则 cache_entry 中任何现有的 key 都将被删除。同样,如果 item 是一个字典,并且其任何值是空字典,则相应的 key 将从 cache_entry 的嵌套字典中删除。

当对象审计员并行运行时,或者在“once”模式下使用指定的设备子集运行时,我们使用嵌套的 recon 缓存条目。

参数:
  • cache_entry – 一个现有缓存条目的字典

  • key – 要更新的项的键

  • item – 要更新的项的值

swift.common.utils.quorum_size(n)

适用于使用“复制”来保证数据完整性的服务(账户/容器服务)的法定人数大小。对象的 quorum_size 是根据存储策略定义的。

代理认为客户端请求成功的所需成功后端请求数。

swift.common.utils.ratelimit_sleep(running_time, max_rate, incr_by=1, rate_buffer=5)

将 eventlet.sleep() 适当的时间,以便永远不会超过 max_rate。如果 max_rate 为 0,则不进行速率限制。建议的最大速率不应超过每秒(1000 * incr_by),因为 eventlet.sleep() 涉及一些开销。返回 running_time,它应该用于后续调用。

参数:
  • running_time – 下一个允许的请求的运行时间(毫秒)。最好从零开始。

  • max_rate – 进程允许的最大每秒速率。

  • incr_by – 增加计数器的量。如果您想限制 1024 字节/秒的速率并且请求大小不同,则很有用。必须大于 0 才能启用速率限制行为。

  • rate_buffer – 速率计数器可以下降并被允许追赶(以比列出的速率更快)的秒数。更大的数字将导致更大的速率峰值,但平均准确性更好。必须大于 0 才能启用速率限制行为。

返回值:

下一个间隔的绝对时间(毫秒);请注意,时间可能已经远远超过该点,但下一次调用将捕获这一点并跳过 sleep。

swift.common.utils.reiterate(iterable)

消耗迭代器中的第一个真值项,然后将其重新链接到迭代器的其余部分。当您想确保下游生成器的序言在继续之前已执行时,此方法很有用。:param iterable: 可迭代对象

swift.common.utils.remove_directory(path)

os.rmdir 的包装器,忽略 ENOENT 和 ENOTEMPTY

参数:

path – 传递给 os.rmdir 的第一个且唯一的参数

swift.common.utils.remove_file(path)

os.unlink 的静默包装器,会抑制 OSError

参数:

path – 传递给 os.unlink 的第一个且唯一的参数

swift.common.utils.renamer(old, new, fsync=True)

尝试通过重试来修复/隐藏类似空对象目录在上传过程中被后端进程删除的竞态条件。

默认情况下,“new”的包含目录和所有新创建的目录都会被 fsync。这会带来性能损失。在不需要这些额外 fsync 的情况下,期望 renamer() 的调用者显式将其关闭。

参数:
  • old – 要重命名的旧路径

  • new – 要重命名为的新路径

  • fsync – 对 new 的包含目录以及所有新创建的目录进行 fsync。

swift.common.utils.replace_partition_in_path(devices, path, part_power)

接受一个路径和一个分区幂,并返回相同的路径,但具有正确的分区号。在增加分区幂时最有用。

参数:
  • devices – 设备挂载的目录(例如 /srv/node)

  • path – 对象文件或哈希目录的完整路径

  • part_power – 用于计算正确分区号的分区幂

返回值:

具有重新计算的分区幂的路径

swift.common.utils.replication(func)

装饰器,用于声明哪些方法可以被不同类型的服务器访问

  • 如果 replication_server 选项为 None,则此装饰器无关紧要。

  • 如果 replication_server 选项为 True,则仅启动带有此装饰器的decorated 方法。

  • 如果 replication_server 选项为 False,则带有此装饰器的decorated 方法将不会启动。

参数:

func – 标记为可复制访问的函数

swift.common.utils.round_robin_iter(its)

接受一个迭代器列表,以轮循方式从中生成一个元素,直到所有迭代器都耗尽。:param its: 迭代器列表

swift.common.utils.rsync_ip(ip)

将 ip 字符串转换为 rsync 兼容的格式

将保持 ipv4 地址不变,但会将 ipv6 地址嵌套在方括号内。

参数:

ip – 一个 ip 字符串(ipv4 或 ipv6)

返回值:

一个字符串 ip 地址

swift.common.utils.rsync_module_interpolation(template, device)

在 rsync 模块模板中插值设备变量

参数:
  • template – rsync 模块模板(字符串形式)

  • device – 来自 ring 的设备

返回值:

一个字符串,其中所有变量都替换为设备属性

swift.common.utils.search_tree(root, glob_match, ext='', exts=None, dir_ext=None)

在 root 中搜索,查找匹配 glob 的任何文件/目录,递归遍历找到的目录,查找以 ext 结尾的文件

参数:
  • root – 搜索路径的起点

  • glob_match – 要在 root 中匹配的 glob,匹配的目录将使用 os.walk 进行遍历

  • ext – 只有以 ext 结尾的文件才会被返回

  • exts – 一个文件扩展名列表;只有以这些扩展名之一结尾的文件才会被返回;如果设置,此列表将覆盖使用“ext”参数指定的任何扩展名。

  • dir_ext – 如果存在,以 dir_ext 结尾的目录将不会被遍历,而是作为匹配的路径返回

返回值:

已排序的匹配文件完整路径列表。

swift.common.utils.select_ip_port(node_dict, use_replication=False)

获取应为给定的 node_dict 使用的 IP 地址和端口。

如果 use_replication 为 True,则返回复制 IP 地址和端口。

如果 use_replication 为 False(默认值)并且 node 字典有一个键为 use_replication 的项,则该项的值将决定是否返回复制 IP 地址和端口。

如果 use_replicationnode_dict['use_replication'] 均未指示其他选项,则返回普通的 IP 地址和端口。

参数:
  • node_dict – 描述节点的字典

  • use_replication – 如果为 True,则返回复制 IP 地址和端口。

返回值:

(IP 地址, 端口) 的元组

swift.common.utils.set_swift_dir(swift_dir)

设置将读取 swift 配置文件所在的目录。如果给定的目录与已设置的目录不同,则将验证新目录中的 swift.conf 文件,并从新 swift.conf 文件重新加载存储策略。

参数:

swift_dir – 用于从其中读取 swift.conf 的非默认目录

swift.common.utils.storage_directory(datadir, partition, name_hash)

获取存储目录

参数:
  • datadir – 基本数据目录

  • partition – 分区

  • name_hash – 账户、容器或对象名称哈希

返回值:

存储目录

swift.common.utils.streq_const_time(s1, s2)

恒定时间字符串比较。

参数 s1:

第一个字符串

参数 s2:

第二个字符串

返回值:

如果字符串相等,则返回 True。

此函数接受两个字符串并进行比较。它旨在用于身份验证目的的比较,以帮助防御定时攻击。

swift.common.utils.strict_b64decode(value, allow_line_breaks=False, exact_size=None)

验证并解码 Base64 编码的数据。

标准库的 base64 模块会默默地丢弃无效字符,但我们通常希望将它们视为错误。

参数:
  • value – 一些 base64 编码的数据

  • allow_line_breaks – 如果为 True,则忽略回车符和换行符

  • exact_size – 如果提供,则为预期的已解码字节的确切大小;还强制执行往返检查

返回值:

已解码的数据

引发:

ValueError – 如果 value 不是字符串,包含无效字符,或填充不足

swift.common.utils.systemd_notify(logger=None, msg=b'READY=1')

发送 systemd 兼容的通知。

尝试将消息发送到 swift 的特定于 pid 的通知套接字;请参阅 get_pid_notify_socket()。这由 swift-reload 命令使用。

此外,如果通知了启动该进程的服务管理器,并且该管理器已设置 NOTIFY_SOCKET 环境变量。例如,systemd 在单元具有 Type=notify 时会设置它。有关更多信息,请参见 systemd 文档:https://www.freedesktop.org/software/systemd/man/sd_notify.html

常见消息包括

READY=1
RELOADING=1
STOPPING=1
参数:
  • logger – 一个日志记录器对象

  • msg – 要发送的消息

删除给定路径中所有最后修改时间早于 mtime 的文件。

参数:
  • path – 要从中删除文件的路径

  • mtime – 要保留的最旧文件的最后修改时间戳

删除列表中所有最后修改时间早于 mtime 的文件。

参数:
  • filepaths – 一个字符串列表,是要检查的文件的完整路径

  • mtime – 要保留的最旧文件的最后修改时间戳

swift.common.utils.validate_device_partition(device, partition)

验证设备和分区是否有效,并且在启用时不会导致目录遍历。

参数:
  • device – 要验证的设备

  • partition – 要验证的分区

引发:

ValueError – 如果给出无效的设备或分区

swift.common.utils.validate_sync_to(value, allowed_sync_hosts, realms_conf)

验证 X-Container-Sync-To 头部值,返回已验证的端点、领域和 realm_key,或错误字符串。

参数:
  • value – 要验证的 X-Container-Sync-To 头部值。

  • allowed_sync_hosts – 如果 realms_conf 不适用,则允许的端点主机列表。

  • realms_conf – swift.common.container_sync_realms.ContainerSyncRealms 的实例,用于验证。

返回值:

一个 (error_string, validated_endpoint, realm, realm_key) 元组。如果其余值已验证,则 error_string 为 None。validated_endpoint 是要同步到的已验证端点。如果通过 realms_conf 进行验证,则将设置 realm 和 realm_key。

swift.common.utils.write_file(path, contents)

将内容写入 path 的文件

参数:
  • path – 任何路径,根据需要会创建子目录

  • contents – 要写入文件的数据,将被转换为字符串

swift.common.utils.write_pickle(obj, dest, tmp=None, pickle_protocol=0)

确保 pickle 文件被写入磁盘。文件首先写入临时位置,确保它已同步到磁盘,然后移动到其最终位置

参数:
  • obj – 要 pickle 的 python 对象

  • dest – 最终目标文件的路径

  • tmp – 要使用的临时文件路径,默认为 None

  • pickle_protocol – 用于 pickle obj 的协议,默认为 0

WSGI

用于 swift 的 WSGI 工具。

class swift.common.wsgi.ConfigDirLoader(conf_dir)

Bases: NamedConfigLoader

从给定路径下的多个文件读取配置。

exception swift.common.wsgi.ConfigFileError

基础: Exception

exception swift.common.wsgi.ConfigFilePortError

Bases: ConfigFileError

class swift.common.wsgi.ConfigString(config_string)

Bases: NamedConfigLoader

将原始配置字符串包装起来以供 paste.deploy 使用。

如果您将其中一个提供给我们的 loadcontext(例如,提供给我们的 appconfig),我们将截获它并将其路由到正确的加载器。

class swift.common.wsgi.NamedConfigLoader(filename)

Bases: ConfigLoader

修补 paste.deploy 的 ConfigLoader,以便每个上下文对象都知道它来自哪个配置节。

class swift.common.wsgi.PipelineWrapper(context)

基类: object

此类提供了一系列实用方法来修改 wsgi 管道的组成。

create_filter(entry_point_name)

创建一个过滤器上下文,该上下文随后可以添加到管道上下文中。

参数:

entry_point_name – 中间件的入口点(仅限 Swift)

返回值:

一个过滤器上下文

index(entry_point_name)

返回给定入口点名称在管道中的第一个索引。

如果给定的模块不在管道中,则引发 ValueError。

insert_filter(ctx, index=0)

将过滤器模块插入管道上下文中。

参数:
  • ctx – 要插入的上下文

  • index – (可选)应将过滤器插入管道过滤器列表中的索引。默认为 0,表示管道的开头。

startswith(entry_point_name)

测试管道是否以给定的入口点名称开头。

参数:

entry_point_name – 中间件或应用程序的入口点(仅限 Swift)

返回值:

如果 entry_point_name 是管道中的第一个,则为 True,否则为 False

class swift.common.wsgi.RestrictedGreenPool(size=1024)

Bases: GreenPool

工作方式与 GreenPool 相同,但如果 size 指定为一,则 spawn_n() 方法将在返回前调用 waitall() 以防止调用者执行任何其他工作(例如调用 accept())。

spawn_n(*args, **kwargs)

创建一个 greenthread 来运行 *function*,与 spawn() 相同。不同之处在于 spawn_n() 返回 None;*function* 的结果无法检索。

class swift.common.wsgi.ServersPerPortStrategy(conf, logger, servers_per_port)

Bases: StrategyBase

WSGI 服务器管理策略对象,用于对象服务器,每个存储策略环中的唯一本地端口都有一个监听端口。 servers_per_port 整数配置设置确定每个端口运行多少个工作进程。

跟踪数据是一个类似 port -> [(pid, socket), ...] 的映射。

用于 run_wsgi()

参数:
  • conf (dict) – 服务器配置字典。

  • logger – 服务器的 LogAdaptor 对象。

  • servers_per_port (int) – 每个端口要运行的工作进程数。

iter_sockets()

生成所有已知的监听套接字。

log_sock_exit(sock, data)

记录服务器退出。

loop_timeout()

在检查重新加载的 ring 之前的超时时间。

返回值:

等待子进程退出,然后检查重新加载的 ring(新端口)的时间。

new_worker_socks()

生成一系列 (socket, (port, server_idx)) 元组,用于每个应该被 fork 启动的服务器。

不再存在于任何 ring 中的“孤立”端口的所有套接字将在生成所有新套接字后关闭(导致其关联的工作进程正常退出)。

每个套接字的 server_idx 项将传递给 log_sock_exit()register_worker_start() 方法。

no_fork_sock()

此策略不支持在前台运行。

register_worker_exit(pid)

当工作进程退出时调用。

参数:

pid (int) – 退出的工作进程的 PID。

register_worker_start(sock, data, pid)

启动新工作进程时调用。

参数:
  • sock (socket) – 新启动的工作进程的监听套接字。

  • data (tuple) – 套接字的 (port, server_idx),由 new_worker_socks() 生成。

  • pid (int) – 新工作进程的 PID

class swift.common.wsgi.StrategyBase(conf, logger)

基类: object

所有策略类的一些通用操作。

post_fork_hook()

在每个 fork 出来的子进程中调用,在启动实际 wsgi 服务器之前,执行任何初始化,例如降级权限。

read_state_from_old_manager(worker_state_fd)

从旧管理器套接字关闭器读取工作进程状态。

套接字关闭过程是最后一个仍然持有工作进程 PID 的环节,因此它将一个 JSON 字典(以其长度为前缀)发送给我们,形式为

{
  "old_pids": {
    "<old worker>": "<first reload time>",
    ...
  }
}

将来可能会添加更多数据。

参数:

worker_state_fd – 应该包含旧工作进程状态的文件描述符。应通过 __SWIFT_SERVER_CHILD_STATE_FD 环境变量传递给我们。

set_close_on_exec_on_listen_sockets()

在任何监听套接字上设置 close-on-exec 标志。

shutdown_sockets()

关闭任何监听套接字。

signal_ready()

信号表示服务器已启动并接受连接。

class swift.common.wsgi.WSGIContext(wsgi_app)

基类: object

此类提供了一种为中间件过滤器提供上下文(范围)的方式,以便能够访问 wsgi start_response 结果,例如请求状态和头部。

class swift.common.wsgi.WorkersStrategy(conf, logger)

Bases: StrategyBase

WSGI 服务器管理策略对象,用于单个绑定端口和监听套接字,由配置数量的工作进程共享。

跟踪数据是 pid -> socket 的映射。

用于 run_wsgi()

参数:
  • conf (dict) – 服务器配置字典。

  • logger – 服务器的 LogAdaptor 对象。

iter_sockets()

生成所有已知的监听套接字。

log_sock_exit(sock, _unused)

记录服务器退出。

参数:
  • sock (socket) – 新启动的工作进程的监听套接字。

  • _unused – 由 new_worker_socks() 生成的套接字的 opaque_data。

loop_timeout()

我们希望避免忙等待,但我们也需要一个非 None 值,以便主循环有机会判断是否应该继续运行(例如,收到 SIGHUP)。

因此,我们返回 0.5。

new_worker_socks()

生成一个 (socket, opqaue_data) 元组序列,用于每个应该被 fork 启动的服务器。

每个套接字的 opaque_data 项将传递给 log_sock_exit()register_worker_start() 方法,其中将被忽略。

no_fork_sock()

如果服务器应在前台运行(不 fork),则返回一个服务器监听套接字。

register_worker_exit(pid)

当工作进程退出时调用。

注意:重新执行的服务器可以从正在被替换的旧服务器进程中回收死掉的工作进程 PID,作为服务重新加载(SIGUSR1)的一部分。所以我们需要对收到未知 PID 具有健壮性。

参数:

pid (int) – 退出的工作进程的 PID。

register_worker_start(sock, _unused, pid)

启动新工作进程时调用。

参数:
  • sock (socket) – 新启动的工作进程的监听套接字。

  • _unused – 由 new_worker_socks() 生成的套接字的 opaque_data。

  • pid (int) – 新工作进程的 PID

swift.common.wsgi.get_socket(conf)

将套接字绑定到 conf 中的 bind ip:port

参数:

conf – Configuration dict to read settings from

返回值:

一个套接字对象,如 socket.listen 或 ssl.wrap_socket 返回(如果 conf 指定了 cert_file)

swift.common.wsgi.init_request_processor(conf_path, app_section, *args, **kwargs)

从 conf 加载通用设置 设置 logger 加载请求处理器

参数:
  • conf_path – paste.deploy 风格的配置文件/目录路径

  • app_section – conf 文件中用于加载配置的应用程序名称

返回值:

已加载的应用程序入口点

引发:

ConfigFileError – 配置文件错误时引发异常

swift.common.wsgi.load_app_config(conf_file)

从配置文件中读取应用程序配置节。

参数:

conf_file – 配置文件路径

返回值:

一个字典

swift.common.wsgi.loadapp(conf_file, global_conf=None, allow_modify_pipeline=True)

从配置文件加载上下文,如果上下文是管道,则允许应用程序修改管道。

参数:
  • conf_file – 配置文件路径

  • global_conf – 用于更新加载配置的选项字典。global_conf 中的选项将覆盖 conf_file 中的选项,除非 conf_file 中的选项前面有 set

  • allow_modify_pipeline – 如果为 True,并且上下文是管道,并且加载的应用程序具有 modify_wsgi_pipeline 属性,那么在加载管道之前将调用该属性。

返回值:

加载的应用程序

swift.common.wsgi.make_env(env, method=None, path=None, agent='Swift', query_string=None, swift_source=None)

返回一个新的、干净的 WSGI 环境。

参数:
  • env – 新环境的基础 WSGI 环境。

  • method – 新的 REQUEST_METHOD,如果为 None,则使用原始的。

  • path – 新的 path_info,如果为 None,则使用原始的。path 不应被转义。在构建 URL 时,Webob Request(根据 WSGI 规范)会转义 env[‘PATH_INFO’]。url += quote(environ[‘PATH_INFO’])

  • query_string – 新的 query_string,如果为 None,则使用原始的。在构建 URL 时,Webob Request 会直接将查询字符串附加到 URL 后面。url += ‘?’ + env[‘QUERY_STRING’]

  • agent – 要使用的 HTTP 用户代理;默认为 ‘Swift’。您可以在 agent 中放入 %(orig)s,它将被替换为原始 env 的 HTTP_USER_AGENT,例如 ‘%(orig)s StaticWeb’。您也可以将 agent 设置为 None 来使用原始 env 的 HTTP_USER_AGENT,或者设置为 ‘’ 以不使用 HTTP_USER_AGENT。

  • swift_source – 用于将请求标记为源自中间件。将在代理日志中记录。

返回值:

新的 WSGI 环境。

swift.common.wsgi.make_pre_authed_env(env, method=None, path=None, agent='Swift', query_string=None, swift_source=None)

make_env() 相同,但增加了预授权。

swift.common.wsgi.make_pre_authed_request(env, method=None, path=None, body=None, headers=None, agent='Swift', swift_source=None)

make_subrequest() 相同,但增加了预授权。

swift.common.wsgi.make_subrequest(env, method=None, path=None, body=None, headers=None, agent='Swift', swift_source=None, make_env=<function make_env>)

基于当前环境创建一个新的 swob.Request,并使用指定的参数。

参数:
  • env – 新请求的基础 WSGI 环境。

  • method – 新请求的 HTTP 方法;默认为原始环境中的方法。

  • path – 新请求的 HTTP 路径;默认为原始环境中的路径。path 应与您发送到 Request.blank 的内容兼容。path 应被转义,并且可以包含查询字符串。例如:‘/a%20space?unicode_str%E8%AA%9E=y%20es’

  • body – 新请求的 HTTP 主体;默认为空。

  • headers – 新请求的额外 HTTP 头部;默认为 None。

  • agent – 要使用的 HTTP 用户代理;默认为 ‘Swift’。您可以在 agent 中放入 %(orig)s,它将被替换为原始 env 的 HTTP_USER_AGENT,例如 ‘%(orig)s StaticWeb’。您也可以将 agent 设置为 None 来使用原始 env 的 HTTP_USER_AGENT,或者设置为 ‘’ 以不使用 HTTP_USER_AGENT。

  • swift_source – 用于将请求标记为源自中间件。将在代理日志中记录。

  • make_env – make_subrequest 调用此 make_env 来帮助构建 swob.Request。

返回值:

新的 swob.Request 对象。

swift.common.wsgi.run_wsgi(conf_path, app_section, *args, **kwargs)

根据某种策略运行服务器。默认策略以预分叉模型运行指定数量的工作进程。对象服务器(仅)可以使用每端口服务器策略,如果其配置具有大于零值的 servers_per_port 设置。

参数:
  • conf_path – paste.deploy 风格的配置文件/目录路径

  • app_section – conf 文件中用于加载配置的应用程序名称

  • allow_modify_pipeline – 布尔值,指示服务器是否有机会更改自身的管道。默认为 True。

  • test_config – 如果为 False(默认值),则加载并验证配置,如果成功则继续运行服务器;如果为 True,则加载并验证配置,但不运行服务器。

返回值:

0 表示成功,非零表示失败

swift.common.wsgi.wrap_conf_type(f)

包装一个函数,该函数的第一个参数是 paste.deploy 风格的配置 URI,这样您就可以传递一个未装饰的原始文件系统路径(或配置字符串),并且配置指令(config:、config_dir: 或 config_str:)将根据实体类型(文件或目录,或者如果文件系统上不存在此类实体 - 仅字符串)自动添加,然后将其传递给 paste.deploy 函数。