Repository navigation
Expand file tree
/
Copy pathweekly.py
More file actions
133 lines (106 loc) · 4.87 KB
/
Copy pathweekly.py
File metadata and controls
133 lines (106 loc) · 4.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#!/usr/bin/env python3
"""
Weekly DevTools toolbox error report.
Downloads the cached results of the two Redash queries, analyzes them, and
writes reports/<YYYY-MM-DD>/{server,component,meeting}.md and summary.json.
Redash refreshes the queries on its own weekly schedule. This script only
reads results, with the per-query API keys from the environment:
REDASH_SERVER_QUERY_KEY and REDASH_COMPONENT_QUERY_KEY.
"""
import argparse
import json
import os
import sys
import tempfile
import urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path
from analyze import TelemetryAnalyzer
REDASH_URL = "https://sql.telemetry.mozilla.org"
DASHBOARD_URL = f"{REDASH_URL}/dashboard/devtools-toolbox-errors"
DEFAULT_REPO = "firefox-devtools/devtools-error-reports"
REPORTS_DIR = Path(__file__).parent / "reports"
MAX_RESULT_AGE = timedelta(days=2)
TOP_N = 10
# kind -> (query id, label in the meeting text)
QUERIES = {
"server": (114959, "Startup errors"),
"component": (114982, "Component errors"),
}
def fetch(url):
req = urllib.request.Request(url, headers={"User-Agent": "devtools-error-reports"})
with urllib.request.urlopen(req, timeout=120) as resp:
return resp.read()
def download_csv(query_id, key, allow_stale):
base = f"{REDASH_URL}/api/queries/{query_id}"
result = json.loads(fetch(f"{base}/results.json?api_key={key}"))["query_result"]
retrieved_at = datetime.fromisoformat(result["retrieved_at"].replace("Z", "+00:00"))
age = datetime.now(timezone.utc) - retrieved_at
if age > MAX_RESULT_AGE and not allow_stale:
sys.exit(f"Query {query_id} result is from {retrieved_at:%Y-%m-%d %H:%M} UTC. "
"Check its refresh schedule on Redash, or pass --allow-stale.")
return fetch(f"{base}/results.csv?api_key={key}")
def previous_summary(today):
for folder in sorted(REPORTS_DIR.iterdir(), reverse=True):
summary = folder / "summary.json"
if folder.name < today and summary.exists():
return folder.name, json.loads(summary.read_text())
return None, None
def describe(kind, current, prev_date, prev):
text = f"{current['total']} errors"
prev_kind = prev.get(kind) if prev else None
if prev_kind:
text += f" ({current['total'] - prev_kind['total']:+d} vs {prev_date})"
prev_counts = dict(prev_kind["top"])
issues = []
for desc, count in current["top"][:3]:
if not prev_kind:
issues.append(f"{desc} ({count})")
elif desc in prev_counts:
issues.append(f"{desc} ({count}, was {prev_counts[desc]})")
else:
issues.append(f"{desc} ({count}, not in last top {TOP_N})")
return f"{text}. Top issues: {', '.join(issues)}."
def main():
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--allow-stale", action="store_true",
help=f"accept query results older than {MAX_RESULT_AGE.days} days")
args = parser.parse_args()
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
out_dir = REPORTS_DIR / today
out_dir.mkdir(parents=True, exist_ok=True)
repo = os.environ.get("GITHUB_REPOSITORY", DEFAULT_REPO)
server = os.environ.get("GITHUB_SERVER_URL", "https://github.com")
reports_url = f"{server}/{repo}/blob/main/reports/{today}"
summary = {}
for kind, (query_id, _) in QUERIES.items():
key = os.environ.get(f"REDASH_{kind.upper()}_QUERY_KEY")
if not key:
sys.exit(f"Set REDASH_{kind.upper()}_QUERY_KEY first")
csv_data = download_csv(query_id, key, args.allow_stale)
with tempfile.NamedTemporaryFile(suffix=".csv") as tmp:
tmp.write(csv_data)
tmp.flush()
analyzer = TelemetryAnalyzer(tmp.name, top_n=TOP_N)
analyzer.load_data()
report = analyzer.generate_detailed_report()
report += "\n\n---\n\n" + analyzer.generate_short_summary() + "\n"
(out_dir / f"{kind}.md").write_text(report)
summary[kind] = {"total": analyzer.total, "top": analyzer.top_issues(TOP_N)}
(out_dir / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")
prev_date, prev = previous_summary(today)
lines = [f"- Toolbox errors ([dashboard]({DASHBOARD_URL})):"]
for kind, (_, label) in QUERIES.items():
lines.append(f" - **{label}** ([full report]({reports_url}/{kind}.md)): "
+ describe(kind, summary[kind], prev_date, prev))
lines.append(" - **TODO**: comment on the trend.")
meeting = "\n".join(lines) + "\n"
(out_dir / "meeting.md").write_text(meeting)
print(meeting)
step_summary = os.environ.get("GITHUB_STEP_SUMMARY")
if step_summary:
with open(step_summary, "a") as f:
f.write(f"```markdown\n{meeting}```\n")
if __name__ == "__main__":
main()