Debian Codegraph @

.ci/metrics/metrics.py

raw
1 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
2 # See https://llvm.org/LICENSE.txt for license information.
3 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4 """Collects Github metrics and uploads them to Grafana.
5
6 This script contains machinery that will pull metrics periodically from Github
7 about workflow runs. It will upload the collected metrics to the specified
8 Grafana instance.
9 """
10
11 import collections
12 import datetime
13 import github
14 import logging
15 import os
16 import requests
17 import time
18
19 from dataclasses import dataclass
20 from github import Auth
21 from github import Github
22
23 GRAFANA_URL = (
24 "https://influx-prod-13-prod-us-east-0.grafana.net/api/v1/push/influx/write"
25 )
26 SCRAPE_INTERVAL_SECONDS = 5 * 60
27
28 # Lists the Github workflows we want to track. Maps the Github job name to
29 # the metric name prefix in grafana.
30 # This metric name is also used as a key in the job->name map.
31 GITHUB_WORKFLOW_TO_TRACK = {"CI Checks": "github_llvm_premerge_checks"}
32
33 # Lists the Github jobs to track for a given workflow. The key is the stable
34 # name (metric name) of the workflow (see GITHUB_WORKFLOW_TO_TRACK).
35 # Each value is a map to link the github job name to the corresponding metric
36 # name.
37 GITHUB_JOB_TO_TRACK = {
38 "github_llvm_premerge_checks": {
39 "Build and Test Linux": "premerge_linux",
40 "Build and Test Windows": "premerge_windows",
41 }
42 }
43
44 # The number of workflows to pull when sampling Github workflows.
45 # - Github API filtering is broken: we cannot apply any filtering:
46 # - See https://github.com/orgs/community/discussions/86766
47 # - A workflow can complete before another workflow, even when starting later.
48 # - We don't want to sample the same workflow twice.
49 #
50 # This means we essentially have a list of workflows sorted by creation date,
51 # and that's all we can deduce from it. So for each iteration, we'll blindly
52 # process the last N workflows.
53 GITHUB_WORKFLOWS_MAX_PROCESS_COUNT = 2000
54 # Second reason for the cut: reaching a workflow older than X.
55 # This means we will miss long-tails (exceptional jobs running for more than
56 # X hours), but that's also the case with the count cutoff above.
57 # Only solution to avoid missing any workflow would be to process the complete
58 # list, which is not possible.
59 GITHUB_WORKFLOW_MAX_CREATED_AGE_HOURS = 8
60
61 # Grafana will fail to insert any metric older than ~2 hours (value determined
62 # by trial and error).
63 GRAFANA_METRIC_MAX_AGE_MN = 120
64
65
66 @dataclass
67 class JobMetrics:
68 job_name: str
69 queue_time: int
70 run_time: int
71 status: int
72 completed_at_ns: int
73 workflow_id: int
74 workflow_name: str
75
76
77 @dataclass
78 class GaugeMetric:
79 name: str
80 value: int
81 time_ns: int
82
83
84 def github_get_metrics(
85 github_repo: github.Repository, last_workflows_seen_as_completed: set[int]
86 ) -> tuple[list[JobMetrics], int]:
87 """Gets the metrics for specified Github workflows.
88
89 This function takes in a list of workflows to track, and optionally the
90 workflow ID of the last tracked invocation. It grabs the relevant data
91 from Github, returning it to the caller.
92 If the last_seen_workflow parameter is None, this returns no metrics, but
93 returns the id of the most recent workflow.
94
95 Args:
96 github_repo: A github repo object to use to query the relevant information.
97 last_seen_workflow: the last workflow this function processed.
98
99 Returns:
100 Returns a tuple with 2 elements:
101 - a list of JobMetrics objects, one per processed job.
102 - the ID of the most recent processed workflow run.
103 """
104 workflow_metrics = []
105 queued_count = collections.Counter()
106 running_count = collections.Counter()
107
108 # Initialize all the counters to 0 so we report 0 when no job is queued
109 # or running.
110 for wf_name, wf_metric_name in GITHUB_WORKFLOW_TO_TRACK.items():
111 for job_name, job_metric_name in GITHUB_JOB_TO_TRACK[wf_metric_name].items():
112 queued_count[wf_metric_name + "_" + job_metric_name] = 0
113 running_count[wf_metric_name + "_" + job_metric_name] = 0
114
115 # The list of workflows this iteration will process.
116 # MaxSize = GITHUB_WORKFLOWS_MAX_PROCESS_COUNT
117 workflow_seen_as_completed = set()
118
119 # Since we process a fixed count of workflows, we want to know when
120 # the depth is too small and if we miss workflows.
121 # E.g.: is there was more than N workflows int last 2 hours.
122 # To monitor this, we'll log the age of the oldest workflow processed,
123 # and setup alterting in Grafana to help us adjust this depth.
124 oldest_seen_workflow_age_mn = None
125
126 # Do not apply any filters to this query.
127 # See https://github.com/orgs/community/discussions/86766
128 # Applying filters like `status=completed` will break pagination, and
129 # return a non-sorted and incomplete list of workflows.
130 i = 0
131 for task in iter(github_repo.get_workflow_runs()):
132 # Max depth reached, stopping.
133 if i >= GITHUB_WORKFLOWS_MAX_PROCESS_COUNT:
134 break
135 i += 1
136
137 workflow_age_mn = (
138 datetime.datetime.now(datetime.timezone.utc) - task.created_at
139 ).total_seconds() / 60
140 oldest_seen_workflow_age_mn = workflow_age_mn
141 # If we reach a workflow older than X, stop.
142 if workflow_age_mn > GITHUB_WORKFLOW_MAX_CREATED_AGE_HOURS * 60:
143 break
144
145 # This workflow is not interesting to us.
146 if task.name not in GITHUB_WORKFLOW_TO_TRACK:
147 continue
148
149 if task.status == "completed":
150 workflow_seen_as_completed.add(task.id)
151
152 # This workflow has already been seen completed in the previous run.
153 if task.id in last_workflows_seen_as_completed:
154 continue
155
156 name_prefix = GITHUB_WORKFLOW_TO_TRACK[task.name]
157 for job in task.jobs():
158 # This job is not interesting to us.
159 if job.name not in GITHUB_JOB_TO_TRACK[name_prefix]:
160 continue
161
162 name_suffix = GITHUB_JOB_TO_TRACK[name_prefix][job.name]
163 metric_name = name_prefix + "_" + name_suffix
164
165 if task.status != "completed":
166 if job.status == "queued":
167 queued_count[metric_name] += 1
168 elif job.status == "in_progress":
169 running_count[metric_name] += 1
170 continue
171
172 job_result = int(job.conclusion == "success" or job.conclusion == "skipped")
173
174 created_at = job.created_at
175 started_at = job.started_at
176 completed_at = job.completed_at
177
178 # GitHub API can return results where the started_at is slightly
179 # later then the created_at (or completed earlier than started).
180 # This would cause a -23h59mn delta, which will show up as +24h
181 # queue/run time on grafana.
182 if started_at < created_at:
183 logging.info(
184 "Workflow {} started before being created.".format(task.id)
185 )
186 queue_time = datetime.timedelta(seconds=0)
187 else:
188 queue_time = started_at - created_at
189 if completed_at < started_at:
190 logging.info("Workflow {} finished before starting.".format(task.id))
191 run_time = datetime.timedelta(seconds=0)
192 else:
193 run_time = completed_at - started_at
194
195 if run_time.seconds == 0:
196 continue
197
198 # Grafana will refuse to ingest metrics older than ~2 hours, so we
199 # should avoid sending historical data.
200 metric_age_mn = (
201 datetime.datetime.now(datetime.timezone.utc) - completed_at
202 ).total_seconds() / 60
203 if metric_age_mn > GRAFANA_METRIC_MAX_AGE_MN:
204 logging.warning(
205 f"Job {job.id} from workflow {task.id} dropped due"
206 + f" to staleness: {metric_age_mn}mn old."
207 )
208 continue
209
210 logging.info(f"Adding a job metric for job {job.id} in workflow {task.id}")
211 # The timestamp associated with the event is expected by Grafana to be
212 # in nanoseconds.
213 completed_at_ns = int(completed_at.timestamp()) * 10**9
214 workflow_metrics.append(
215 JobMetrics(
216 metric_name,
217 queue_time.seconds,
218 run_time.seconds,
219 job_result,
220 completed_at_ns,
221 task.id,
222 task.name,
223 )
224 )
225
226 for name, value in queued_count.items():
227 workflow_metrics.append(
228 GaugeMetric(f"workflow_queue_size_{name}", value, time.time_ns())
229 )
230 for name, value in running_count.items():
231 workflow_metrics.append(
232 GaugeMetric(f"running_workflow_count_{name}", value, time.time_ns())
233 )
234
235 # Always send a hearbeat metric so we can monitor is this container is still able to log to Grafana.
236 workflow_metrics.append(
237 GaugeMetric("metrics_container_heartbeat", 1, time.time_ns())
238 )
239
240 # Log the oldest workflow we saw, allowing us to monitor if the processing
241 # depth is correctly set-up.
242 if oldest_seen_workflow_age_mn is not None:
243 workflow_metrics.append(
244 GaugeMetric(
245 "github_oldest_processed_workflow_mn",
246 oldest_seen_workflow_age_mn,
247 time.time_ns(),
248 )
249 )
250 return workflow_metrics, workflow_seen_as_completed
251
252
253 def upload_metrics(workflow_metrics, metrics_userid, api_key):
254 """Upload metrics to Grafana.
255
256 Takes in a list of workflow metrics and then uploads them to Grafana
257 through a REST request.
258
259 Args:
260 workflow_metrics: A list of metrics to upload to Grafana.
261 metrics_userid: The userid to use for the upload.
262 api_key: The API key to use for the upload.
263 """
264
265 if len(workflow_metrics) == 0:
266 logging.info("No metrics found to upload.")
267 return
268
269 metrics_batch = []
270 for workflow_metric in workflow_metrics:
271 if isinstance(workflow_metric, GaugeMetric):
272 name = workflow_metric.name.lower().replace(" ", "_")
273 metrics_batch.append(
274 f"{name} value={workflow_metric.value} {workflow_metric.time_ns}"
275 )
276 elif isinstance(workflow_metric, JobMetrics):
277 name = workflow_metric.job_name.lower().replace(" ", "_")
278 metrics_batch.append(
279 f"{name} queue_time={workflow_metric.queue_time},run_time={workflow_metric.run_time},status={workflow_metric.status} {workflow_metric.completed_at_ns}"
280 )
281 else:
282 raise ValueError(
283 f"Unsupported object type {type(workflow_metric)}: {str(workflow_metric)}"
284 )
285
286 request_data = "\n".join(metrics_batch)
287 response = requests.post(
288 GRAFANA_URL,
289 headers={"Content-Type": "text/plain"},
290 data=request_data,
291 auth=(metrics_userid, api_key),
292 )
293
294 if response.status_code < 200 or response.status_code >= 300:
295 logging.info(f"Failed to submit data to Grafana: {response.status_code}")
296
297
298 def main():
299 # Authenticate with Github
300 github_auth = Auth.Token(os.environ["GITHUB_TOKEN"])
301 grafana_api_key = os.environ["GRAFANA_API_KEY"]
302 grafana_metrics_userid = os.environ["GRAFANA_METRICS_USERID"]
303
304 # The last workflow this script processed.
305 # Because the Github queries are broken, we'll simply log a 'processed'
306 # bit for the last COUNT_TO_PROCESS workflows.
307 gh_last_workflows_seen_as_completed = set()
308
309 # Enter the main loop. Every five minutes we wake up and dump metrics for
310 # the relevant jobs.
311 while True:
312 github_object = Github(auth=github_auth)
313 github_repo = github_object.get_repo("llvm/llvm-project")
314
315 gh_metrics, gh_last_workflows_seen_as_completed = github_get_metrics(
316 github_repo, gh_last_workflows_seen_as_completed
317 )
318
319 upload_metrics(gh_metrics, grafana_metrics_userid, grafana_api_key)
320 logging.info(f"Uploaded {len(gh_metrics)} metrics")
321
322 time.sleep(SCRAPE_INTERVAL_SECONDS)
323
324
325 if __name__ == "__main__":
326 logging.basicConfig(level=logging.INFO)
327 main()