This commit is contained in:
1 parent
b724a21a0d
commit
d73fa2c435
45 files changed
+2733
-226
No files matched your search
@@ -0,0 +1,217 @@
|
||||
import hashlib
|
||||
import hmac
|
||||
import http.client
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
|
||||
def endpoint_origin(value):
|
||||
endpoint = urlsplit(value)
|
||||
if (endpoint.scheme not in ("http", "https") or not endpoint.hostname
|
||||
or endpoint.username or endpoint.password or endpoint.query or endpoint.fragment
|
||||
or endpoint.path not in ("", "/")):
|
||||
raise ValueError("endpoint must be an HTTP(S) origin without credentials")
|
||||
if endpoint.scheme == "http" and endpoint.hostname not in ("localhost", "127.0.0.1", "::1"):
|
||||
raise ValueError("use HTTPS outside localhost")
|
||||
return endpoint
|
||||
|
||||
|
||||
def signed_headers(method, path, body, host, access, secret, region, query=""):
|
||||
now = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
date = now[:8]
|
||||
digest = hashlib.sha256(body).hexdigest()
|
||||
names = "host;x-amz-content-sha256;x-amz-date"
|
||||
canonical = (f"{method}\n{path}\n{query}\nhost:{host}\nx-amz-content-sha256:{digest}\n"
|
||||
f"x-amz-date:{now}\n\n{names}\n{digest}")
|
||||
scope = f"{date}/{region}/s3/aws4_request"
|
||||
message = f"AWS4-HMAC-SHA256\n{now}\n{scope}\n{hashlib.sha256(canonical.encode()).hexdigest()}"
|
||||
key = ("AWS4" + secret).encode()
|
||||
for part in (date, region, "s3", "aws4_request"):
|
||||
key = hmac.new(key, part.encode(), hashlib.sha256).digest()
|
||||
signature = hmac.new(key, message.encode(), hashlib.sha256).hexdigest()
|
||||
return {
|
||||
"Host": host, "x-amz-content-sha256": digest, "x-amz-date": now,
|
||||
"Authorization": (f"AWS4-HMAC-SHA256 Credential={access}/{scope},"
|
||||
f"SignedHeaders={names},Signature={signature}"),
|
||||
}
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, endpoint, region, timeout=10):
|
||||
self.endpoint = endpoint_origin(endpoint)
|
||||
self.region = region
|
||||
self.timeout = timeout
|
||||
self.access = os.environ["S3_ACCESS_KEY"]
|
||||
self.secret = os.environ["S3_SECRET_KEY"]
|
||||
self.local = threading.local()
|
||||
self.connections = set()
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def request(self, method, bucket, key=None, body=b"", limit=1048576, query=None):
|
||||
path = "/" + quote(bucket, safe="")
|
||||
if key is not None:
|
||||
path += "/" + quote(key, safe="/~")
|
||||
encoded_query = "&".join(quote(name, safe="~") + "=" + quote(value, safe="~")
|
||||
for name, value in sorted((query or {}).items()))
|
||||
connection = self.connection()
|
||||
headers = signed_headers(method, path, body, self.endpoint.netloc,
|
||||
self.access, self.secret, self.region, encoded_query)
|
||||
try:
|
||||
connection.request(method, path + ("?" + encoded_query if encoded_query else ""), body, headers)
|
||||
response = connection.getresponse()
|
||||
data = response.read(limit + 1)
|
||||
if len(data) > limit:
|
||||
raise ValueError("response exceeded the test response limit")
|
||||
return response.status, dict(response.getheaders()), data
|
||||
except Exception:
|
||||
connection.close()
|
||||
self.local.connection = None
|
||||
with self.lock:
|
||||
self.connections.discard(connection)
|
||||
raise
|
||||
|
||||
def connection(self):
|
||||
connection = getattr(self.local, "connection", None)
|
||||
if connection is None:
|
||||
cls = http.client.HTTPSConnection if self.endpoint.scheme == "https" else http.client.HTTPConnection
|
||||
connection = cls(self.endpoint.hostname, self.endpoint.port, timeout=self.timeout)
|
||||
self.local.connection = connection
|
||||
with self.lock:
|
||||
self.connections.add(connection)
|
||||
return connection
|
||||
|
||||
def close(self):
|
||||
for connection in self.connections:
|
||||
connection.close()
|
||||
|
||||
|
||||
class Metrics:
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.operations = {}
|
||||
self.errors = []
|
||||
|
||||
def record(self, operation, seconds, success, status, sent, received, error=None):
|
||||
with self.lock:
|
||||
stats = self.operations.setdefault(operation, {
|
||||
"attempts": 0, "succeeded": 0, "failed": 0, "seconds": 0,
|
||||
"request_payload_bytes": 0, "response_payload_bytes": 0,
|
||||
"successful_request_payload_bytes": 0, "successful_response_payload_bytes": 0,
|
||||
"status_counts": {}, "histogram": {},
|
||||
})
|
||||
stats["attempts"] += 1
|
||||
stats["succeeded" if success else "failed"] += 1
|
||||
stats["seconds"] += seconds
|
||||
stats["request_payload_bytes"] += sent
|
||||
stats["response_payload_bytes"] += received
|
||||
if success:
|
||||
stats["successful_request_payload_bytes"] += sent
|
||||
stats["successful_response_payload_bytes"] += received
|
||||
code = str(status) if status is not None else "transport"
|
||||
stats["status_counts"][code] = stats["status_counts"].get(code, 0) + 1
|
||||
bucket = math.ceil(math.log(max(seconds * 1000, .001), 1.1))
|
||||
stats["histogram"][bucket] = stats["histogram"].get(bucket, 0) + 1
|
||||
if error and len(self.errors) < 20:
|
||||
self.errors.append({"operation": operation, "error": error})
|
||||
|
||||
def report(self, duration):
|
||||
output = {}
|
||||
for operation, stats in self.operations.items():
|
||||
item = {key: value for key, value in stats.items() if key not in ("histogram", "seconds")}
|
||||
item["successful_requests_per_second"] = round(stats["succeeded"] / max(duration, .001), 3)
|
||||
item["successful_upload_mib_per_second"] = round(stats["successful_request_payload_bytes"] / max(duration, .001) / 1048576, 3)
|
||||
item["successful_download_mib_per_second"] = round(stats["successful_response_payload_bytes"] / max(duration, .001) / 1048576, 3)
|
||||
item["mean_ms"] = round(stats["seconds"] * 1000 / stats["attempts"], 3)
|
||||
for label, fraction in (("p50_ms_upper", .5), ("p95_ms_upper", .95), ("p99_ms_upper", .99)):
|
||||
target = math.ceil(stats["attempts"] * fraction)
|
||||
seen = 0
|
||||
for bucket, count in sorted(stats["histogram"].items()):
|
||||
seen += count
|
||||
if seen >= target:
|
||||
item[label] = round(1.1 ** bucket, 3)
|
||||
break
|
||||
output[operation] = item
|
||||
return {"operations": output, "error_samples": self.errors,
|
||||
"latency_note": "All attempts; percentile histogram upper bounds have at most 10% bin width."}
|
||||
|
||||
|
||||
def request_checked(client, metrics, method, bucket, key, body, expected, digest=None):
|
||||
started = time.perf_counter()
|
||||
status = None
|
||||
received = 0
|
||||
error = None
|
||||
try:
|
||||
status, headers, data = client.request(method, bucket, key, body)
|
||||
received = len(data)
|
||||
if status not in expected:
|
||||
error = f"HTTP {status}"
|
||||
elif digest is not None and hashlib.sha256(data).hexdigest() != digest:
|
||||
error = "response checksum mismatch"
|
||||
return error is None
|
||||
except Exception as failure:
|
||||
error = type(failure).__name__
|
||||
return False
|
||||
finally:
|
||||
metrics.record(method, time.perf_counter() - started, error is None,
|
||||
status, len(body), received, error)
|
||||
|
||||
|
||||
def write_json(path, value):
|
||||
path = Path(path)
|
||||
temporary = path.with_name(path.name + ".tmp")
|
||||
with open(temporary, "w", encoding="utf-8", opener=lambda p, flags: os.open(p, flags, 0o600)) as output:
|
||||
json.dump(value, output, indent=2, sort_keys=True)
|
||||
output.write("\n")
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def read_manifest(path):
|
||||
path = Path(path)
|
||||
if path.stat().st_size > 32 * 1024 * 1024:
|
||||
raise ValueError("manifest is too large")
|
||||
value = json.loads(path.read_text())
|
||||
identifier = value["id"]
|
||||
if (value.get("format") != 1 or len(identifier) != 32
|
||||
or any(char not in "0123456789abcdef" for char in identifier)
|
||||
or value["bucket"] != "readiness-" + identifier):
|
||||
raise ValueError("invalid test ownership manifest")
|
||||
if len(value["objects"]) > 100000:
|
||||
raise ValueError("too many manifest objects")
|
||||
for key, entry in value["objects"].items():
|
||||
if not key.startswith("objects/") or not key[8:].isdigit():
|
||||
raise ValueError("invalid test object key")
|
||||
if not 1 <= entry["size"] <= 1048576:
|
||||
raise ValueError("invalid test object size")
|
||||
if len(entry["sha256"]) != 64:
|
||||
raise ValueError("invalid test object checksum")
|
||||
endpoint_origin(value["endpoint"])
|
||||
return value
|
||||
|
||||
|
||||
def check_owner(client, manifest):
|
||||
status, _, body = client.request("GET", manifest["bucket"], ".readiness-owner")
|
||||
if status != 200 or body != manifest["id"].encode():
|
||||
raise ValueError("test ownership marker mismatch; refusing to access or delete objects")
|
||||
|
||||
|
||||
def check_empty_except_marker(client, manifest):
|
||||
status, _, body = client.request("GET", manifest["bucket"], query={"list-type": "2", "max-keys": "2"})
|
||||
if status != 200:
|
||||
raise ValueError("could not verify test bucket contents before removal")
|
||||
try:
|
||||
root = ET.fromstring(body)
|
||||
except ET.ParseError as error:
|
||||
raise ValueError("invalid bucket listing; refusing to remove marker") from error
|
||||
keys = [element.text for element in root.findall("{*}Contents/{*}Key")]
|
||||
truncated = root.findtext("{*}IsTruncated")
|
||||
if root.tag.rsplit("}", 1)[-1] != "ListBucketResult" or keys != [".readiness-owner"] or truncated != "false":
|
||||
raise ValueError("bucket has unlisted objects; preserving bucket and ownership marker")
|
||||
Reference in new issue
Block a user