mirror of
https://github.com/floci-io/floci.git
synced 2026-12-03 10:17:48 -05:00
Part 1 of #7030. GetSeries (/api/v1/series) and GetLabels (/api/v1/labels, /api/v1/label/<name>/values) answer over the metrics the OTLP endpoint ingests, with the labels, selector syntax, limits and Prometheus envelope the CloudWatch user guide's PromQL pages give. Regular expressions are RE2's, as Prometheus's are. The guide's "IAM permissions for PromQL" table is vendored by a new fetcher and read by the authorized-actions generator, so the operations are checked as cloudwatch:ListMetrics, and QueryMetrics carries cloudwatch:ListMetrics as a companion every request needs, which the enforcement filter checks. @IamOperation can name a method's operation. The OTLP 40 KB metadata limit counts the resource and scope schema URLs, which PromQL reads as labels of the series.
191 lines
9.5 KiB
Python
191 lines
9.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Vendor what the Amazon CloudWatch user guide says each PromQL API operation needs into
|
|
tools/aws/sources/cloudwatch-promql-permissions.json, a source of the IAM tables.
|
|
|
|
CloudWatch serves PromQL through Prometheus-compatible HTTP endpoints, /api/v1/query and its siblings, which neither
|
|
botocore nor the Service Reference model: no operation of theirs names them, and so no generated route gives their
|
|
actions. The user guide does, in two places this script copies as they stand:
|
|
|
|
- The "IAM permissions for PromQL" table of "Query metrics with PromQL", each endpoint path with its HTTP methods and
|
|
the actions it requires:
|
|
|
|
/api/v1/query GET, POST cloudwatch:GetMetricData, cloudwatch:ListMetrics
|
|
/api/v1/series GET, POST cloudwatch:ListMetrics
|
|
|
|
https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-PromQL.html
|
|
|
|
- The page of each operation "Prometheus-compatible APIs" links to, named by its title (QueryMetrics, GetSeries,
|
|
GetLabels), with the paths its "Valid URI" or "Valid URIs" give:
|
|
|
|
https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-PromQL-APIs.html
|
|
|
|
A path is copied with its placeholder as the page names it, /api/v1/label/{label_name}/values. A table or a page whose
|
|
layout changed is refused rather than read short, so a refresh never drops a check. Nothing in the output is written
|
|
by hand, and tools/aws/regen_iam_authorized_actions.py reads it against the Service Reference's actions.
|
|
|
|
Run from anywhere in the repo:
|
|
python3 tools/aws/fetch_cloudwatch_promql_permissions.py # rewrite the vendored file
|
|
python3 tools/aws/fetch_cloudwatch_promql_permissions.py --verify # online: the file still says it
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import html
|
|
import json
|
|
import re
|
|
import sys
|
|
import urllib.request
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
GUIDE = "https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/"
|
|
PERMISSIONS_PAGE = GUIDE + "CloudWatch-PromQL.html"
|
|
OPERATIONS_PAGE = GUIDE + "CloudWatch-PromQL-APIs.html"
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
OUTPUT = REPO_ROOT / "tools/aws/sources/cloudwatch-promql-permissions.json"
|
|
FETCHER = str(Path(__file__).resolve().relative_to(REPO_ROOT))
|
|
|
|
HEADING_RE = re.compile(r'<h2 id="CloudWatch-PromQL-IAM">IAM permissions for PromQL</h2>')
|
|
HEADERS = ["API endpoint path", "HTTP methods", "Required actions"]
|
|
OPERATION_LINK_RE = re.compile(r'href="\./(CloudWatch-PromQL-API-[A-Za-z]+\.html)"')
|
|
TITLE_RE = re.compile(r'<h1 class="topictitle"[^>]*>([A-Za-z]+)</h1>')
|
|
URIS_RE = re.compile(r'<dt><span class="term">Valid URIs?</span></dt>\s*<dd>(?P<uris>.*?)</dd>', re.S)
|
|
PATH_RE = re.compile(r"^/api/v1/[a-z_]+(?:/\{[a-z_]+\}/[a-z_]+)?$")
|
|
METHOD_RE = re.compile(r"^(?:GET|POST|PUT|DELETE|PATCH|HEAD)$")
|
|
ACTION_RE = re.compile(r"^cloudwatch:[A-Za-z]+$")
|
|
|
|
|
|
def text(fragment: str) -> str:
|
|
"""A fragment of a page as text: a placeholder the page sets apart as replaceable kept in braces, tags dropped and
|
|
spaces collapsed."""
|
|
braced = re.sub(r'<code class="replaceable">([^<]*)</code>', r"{\1}", fragment)
|
|
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", braced))).strip()
|
|
|
|
|
|
def code(fragment: str) -> list[str]:
|
|
"""Each code span a fragment holds at its own level, a placeholder inside one kept in braces."""
|
|
spans = []
|
|
for span in re.finditer(r'<code class="code">((?:[^<]|<code class="replaceable">[^<]*</code>)*)</code>', fragment):
|
|
spans.append(text(span.group(1)))
|
|
return spans
|
|
|
|
|
|
def read_permissions(page: str) -> list[dict]:
|
|
"""The rows of the page's "IAM permissions for PromQL" table: each path, its methods and the actions it requires."""
|
|
heading = HEADING_RE.search(page)
|
|
if not heading:
|
|
raise ValueError(f"{PERMISSIONS_PAGE} has no 'IAM permissions for PromQL' section: its layout changed")
|
|
table = re.search(r"<table[^>]*>(?P<table>.*?)</table>", page[heading.end():], re.S)
|
|
if not table:
|
|
raise ValueError(f"{PERMISSIONS_PAGE} gives no table under 'IAM permissions for PromQL': its layout changed")
|
|
headers = [text(cell) for cell in re.findall(r"<th[^>]*>(.*?)</th>", table.group("table"), re.S)]
|
|
if headers != HEADERS:
|
|
raise ValueError(f"the PromQL permissions table's columns are {headers}, not {HEADERS}: its layout changed")
|
|
rows = []
|
|
for row in re.findall(r"<tr>(.*?)</tr>", table.group("table"), re.S):
|
|
cells = re.findall(r"<td[^>]*>(.*?)</td>", row, re.S)
|
|
if not cells:
|
|
continue
|
|
if len(cells) != len(HEADERS):
|
|
raise ValueError(f"a row of the PromQL permissions table has {len(cells)} cells: its layout changed")
|
|
paths, methods, actions = code(cells[0]), text(cells[1]).split(", "), code(cells[2])
|
|
if len(paths) != 1 or not PATH_RE.match(paths[0]) or not methods \
|
|
or not all(METHOD_RE.match(method) for method in methods) \
|
|
or not actions or not all(ACTION_RE.match(action) for action in actions):
|
|
raise ValueError(f"the PromQL permissions table gives '{text(row)}', which is not a path, its methods "
|
|
f"and cloudwatch: actions: its wording changed")
|
|
rows.append({"path": paths[0], "methods": methods, "actions": actions})
|
|
if not rows:
|
|
raise ValueError("the PromQL permissions table gives no rows: its layout changed")
|
|
return rows
|
|
|
|
|
|
def operation_pages(index: str) -> list[str]:
|
|
"""The page of each operation "Prometheus-compatible APIs" links to, in the order it lists them."""
|
|
found = []
|
|
for link in OPERATION_LINK_RE.findall(index):
|
|
if link not in found:
|
|
found.append(link)
|
|
if not found:
|
|
raise ValueError(f"{OPERATIONS_PAGE} links no operation page: its layout changed")
|
|
return found
|
|
|
|
|
|
def read_operation(page: str, url: str) -> dict:
|
|
"""The operation a page is about, by its title, and the paths its "Valid URI" or "Valid URIs" give."""
|
|
title = TITLE_RE.search(page)
|
|
uris = URIS_RE.search(page)
|
|
if not title or not uris:
|
|
raise ValueError(f"{url} gives no operation title or no valid URIs: its layout changed")
|
|
paths = []
|
|
for paragraph in re.findall(r"<p>(.*?)</p>", uris.group("uris"), re.S):
|
|
spans = code(paragraph)
|
|
if not spans or not PATH_RE.match(spans[0]):
|
|
raise ValueError(f"{url} gives the valid URI '{text(paragraph)}', which names no path: its wording "
|
|
f"changed")
|
|
paths.append(spans[0])
|
|
return {"operation": title.group(1), "page": url, "uris": paths}
|
|
|
|
|
|
def build(permissions_page: str, index: str, pages: dict[str, str]) -> dict:
|
|
links = operation_pages(index)
|
|
return {
|
|
"_source": {
|
|
"pages": [PERMISSIONS_PAGE, OPERATIONS_PAGE, *(GUIDE + link for link in links)],
|
|
"fetcher": FETCHER,
|
|
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
"note": "The user guide's table of the actions each PromQL API path requires, and the paths each "
|
|
"operation's page gives as its valid URIs, copied as they stand.",
|
|
},
|
|
"permissions": read_permissions(permissions_page),
|
|
"operations": [read_operation(pages[link], GUIDE + link) for link in links],
|
|
}
|
|
|
|
|
|
def fetch_url(url: str) -> str:
|
|
request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"})
|
|
with urllib.request.urlopen(request, timeout=60) as response:
|
|
return response.read().decode("utf-8")
|
|
|
|
|
|
def fetch_all(fetch=fetch_url) -> tuple[str, str, dict[str, str]]:
|
|
"""The permissions page, the index of operations and each operation's page."""
|
|
permissions_page, index = fetch(PERMISSIONS_PAGE), fetch(OPERATIONS_PAGE)
|
|
return permissions_page, index, {link: fetch(GUIDE + link) for link in operation_pages(index)}
|
|
|
|
|
|
def stale(vendored: dict, permissions_page: str, index: str, pages: dict[str, str]) -> bool:
|
|
"""Whether the pages now give something other than the vendored file, its date aside."""
|
|
built = build(permissions_page, index, pages)
|
|
return any(vendored.get(key) != built[key] for key in built if key != "_source") \
|
|
or vendored.get("_source", {}).get("pages") != built["_source"]["pages"]
|
|
|
|
|
|
def main(argv: list[str] | None = None, fetch=fetch_url) -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages")
|
|
args = parser.parse_args(argv)
|
|
try:
|
|
permissions_page, index, pages = fetch_all(fetch)
|
|
except OSError as e:
|
|
print(f"error: could not read the Amazon CloudWatch user guide ({e})", file=sys.stderr)
|
|
return 2
|
|
if args.verify:
|
|
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
|
|
if stale(vendored, permissions_page, index, pages):
|
|
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the Amazon CloudWatch user guide does: "
|
|
f"run tools/aws/fetch_cloudwatch_promql_permissions.py and then make iam-authorized-actions-sync",
|
|
file=sys.stderr)
|
|
return 1
|
|
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the Amazon CloudWatch user guide")
|
|
return 0
|
|
built = build(permissions_page, index, pages)
|
|
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
|
|
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['permissions'])} paths, "
|
|
f"{len(built['operations'])} operations)")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|