wireless-vendor-identifiers / scripts /build_snapshot.py
ictrun's picture
Add monthly refresh job (scripts/refresh.py)
f68295f verified
Raw History Blame Contribute Delete
12.9 kB
#!/usr/bin/env python3
"""Rebuild the dataset tables from a fresh upstream snapshot.
Usage:
python3 scripts/build_snapshot.py --upstream DIR --date YYYY-MM-DD [--seed CSV]
DIR holds the raw upstream files named like the manifest paths with "/"
replaced by "_" (oui.csv, company_identifiers_company_identifiers.yaml,
core_ad_types.yaml, uuids_member_uuids.yaml, ...).
vendor_identifiers is rebuilt in full. bluetooth_assigned_numbers is rebuilt
from YAML for every namespace except GAP appearance rows, which are kept from
the previous snapshot and only re-stamped (the script refuses to run if the
appearance source changed).
first_seen_snapshot is carried over from the previous tables. A record that
is not in them takes its date from --seed (a record_id,first_seen_snapshot
CSV, used when backfilling history) or, failing that, --date.
"""
import argparse
import csv
import hashlib
import re
from collections import Counter
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
DATA = ROOT / "data"
SIG_BASE = "https://bitbucket.org/bluetooth-SIG/public/raw/main/assigned_numbers/"
OUI_URL = "https://standards-oui.ieee.org/oui/oui.csv"
COMPANY_FILE = "company_identifiers/company_identifiers.yaml"
MEMBER_FILE = "uuids/member_uuids.yaml"
APPEARANCE_FILE = "core/appearance_values.yaml"
FIRST_SEEN = "first_seen_snapshot"
# namespace -> (source file, key holding the number)
SIG_TABLES = {
"ble_ad_type": ("core/ad_types.yaml", "value"),
"gatt_service_uuid": ("uuids/service_uuids.yaml", "uuid"),
"gatt_characteristic_uuid": ("uuids/characteristic_uuids.yaml", "uuid"),
"gatt_descriptor_uuid": ("uuids/descriptors.yaml", "uuid"),
"gatt_declaration_uuid": ("uuids/declarations.yaml", "uuid"),
"bluetooth_protocol_uuid": ("uuids/protocol_identifiers.yaml", "uuid"),
"bluetooth_service_class_uuid": ("uuids/service_class.yaml", "uuid"),
"bluetooth_unit_uuid": ("uuids/units.yaml", "uuid"),
}
# Bluetooth SIG registries that assign numbers to companies.
# namespace -> (source file, key, record_id prefix, identifier_format)
SIG_VENDOR_REGISTRIES = {
"bluetooth_sig_company_identifier": (
COMPANY_FILE, "value", "bluetooth-company-id-",
"16-bit hexadecimal Bluetooth Company Identifier"),
"bluetooth_sig_member_uuid": (
MEMBER_FILE, "uuid", "bluetooth-member-uuid-",
"16-bit hexadecimal Bluetooth SIG member service UUID"),
}
VENDOR_NAMESPACES = ["ieee_oui_ma_l"] + list(SIG_VENDOR_REGISTRIES)
def sha256(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def local_name(upstream, rel):
return upstream / rel.replace("/", "_")
def parse_yaml_list(path):
"""Parse the flat `- key: value` list format used by Bluetooth SIG YAML."""
items, cur = [], None
for line in path.read_text(encoding="utf-8").splitlines():
m = re.match(r"^\s*(-\s+)?([A-Za-z_]+):\s*(.*?)\s*$", line)
if not m or line.lstrip().startswith("#"):
continue
dash, key, val = m.groups()
if len(val) >= 2 and val[0] == val[-1] and val[0] in "'\"":
val = val[1:-1].replace("''", "'")
if dash:
cur = {}
items.append(cur)
if cur is not None and val:
cur[key] = val
return items
def norm(text):
return " " + re.sub(r"[^a-z0-9]+", " ", text.lower()).strip() + " "
def slug(text):
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
def hex_value(raw, width):
return "0x" + format(int(raw, 16), "0%dX" % width)
def read_csv(path):
with open(path, newline="", encoding="utf-8") as fh:
return list(csv.DictReader(fh))
def write_csv(name, rows, fields):
with open(DATA / name, "w", newline="", encoding="utf-8") as fh:
writer = csv.DictWriter(fh, fieldnames=fields, lineterminator="\n")
writer.writeheader()
writer.writerows(rows)
def with_column(fields, column, after=None):
"""Return fields with column present, inserted after `after` or appended."""
if column in fields:
return list(fields)
if after is None:
return list(fields) + [column]
i = fields.index(after) + 1
return list(fields[:i]) + [column] + list(fields[i:])
class VendorMatcher:
def __init__(self, vendors):
self.vendors = [
(v, [norm(k) for k in v["keyword_hints"].split("|")]) for v in vendors
]
def match(self, name):
n = norm(name)
hits = [v for v, kws in self.vendors if any(k in n for k in kws)]
if len(hits) > 1:
raise ValueError("ambiguous vendor match: %r" % name)
return hits[0] if hits else None
def vendor_row(vendor, record_id, namespace, value, fmt, name, authority, url, date, sha):
return {
"record_id": record_id,
"vendor_slug": vendor["vendor_slug"],
"vendor_display_name": vendor["vendor_display_name"],
"ecosystem_tags": vendor["ecosystem_tags"],
"identifier_namespace": namespace,
"identifier_value": value,
"identifier_format": fmt,
"assignment_name": name,
"source_authority": authority,
"source_url": url,
"source_snapshot_date": date,
"source_sha256": sha,
"safe_use_category": "public_identifier_metadata",
"dual_use_notes": "identifier_only",
}
def sig_vendor_rows(upstream, date, matcher, hashes, namespace):
rel, key, prefix, fmt = SIG_VENDOR_REGISTRIES[namespace]
rows = []
for item in parse_yaml_list(local_name(upstream, rel)):
vendor = matcher.match(item["name"])
if vendor:
value = hex_value(item[key], 4)
rows.append(vendor_row(vendor, prefix + value[2:], namespace, value, fmt,
item["name"], "Bluetooth SIG", SIG_BASE + rel,
date, hashes[rel]))
return rows
def build_vendor_identifiers(upstream, date, matcher, hashes):
rows = []
with open(upstream / "oui.csv", newline="", encoding="utf-8-sig") as fh:
for r in csv.DictReader(fh):
if r["Registry"] != "MA-L":
continue
name = r["Organization Name"].strip()
vendor = matcher.match(name)
if vendor:
oui = r["Assignment"].strip().upper()
rows.append(vendor_row(vendor, "ieee-oui-" + oui, "ieee_oui_ma_l", oui,
"24-bit hexadecimal OUI/MA-L assignment", name,
"IEEE Registration Authority", OUI_URL,
date, hashes["oui"]))
for namespace in SIG_VENDOR_REGISTRIES:
rows.extend(sig_vendor_rows(upstream, date, matcher, hashes, namespace))
rows.sort(key=lambda r: (r["vendor_slug"], r["record_id"]))
return rows
def build_assigned_numbers(upstream, date, old_rows, hashes):
rows = []
for namespace, (rel, key) in SIG_TABLES.items():
for item in parse_yaml_list(local_name(upstream, rel)):
raw = item[key]
value = hex_value(raw, len(raw) - 2)
rows.append({
"record_id": "%s-%s-%s" % (namespace, value[2:], slug(item["name"])),
"assigned_number_namespace": namespace,
"assigned_number_value": value,
"name": item["name"],
"qualified_identifier": item.get("id", ""),
"parent_namespace": "",
"parent_value": "",
"reference": item.get("reference", ""),
"source_authority": "Bluetooth SIG",
"source_file": rel,
"source_url": SIG_BASE + rel,
"source_snapshot_date": date,
"source_sha256": hashes[rel],
"safe_use_category": "public_assigned_number_metadata",
"dual_use_notes": "identifier_only",
})
for r in old_rows:
if r["source_file"] == APPEARANCE_FILE:
rows.append(dict(r, source_snapshot_date=date, source_sha256=hashes[APPEARANCE_FILE]))
rows.sort(key=lambda r: (r["assigned_number_namespace"], int(r["assigned_number_value"], 16)))
return rows
def stamp_first_seen(rows, old_rows, seed, date):
previous = {r["record_id"]: r.get(FIRST_SEEN) for r in old_rows}
return [
dict(r, **{FIRST_SEEN: previous.get(r["record_id"]) or seed.get(r["record_id"]) or date})
for r in rows
]
def build_summary(old_summary, vi):
counts = Counter((r["vendor_slug"], r["identifier_namespace"]) for r in vi)
summary = []
for s in old_summary:
v = s["vendor_slug"]
per_ns = {ns + "_count": counts[(v, ns)] for ns in VENDOR_NAMESPACES}
summary.append(dict(s, total_identifiers=sum(per_ns.values()), **per_ns))
fields = list(old_summary[0].keys())
prev = "total_identifiers"
for ns in VENDOR_NAMESPACES:
fields = with_column(fields, ns + "_count", after=prev)
prev = ns + "_count"
return summary, fields
def build_manifest(old_manifest, date, hashes, vi, bn):
template = {k: "" for k in old_manifest[0]}
by_url = {m["source_url"]: m for m in old_manifest}
sources = [("vendor_identifiers", "IEEE Registration Authority", OUI_URL)]
sources += [("vendor_identifiers", "Bluetooth SIG", SIG_BASE + rel)
for rel, *_ in SIG_VENDOR_REGISTRIES.values()]
sources += [("bluetooth_assigned_numbers", "Bluetooth SIG", SIG_BASE + rel)
for rel, _ in SIG_TABLES.values()]
sources.append(("bluetooth_assigned_numbers", "Bluetooth SIG", SIG_BASE + APPEARANCE_FILE))
manifest = []
for comp, auth, url in sources:
if url == OUI_URL:
sha = hashes["oui"]
n = sum(1 for r in vi if r["identifier_namespace"] == "ieee_oui_ma_l")
else:
rel = url[len(SIG_BASE):]
sha = hashes[rel]
ns = [k for k, v in SIG_VENDOR_REGISTRIES.items() if v[0] == rel]
if ns:
n = sum(1 for r in vi if r["identifier_namespace"] == ns[0])
else:
n = sum(1 for r in bn if r["source_file"] == rel)
base = by_url.get(url, dict(template, dataset_component=comp,
source_authority=auth, source_url=url))
manifest.append(dict(base, snapshot_date=date, source_sha256=sha, curated_records=n))
return manifest
UPSTREAM_FILES = [COMPANY_FILE, MEMBER_FILE, APPEARANCE_FILE] + [rel for rel, _ in SIG_TABLES.values()]
def upstream_urls():
"""Map local upstream file name -> download URL."""
urls = {"oui.csv": OUI_URL}
urls.update({rel.replace("/", "_"): SIG_BASE + rel for rel in UPSTREAM_FILES})
return urls
def upstream_hashes(upstream):
hashes = {rel: sha256(local_name(upstream, rel)) for rel in UPSTREAM_FILES}
hashes["oui"] = sha256(upstream / "oui.csv")
return hashes
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--upstream", required=True, type=Path)
ap.add_argument("--date", required=True)
ap.add_argument("--seed", type=Path, help="record_id,first_seen_snapshot CSV")
args = ap.parse_args()
build(upstream, date, args.seed)
def build(upstream, date, seed_path=None):
hashes = upstream_hashes(upstream)
seed = {r["record_id"]: r[FIRST_SEEN] for r in read_csv(seed_path)} if seed_path else {}
old_manifest = read_csv(DATA / "source_manifest.csv")
old_appearance_sha = {m["source_sha256"] for m in old_manifest if m["source_url"].endswith(APPEARANCE_FILE)}
if old_appearance_sha != {hashes[APPEARANCE_FILE]}:
raise SystemExit("appearance_values.yaml changed upstream; extend the builder first")
vendors = read_csv(DATA / "vendors.csv")
old_vi = read_csv(DATA / "vendor_identifiers.csv")
old_bn = read_csv(DATA / "bluetooth_assigned_numbers.csv")
vi = build_vendor_identifiers(upstream, date, VendorMatcher(vendors), hashes)
bn = build_assigned_numbers(upstream, date, old_bn, hashes)
vi = stamp_first_seen(vi, old_vi, seed, date)
bn = stamp_first_seen(bn, old_bn, seed, date)
write_csv("vendor_identifiers.csv", vi, with_column(list(old_vi[0].keys()), FIRST_SEEN))
write_csv("bluetooth_assigned_numbers.csv", bn, with_column(list(old_bn[0].keys()), FIRST_SEEN))
summary, summary_fields = build_summary(read_csv(DATA / "vendor_summary.csv"), vi)
write_csv("vendor_summary.csv", summary, summary_fields)
manifest = build_manifest(old_manifest, date, hashes, vi, bn)
write_csv("source_manifest.csv", manifest, list(old_manifest[0].keys()))
print("vendor_identifiers", len(vi), "bluetooth_assigned_numbers", len(bn))
print(Counter(r["identifier_namespace"] for r in vi))
print("first_seen", Counter(r[FIRST_SEEN] for r in vi), Counter(r[FIRST_SEEN] for r in bn))
if __name__ == "__main__":
main()