File size: 13,921 Bytes
784ee2c | 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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 | #!/usr/bin/env python3
import json
import argparse
import os
# --- PUBSUB ---
from google.cloud import pubsub_v1
from google.oauth2 import service_account
# --- END PUBSUB ---
# Remember where we were invoked from: the chdir below would otherwise silently
# reinterpret any relative path passed on the command line as relative to flow/.
INVOCATION_DIR = os.getcwd()
# make sure the working dir is flow/
os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
# Create the argument parser
parser = argparse.ArgumentParser(description="Process some integers.")
# Add the named arguments
parser.add_argument("--buildID", type=str, help="Build ID from jenkins")
parser.add_argument("--branchName", type=str, help="Current Branch Name")
parser.add_argument("--pipelineID", type=str, help="Jenkins pipeline ID")
parser.add_argument("--commitSHA", type=str, help="Current commit sha")
parser.add_argument("--jenkinsURL", type=str, help="Jenkins Report URL")
parser.add_argument(
"--changeBranch", type=str, help="Branch corresponding to change request"
)
parser.add_argument("--variant", type=str, default="base")
parser.add_argument(
"--jobName",
type=str,
default=None,
help="Canonical Jenkins job-folder name (JOB_NAME with the trailing "
"/<branch> segment stripped, folder slashes kept). When set, the "
"Pub/Sub payload is emitted as schema v3 with a top-level job_name "
"so the backend resolves the pipeline directly instead of "
"classifying the BUILD_TAG.",
)
parser.add_argument(
"--provenanceFile",
type=str,
default=None,
help="Path to a JSON file describing what was actually built: the "
"jenkins-ci shared-library version and the submodule commits present in "
"the build workspace. Must be produced there, not here — nightly "
"pipelines repoint tools/OpenROAD, so the reporting workspace holds the "
"pinned commit rather than the built one. When supplied alongside "
"--jobName the payload is emitted as schema v4.",
)
# --- PUBSUB args ---
parser.add_argument(
"--jenkinsEnv",
type=str,
default="unknown",
choices=["public", "secure", "unknown"],
help="Jenkins environment (public or secure)",
)
parser.add_argument("--pubsubProjectID", type=str, help="GCP project ID for Pub/Sub")
parser.add_argument(
"--pubsubTopicID",
type=str,
default="ci-metrics-reports-topics",
help="Pub/Sub topic ID",
)
parser.add_argument(
"--pubsubCred", type=str, help="Service account credentials file for Pub/Sub"
)
# --- END PUBSUB args ---
# Parse the arguments
args = parser.parse_args()
# --- PUBSUB ---
# Pub/Sub hard cap is 10 MB. Stay under with safety margin to leave room for
# attribute overhead and future payload growth.
MAX_PUBSUB_BYTES = 8 * 1024 * 1024
def build_design_record(dataFile, platform, design, variant, rules):
"""Return a dict for one design to be included in the pipeline-level payload."""
with open(dataFile) as f:
data = json.load(f)
metrics = {k.replace(":", "__"): v for k, v in data.items()}
return {
"platform": platform,
"design": design,
"variant": variant,
"rules": rules,
"metrics": metrics,
}
def _submodule_defect(entry):
"""Describe why ``entry`` is not a usable submodule record, or ``None``.
Mirrors the keys the backend requires of every element of the v4
``submodules`` array. ``overridden`` is checked for presence only: ``False``
is the common, valid case.
"""
if not isinstance(entry, dict):
return "is not an object"
for key in ("path", "sha"):
value = entry.get(key)
if not isinstance(value, str) or not value.strip():
return f"has no {key}"
if entry.get("overridden") is None:
return "has no overridden"
return None
def load_provenance(path):
"""Return the build-provenance dict from ``path``, or ``None``.
A malformed or unreadable file degrades to v3 rather than failing the upload:
losing the whole metrics report over missing provenance would be a worse
outcome than losing the provenance.
"""
if not path:
return None
# Relative paths are resolved against the caller's directory, not flow/.
if not os.path.isabs(path):
path = os.path.join(INVOCATION_DIR, path)
try:
with open(path) as f:
data = json.load(f)
except (OSError, ValueError) as e:
print(
f"[WARN] Could not read provenance file '{path}': {e}. "
"Falling back to v3."
)
return None
# json.load accepts any top-level JSON value: a file holding a list or a
# bare scalar parses fine, then .get() below raises AttributeError.
if not isinstance(data, dict):
print(
f"[WARN] Provenance file '{path}' does not contain a JSON object. "
"Falling back to v3."
)
return None
submodules = data.get("submodules")
library = data.get("jenkins_library")
if not isinstance(submodules, list) or not submodules:
print(f"[WARN] Provenance file '{path}' has no submodules. Falling back to v3.")
return None
if not isinstance(library, dict) or not library.get("ref"):
print(
f"[WARN] Provenance file '{path}' has no jenkins_library.ref. "
"Falling back to v3."
)
return None
# Every entry has to satisfy the backend's per-entry v4 keys, not just the
# array as a whole: one defective entry rejects the whole message, and the
# point of degrading to v3 is to not emit a message the backend will reject.
for i, entry in enumerate(submodules):
defect = _submodule_defect(entry)
if defect:
print(
f"[WARN] Provenance file '{path}': submodules[{i}] {defect}. "
"Falling back to v3."
)
return None
return {"jenkins_library": library, "submodules": submodules}
def resolve_job_name(args):
"""Canonical job name, or None when absent/blank."""
return args.jobName.strip() if args.jobName else None
def resolve_schema_version(args, provenance):
"""The schema version this run's payload satisfies.
v4 needs both a job name and provenance; the backend requires every v4 key,
so a run that could not capture its submodules must stay on v3 rather than
emit a v4 message the backend will reject.
"""
if not resolve_job_name(args):
return 2
return 4 if provenance else 3
def build_pipeline_payload(design_records, args, provenance=None):
"""Return the pipeline-level payload dict.
Emits schema v2 (no job name), v3 (job name) or v4 (job name plus build
provenance) — see :func:`resolve_schema_version`.
"""
job_name = resolve_job_name(args)
schema_version = resolve_schema_version(args, provenance)
payload = {
"payload_schema_version": schema_version,
"jenkins_env": args.jenkinsEnv,
"build_id": args.buildID,
"branch_name": args.branchName,
"pipeline_id": args.pipelineID,
"change_branch": args.changeBranch,
"commit_sha": args.commitSHA,
"jenkins_url": args.jenkinsURL,
"designs": design_records,
}
if job_name:
payload["job_name"] = job_name
# Only a v4 payload carries provenance. Provenance without a job name cannot
# be v4 (the backend requires job_name from v3 up), and attaching v4 keys to
# a message labelled v2 would make payload_schema_version stop describing
# the payload.
if schema_version == 4:
payload.update(provenance)
return payload
def publish_pipeline_report(
publisher, topic_path, message_data, design_count, args, provenance=None
):
"""Publish a pre-encoded pipeline message (v2, v3 or v4)."""
size_kb = len(message_data) / 1024
schema_version = str(resolve_schema_version(args, provenance))
print(
f"[INFO] Publishing v{schema_version} pipeline report "
f"({design_count} designs, {size_kb:.1f} KB) to Pub/Sub."
)
future = publisher.publish(
topic_path,
data=message_data,
payload_schema_version=schema_version,
jenkins_env=args.jenkinsEnv,
)
message_id = future.result()
print(f"[INFO] Published pipeline report to Pub/Sub (message ID: {message_id}).")
def publish_v1_per_design(publisher, topic_path, design_records, args, provenance=None):
"""Fallback path used when the v2 pipeline payload exceeds MAX_PUBSUB_BYTES.
Emits one v1-format message per design (no payload_schema_version, metrics
flattened at the root), matching the legacy schema the ingestion service
still supports.
Provenance is mirrored onto every message: all of them resolve to the same
build, and the backend upserts components by path, so N copies converge on
one set of rows. Omitting it here would make an oversized nightly look like
a build with no overrides.
Unlike the pipeline payload this is not gated on the v4 job-name
requirement: a v1 message declares no schema version, so there is nothing
for the extra keys to contradict, and the backend reads provenance here by
key presence rather than by version.
"""
futures = []
for d in design_records:
payload = {
"build_id": args.buildID,
"branch_name": args.branchName,
"pipeline_id": args.pipelineID,
"change_branch": args.changeBranch,
"commit_sha": args.commitSHA,
"jenkins_url": args.jenkinsURL,
"jenkins_env": args.jenkinsEnv,
"rules": d["rules"],
}
if provenance:
payload.update(provenance)
payload.update(d["metrics"])
message_data = json.dumps(payload, default=str).encode("utf-8")
try:
future = publisher.publish(
topic_path,
data=message_data,
jenkins_env=args.jenkinsEnv,
)
futures.append((d, future))
except Exception as e:
print(
f"[WARN] Pub/Sub v1 fallback publish failed for "
f"{d['platform']} {d['design']} {d['variant']}: {e}"
)
for d, future in futures:
try:
message_id = future.result()
print(
f"[INFO] Published v1 fallback message (ID: {message_id}) for "
f"{d['platform']} {d['design']} {d['variant']}."
)
except Exception as e:
print(
f"[WARN] Pub/Sub v1 fallback publish failed for "
f"{d['platform']} {d['design']} {d['variant']}: {e}"
)
# --- END PUBSUB ---
def get_rules(dataFile):
data = {}
if os.path.exists(dataFile):
with open(dataFile) as f:
data = json.load(f)
return data
# --- PUBSUB init ---
publisher = None
topic_path = None
if args.pubsubCred and args.pubsubProjectID:
pubsub_credentials = service_account.Credentials.from_service_account_file(
args.pubsubCred
)
publisher = pubsub_v1.PublisherClient(credentials=pubsub_credentials)
topic_path = publisher.topic_path(args.pubsubProjectID, args.pubsubTopicID)
print(f"[INFO] Pub/Sub publisher initialized for topic: {topic_path}")
elif args.pubsubProjectID:
# No credentials file — use default credentials (e.g., emulator or ADC)
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(args.pubsubProjectID, args.pubsubTopicID)
print(
f"[INFO] Pub/Sub publisher initialized (default creds) for topic: {topic_path}"
)
# --- END PUBSUB init ---
RUN_FILENAME = "metadata.json"
# --- PUBSUB ---
design_records = []
# --- END PUBSUB ---
for reportDir, dirs, files in sorted(os.walk("reports", topdown=False)):
dirList = reportDir.split(os.sep)
if len(dirList) != 4:
continue
# basic info about test design
platform = dirList[1]
design = dirList[2]
variant = dirList[3]
dataFile = os.path.join(reportDir, RUN_FILENAME)
if not os.path.exists(dataFile):
print(f"[WARN] No data file for {platform} {design} {variant}.")
continue
if platform == "sky130hd_fakestack" or platform == "src":
print(f"[WARN] Skiping upload {platform} {design} {variant}.")
continue
print(f"[INFO] Get rules for {platform} {design} {variant}.")
rules = get_rules(
os.path.join("designs", platform, design, f"rules-{variant}.json")
)
# --- PUBSUB ---
if publisher:
design_records.append(
build_design_record(dataFile, platform, design, variant, rules)
)
# --- END PUBSUB ---
# --- PUBSUB ---
if publisher and design_records:
provenance = load_provenance(args.provenanceFile)
payload = build_pipeline_payload(design_records, args, provenance)
message_data = json.dumps(payload, default=str).encode("utf-8")
if len(message_data) > MAX_PUBSUB_BYTES:
print(
f"[WARN] Payload size {len(message_data) / 1024:.1f} KB exceeds "
f"{MAX_PUBSUB_BYTES // 1024} KB cap. Falling back to v1 per-design publish "
f"({len(design_records)} messages)."
)
publish_v1_per_design(publisher, topic_path, design_records, args, provenance)
else:
try:
publish_pipeline_report(
publisher,
topic_path,
message_data,
len(design_records),
args,
provenance,
)
except Exception as e:
print(f"[WARN] Pub/Sub publish failed for pipeline report: {e}")
elif publisher and not design_records:
print("[WARN] Pub/Sub publisher initialized but no design records were collected.")
# --- END PUBSUB ---
|