pkg-stats 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. #!/usr/bin/env python3
  2. # Copyright (C) 2009 by Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. # General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. import aiohttp
  18. import argparse
  19. import asyncio
  20. import datetime
  21. import fnmatch
  22. import os
  23. from collections import defaultdict
  24. import re
  25. import subprocess
  26. import json
  27. import sys
  28. brpath = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", ".."))
  29. sys.path.append(os.path.join(brpath, "utils"))
  30. from getdeveloperlib import parse_developers # noqa: E402
  31. import cve as cvecheck # noqa: E402
  32. INFRA_RE = re.compile(r"\$\(eval \$\(([a-z-]*)-package\)\)")
  33. URL_RE = re.compile(r"\s*https?://\S*\s*$")
  34. RM_API_STATUS_ERROR = 1
  35. RM_API_STATUS_FOUND_BY_DISTRO = 2
  36. RM_API_STATUS_FOUND_BY_PATTERN = 3
  37. RM_API_STATUS_NOT_FOUND = 4
  38. class Defconfig:
  39. def __init__(self, name, path):
  40. self.name = name
  41. self.path = path
  42. self.developers = None
  43. def set_developers(self, developers):
  44. """
  45. Fills in the .developers field
  46. """
  47. self.developers = [
  48. developer.name
  49. for developer in developers
  50. if developer.hasfile(self.path)
  51. ]
  52. def get_defconfig_list():
  53. """
  54. Builds the list of Buildroot defconfigs, returning a list of Defconfig
  55. objects.
  56. """
  57. return [
  58. Defconfig(name[:-len('_defconfig')], os.path.join('configs', name))
  59. for name in os.listdir(os.path.join(brpath, 'configs'))
  60. if name.endswith('_defconfig')
  61. ]
  62. class Package:
  63. all_licenses = dict()
  64. all_license_files = list()
  65. all_versions = dict()
  66. all_ignored_cves = dict()
  67. # This is the list of all possible checks. Add new checks to this list so
  68. # a tool that post-processeds the json output knows the checks before
  69. # iterating over the packages.
  70. status_checks = ['cve', 'developers', 'hash', 'license',
  71. 'license-files', 'patches', 'pkg-check', 'url', 'version']
  72. def __init__(self, name, path):
  73. self.name = name
  74. self.path = path
  75. self.pkg_path = os.path.dirname(path)
  76. self.infras = None
  77. self.license = None
  78. self.has_license = False
  79. self.has_license_files = False
  80. self.has_hash = False
  81. self.patch_files = []
  82. self.warnings = 0
  83. self.current_version = None
  84. self.url = None
  85. self.url_worker = None
  86. self.cves = list()
  87. self.latest_version = {'status': RM_API_STATUS_ERROR, 'version': None, 'id': None}
  88. self.status = {}
  89. def pkgvar(self):
  90. return self.name.upper().replace("-", "_")
  91. def set_url(self):
  92. """
  93. Fills in the .url field
  94. """
  95. self.status['url'] = ("warning", "no Config.in")
  96. pkgdir = os.path.dirname(os.path.join(brpath, self.path))
  97. for filename in os.listdir(pkgdir):
  98. if fnmatch.fnmatch(filename, 'Config.*'):
  99. fp = open(os.path.join(pkgdir, filename), "r")
  100. for config_line in fp:
  101. if URL_RE.match(config_line):
  102. self.url = config_line.strip()
  103. self.status['url'] = ("ok", "found")
  104. fp.close()
  105. return
  106. self.status['url'] = ("error", "missing")
  107. fp.close()
  108. @property
  109. def patch_count(self):
  110. return len(self.patch_files)
  111. @property
  112. def has_valid_infra(self):
  113. try:
  114. if self.infras[0][1] == 'virtual':
  115. return False
  116. except IndexError:
  117. return False
  118. return True
  119. def set_infra(self):
  120. """
  121. Fills in the .infras field
  122. """
  123. self.infras = list()
  124. with open(os.path.join(brpath, self.path), 'r') as f:
  125. lines = f.readlines()
  126. for l in lines:
  127. match = INFRA_RE.match(l)
  128. if not match:
  129. continue
  130. infra = match.group(1)
  131. if infra.startswith("host-"):
  132. self.infras.append(("host", infra[5:]))
  133. else:
  134. self.infras.append(("target", infra))
  135. def set_license(self):
  136. """
  137. Fills in the .status['license'] and .status['license-files'] fields
  138. """
  139. if not self.has_valid_infra:
  140. self.status['license'] = ("na", "no valid package infra")
  141. self.status['license-files'] = ("na", "no valid package infra")
  142. return
  143. var = self.pkgvar()
  144. self.status['license'] = ("error", "missing")
  145. self.status['license-files'] = ("error", "missing")
  146. if var in self.all_licenses:
  147. self.license = self.all_licenses[var]
  148. self.status['license'] = ("ok", "found")
  149. if var in self.all_license_files:
  150. self.status['license-files'] = ("ok", "found")
  151. def set_hash_info(self):
  152. """
  153. Fills in the .status['hash'] field
  154. """
  155. if not self.has_valid_infra:
  156. self.status['hash'] = ("na", "no valid package infra")
  157. self.status['hash-license'] = ("na", "no valid package infra")
  158. return
  159. hashpath = self.path.replace(".mk", ".hash")
  160. if os.path.exists(os.path.join(brpath, hashpath)):
  161. self.status['hash'] = ("ok", "found")
  162. else:
  163. self.status['hash'] = ("error", "missing")
  164. def set_patch_count(self):
  165. """
  166. Fills in the .patch_count, .patch_files and .status['patches'] fields
  167. """
  168. if not self.has_valid_infra:
  169. self.status['patches'] = ("na", "no valid package infra")
  170. return
  171. pkgdir = os.path.dirname(os.path.join(brpath, self.path))
  172. for subdir, _, _ in os.walk(pkgdir):
  173. self.patch_files = fnmatch.filter(os.listdir(subdir), '*.patch')
  174. if self.patch_count == 0:
  175. self.status['patches'] = ("ok", "no patches")
  176. elif self.patch_count < 5:
  177. self.status['patches'] = ("warning", "some patches")
  178. else:
  179. self.status['patches'] = ("error", "lots of patches")
  180. def set_current_version(self):
  181. """
  182. Fills in the .current_version field
  183. """
  184. var = self.pkgvar()
  185. if var in self.all_versions:
  186. self.current_version = self.all_versions[var]
  187. def set_check_package_warnings(self):
  188. """
  189. Fills in the .warnings and .status['pkg-check'] fields
  190. """
  191. cmd = [os.path.join(brpath, "utils/check-package")]
  192. pkgdir = os.path.dirname(os.path.join(brpath, self.path))
  193. self.status['pkg-check'] = ("error", "Missing")
  194. for root, dirs, files in os.walk(pkgdir):
  195. for f in files:
  196. if f.endswith(".mk") or f.endswith(".hash") or f == "Config.in" or f == "Config.in.host":
  197. cmd.append(os.path.join(root, f))
  198. o = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[1]
  199. lines = o.splitlines()
  200. for line in lines:
  201. m = re.match("^([0-9]*) warnings generated", line.decode())
  202. if m:
  203. self.warnings = int(m.group(1))
  204. if self.warnings == 0:
  205. self.status['pkg-check'] = ("ok", "no warnings")
  206. else:
  207. self.status['pkg-check'] = ("error", "{} warnings".format(self.warnings))
  208. return
  209. @property
  210. def ignored_cves(self):
  211. """
  212. Give the list of CVEs ignored by the package
  213. """
  214. return list(self.all_ignored_cves.get(self.pkgvar(), []))
  215. def set_developers(self, developers):
  216. """
  217. Fills in the .developers and .status['developers'] field
  218. """
  219. self.developers = [
  220. dev.name
  221. for dev in developers
  222. if dev.hasfile(self.path)
  223. ]
  224. if self.developers:
  225. self.status['developers'] = ("ok", "{} developers".format(len(self.developers)))
  226. else:
  227. self.status['developers'] = ("warning", "no developers")
  228. def is_status_ok(self, name):
  229. return self.status[name][0] == 'ok'
  230. def __eq__(self, other):
  231. return self.path == other.path
  232. def __lt__(self, other):
  233. return self.path < other.path
  234. def __str__(self):
  235. return "%s (path='%s', license='%s', license_files='%s', hash='%s', patches=%d)" % \
  236. (self.name, self.path, self.is_status_ok('license'),
  237. self.is_status_ok('license-files'), self.status['hash'], self.patch_count)
  238. def get_pkglist(npackages, package_list):
  239. """
  240. Builds the list of Buildroot packages, returning a list of Package
  241. objects. Only the .name and .path fields of the Package object are
  242. initialized.
  243. npackages: limit to N packages
  244. package_list: limit to those packages in this list
  245. """
  246. WALK_USEFUL_SUBDIRS = ["boot", "linux", "package", "toolchain"]
  247. WALK_EXCLUDES = ["boot/common.mk",
  248. "linux/linux-ext-.*.mk",
  249. "package/freescale-imx/freescale-imx.mk",
  250. "package/gcc/gcc.mk",
  251. "package/gstreamer/gstreamer.mk",
  252. "package/gstreamer1/gstreamer1.mk",
  253. "package/gtk2-themes/gtk2-themes.mk",
  254. "package/matchbox/matchbox.mk",
  255. "package/opengl/opengl.mk",
  256. "package/qt5/qt5.mk",
  257. "package/x11r7/x11r7.mk",
  258. "package/doc-asciidoc.mk",
  259. "package/pkg-.*.mk",
  260. "toolchain/toolchain-external/pkg-toolchain-external.mk",
  261. "toolchain/toolchain-external/toolchain-external.mk",
  262. "toolchain/toolchain.mk",
  263. "toolchain/helpers.mk",
  264. "toolchain/toolchain-wrapper.mk"]
  265. packages = list()
  266. count = 0
  267. for root, dirs, files in os.walk(brpath):
  268. root = os.path.relpath(root, brpath)
  269. rootdir = root.split("/")
  270. if len(rootdir) < 1:
  271. continue
  272. if rootdir[0] not in WALK_USEFUL_SUBDIRS:
  273. continue
  274. for f in files:
  275. if not f.endswith(".mk"):
  276. continue
  277. # Strip ending ".mk"
  278. pkgname = f[:-3]
  279. if package_list and pkgname not in package_list:
  280. continue
  281. pkgpath = os.path.join(root, f)
  282. skip = False
  283. for exclude in WALK_EXCLUDES:
  284. if re.match(exclude, pkgpath):
  285. skip = True
  286. continue
  287. if skip:
  288. continue
  289. p = Package(pkgname, pkgpath)
  290. packages.append(p)
  291. count += 1
  292. if npackages and count == npackages:
  293. return packages
  294. return packages
  295. def get_config_packages():
  296. cmd = ["make", "--no-print-directory", "show-info"]
  297. js = json.loads(subprocess.check_output(cmd))
  298. return js.keys()
  299. def package_init_make_info():
  300. # Fetch all variables at once
  301. variables = subprocess.check_output(["make", "BR2_HAVE_DOT_CONFIG=y", "-s", "printvars",
  302. "VARS=%_LICENSE %_LICENSE_FILES %_VERSION %_IGNORE_CVES"])
  303. variable_list = variables.decode().splitlines()
  304. # We process first the host package VERSION, and then the target
  305. # package VERSION. This means that if a package exists in both
  306. # target and host variants, with different values (eg. version
  307. # numbers (unlikely)), we'll report the target one.
  308. variable_list = [x[5:] for x in variable_list if x.startswith("HOST_")] + \
  309. [x for x in variable_list if not x.startswith("HOST_")]
  310. for l in variable_list:
  311. # Get variable name and value
  312. pkgvar, value = l.split("=")
  313. # Strip the suffix according to the variable
  314. if pkgvar.endswith("_LICENSE"):
  315. # If value is "unknown", no license details available
  316. if value == "unknown":
  317. continue
  318. pkgvar = pkgvar[:-8]
  319. Package.all_licenses[pkgvar] = value
  320. elif pkgvar.endswith("_LICENSE_FILES"):
  321. if pkgvar.endswith("_MANIFEST_LICENSE_FILES"):
  322. continue
  323. pkgvar = pkgvar[:-14]
  324. Package.all_license_files.append(pkgvar)
  325. elif pkgvar.endswith("_VERSION"):
  326. if pkgvar.endswith("_DL_VERSION"):
  327. continue
  328. pkgvar = pkgvar[:-8]
  329. Package.all_versions[pkgvar] = value
  330. elif pkgvar.endswith("_IGNORE_CVES"):
  331. pkgvar = pkgvar[:-12]
  332. Package.all_ignored_cves[pkgvar] = value.split()
  333. check_url_count = 0
  334. async def check_url_status(session, pkg, npkgs, retry=True):
  335. global check_url_count
  336. try:
  337. async with session.get(pkg.url) as resp:
  338. if resp.status >= 400:
  339. pkg.status['url'] = ("error", "invalid {}".format(resp.status))
  340. check_url_count += 1
  341. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  342. return
  343. except (aiohttp.ClientError, asyncio.TimeoutError):
  344. if retry:
  345. return await check_url_status(session, pkg, npkgs, retry=False)
  346. else:
  347. pkg.status['url'] = ("error", "invalid (err)")
  348. check_url_count += 1
  349. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  350. return
  351. pkg.status['url'] = ("ok", "valid")
  352. check_url_count += 1
  353. print("[%04d/%04d] %s" % (check_url_count, npkgs, pkg.name))
  354. async def check_package_urls(packages):
  355. tasks = []
  356. connector = aiohttp.TCPConnector(limit_per_host=5)
  357. async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
  358. packages = [p for p in packages if p.status['url'][0] == 'ok']
  359. for pkg in packages:
  360. tasks.append(check_url_status(sess, pkg, len(packages)))
  361. await asyncio.wait(tasks)
  362. def check_package_latest_version_set_status(pkg, status, version, identifier):
  363. pkg.latest_version = {
  364. "status": status,
  365. "version": version,
  366. "id": identifier,
  367. }
  368. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  369. pkg.status['version'] = ('warning', "Release Monitoring API error")
  370. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  371. pkg.status['version'] = ('warning', "Package not found on Release Monitoring")
  372. if pkg.latest_version['version'] is None:
  373. pkg.status['version'] = ('warning', "No upstream version available on Release Monitoring")
  374. elif pkg.latest_version['version'] != pkg.current_version:
  375. pkg.status['version'] = ('error', "The newer version {} is available upstream".format(pkg.latest_version['version']))
  376. else:
  377. pkg.status['version'] = ('ok', 'up-to-date')
  378. async def check_package_get_latest_version_by_distro(session, pkg, retry=True):
  379. url = "https://release-monitoring.org//api/project/Buildroot/%s" % pkg.name
  380. try:
  381. async with session.get(url) as resp:
  382. if resp.status != 200:
  383. return False
  384. data = await resp.json()
  385. version = data['version'] if 'version' in data else None
  386. check_package_latest_version_set_status(pkg,
  387. RM_API_STATUS_FOUND_BY_DISTRO,
  388. version,
  389. data['id'])
  390. return True
  391. except (aiohttp.ClientError, asyncio.TimeoutError):
  392. if retry:
  393. return await check_package_get_latest_version_by_distro(session, pkg, retry=False)
  394. else:
  395. return False
  396. async def check_package_get_latest_version_by_guess(session, pkg, retry=True):
  397. url = "https://release-monitoring.org/api/projects/?pattern=%s" % pkg.name
  398. try:
  399. async with session.get(url) as resp:
  400. if resp.status != 200:
  401. return False
  402. data = await resp.json()
  403. # filter projects that have the right name and a version defined
  404. projects = [p for p in data['projects'] if p['name'] == pkg.name and 'version' in p]
  405. projects.sort(key=lambda x: x['id'])
  406. if len(projects) > 0:
  407. check_package_latest_version_set_status(pkg,
  408. RM_API_STATUS_FOUND_BY_DISTRO,
  409. projects[0]['version'],
  410. projects[0]['id'])
  411. return True
  412. except (aiohttp.ClientError, asyncio.TimeoutError):
  413. if retry:
  414. return await check_package_get_latest_version_by_guess(session, pkg, retry=False)
  415. else:
  416. return False
  417. check_latest_count = 0
  418. async def check_package_latest_version_get(session, pkg, npkgs):
  419. global check_latest_count
  420. if await check_package_get_latest_version_by_distro(session, pkg):
  421. check_latest_count += 1
  422. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  423. return
  424. if await check_package_get_latest_version_by_guess(session, pkg):
  425. check_latest_count += 1
  426. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  427. return
  428. check_package_latest_version_set_status(pkg,
  429. RM_API_STATUS_NOT_FOUND,
  430. None, None)
  431. check_latest_count += 1
  432. print("[%04d/%04d] %s" % (check_latest_count, npkgs, pkg.name))
  433. async def check_package_latest_version(packages):
  434. """
  435. Fills in the .latest_version field of all Package objects
  436. This field is a dict and has the following keys:
  437. - status: one of RM_API_STATUS_ERROR,
  438. RM_API_STATUS_FOUND_BY_DISTRO, RM_API_STATUS_FOUND_BY_PATTERN,
  439. RM_API_STATUS_NOT_FOUND
  440. - version: string containing the latest version known by
  441. release-monitoring.org for this package
  442. - id: string containing the id of the project corresponding to this
  443. package, as known by release-monitoring.org
  444. """
  445. for pkg in [p for p in packages if not p.has_valid_infra]:
  446. pkg.status['version'] = ("na", "no valid package infra")
  447. tasks = []
  448. connector = aiohttp.TCPConnector(limit_per_host=5)
  449. async with aiohttp.ClientSession(connector=connector, trust_env=True) as sess:
  450. packages = [p for p in packages if p.has_valid_infra]
  451. for pkg in packages:
  452. tasks.append(check_package_latest_version_get(sess, pkg, len(packages)))
  453. await asyncio.wait(tasks)
  454. def check_package_cves(nvd_path, packages):
  455. if not os.path.isdir(nvd_path):
  456. os.makedirs(nvd_path)
  457. for cve in cvecheck.CVE.read_nvd_dir(nvd_path):
  458. for pkg_name in cve.pkg_names:
  459. if pkg_name in packages:
  460. pkg = packages[pkg_name]
  461. if cve.affects(pkg.name, pkg.current_version, pkg.ignored_cves) == cve.CVE_AFFECTS:
  462. pkg.cves.append(cve.identifier)
  463. def calculate_stats(packages):
  464. stats = defaultdict(int)
  465. stats['packages'] = len(packages)
  466. for pkg in packages:
  467. # If packages have multiple infra, take the first one. For the
  468. # vast majority of packages, the target and host infra are the
  469. # same. There are very few packages that use a different infra
  470. # for the host and target variants.
  471. if len(pkg.infras) > 0:
  472. infra = pkg.infras[0][1]
  473. stats["infra-%s" % infra] += 1
  474. else:
  475. stats["infra-unknown"] += 1
  476. if pkg.is_status_ok('license'):
  477. stats["license"] += 1
  478. else:
  479. stats["no-license"] += 1
  480. if pkg.is_status_ok('license-files'):
  481. stats["license-files"] += 1
  482. else:
  483. stats["no-license-files"] += 1
  484. if pkg.is_status_ok('hash'):
  485. stats["hash"] += 1
  486. else:
  487. stats["no-hash"] += 1
  488. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  489. stats["rmo-mapping"] += 1
  490. else:
  491. stats["rmo-no-mapping"] += 1
  492. if not pkg.latest_version['version']:
  493. stats["version-unknown"] += 1
  494. elif pkg.latest_version['version'] == pkg.current_version:
  495. stats["version-uptodate"] += 1
  496. else:
  497. stats["version-not-uptodate"] += 1
  498. stats["patches"] += pkg.patch_count
  499. stats["total-cves"] += len(pkg.cves)
  500. if len(pkg.cves) != 0:
  501. stats["pkg-cves"] += 1
  502. return stats
  503. html_header = """
  504. <head>
  505. <script src=\"https://www.kryogenix.org/code/browser/sorttable/sorttable.js\"></script>
  506. <style type=\"text/css\">
  507. table {
  508. width: 100%;
  509. }
  510. td {
  511. border: 1px solid black;
  512. }
  513. td.centered {
  514. text-align: center;
  515. }
  516. td.wrong {
  517. background: #ff9a69;
  518. }
  519. td.correct {
  520. background: #d2ffc4;
  521. }
  522. td.nopatches {
  523. background: #d2ffc4;
  524. }
  525. td.somepatches {
  526. background: #ffd870;
  527. }
  528. td.lotsofpatches {
  529. background: #ff9a69;
  530. }
  531. td.good_url {
  532. background: #d2ffc4;
  533. }
  534. td.missing_url {
  535. background: #ffd870;
  536. }
  537. td.invalid_url {
  538. background: #ff9a69;
  539. }
  540. td.version-good {
  541. background: #d2ffc4;
  542. }
  543. td.version-needs-update {
  544. background: #ff9a69;
  545. }
  546. td.version-unknown {
  547. background: #ffd870;
  548. }
  549. td.version-error {
  550. background: #ccc;
  551. }
  552. </style>
  553. <title>Statistics of Buildroot packages</title>
  554. </head>
  555. <a href=\"#results\">Results</a><br/>
  556. <p id=\"sortable_hint\"></p>
  557. """
  558. html_footer = """
  559. </body>
  560. <script>
  561. if (typeof sorttable === \"object\") {
  562. document.getElementById(\"sortable_hint\").innerHTML =
  563. \"hint: the table can be sorted by clicking the column headers\"
  564. }
  565. </script>
  566. </html>
  567. """
  568. def infra_str(infra_list):
  569. if not infra_list:
  570. return "Unknown"
  571. elif len(infra_list) == 1:
  572. return "<b>%s</b><br/>%s" % (infra_list[0][1], infra_list[0][0])
  573. elif infra_list[0][1] == infra_list[1][1]:
  574. return "<b>%s</b><br/>%s + %s" % \
  575. (infra_list[0][1], infra_list[0][0], infra_list[1][0])
  576. else:
  577. return "<b>%s</b> (%s)<br/><b>%s</b> (%s)" % \
  578. (infra_list[0][1], infra_list[0][0],
  579. infra_list[1][1], infra_list[1][0])
  580. def boolean_str(b):
  581. if b:
  582. return "Yes"
  583. else:
  584. return "No"
  585. def dump_html_pkg(f, pkg):
  586. f.write(" <tr>\n")
  587. f.write(" <td>%s</td>\n" % pkg.path)
  588. # Patch count
  589. td_class = ["centered"]
  590. if pkg.patch_count == 0:
  591. td_class.append("nopatches")
  592. elif pkg.patch_count < 5:
  593. td_class.append("somepatches")
  594. else:
  595. td_class.append("lotsofpatches")
  596. f.write(" <td class=\"%s\">%s</td>\n" %
  597. (" ".join(td_class), str(pkg.patch_count)))
  598. # Infrastructure
  599. infra = infra_str(pkg.infras)
  600. td_class = ["centered"]
  601. if infra == "Unknown":
  602. td_class.append("wrong")
  603. else:
  604. td_class.append("correct")
  605. f.write(" <td class=\"%s\">%s</td>\n" %
  606. (" ".join(td_class), infra_str(pkg.infras)))
  607. # License
  608. td_class = ["centered"]
  609. if pkg.is_status_ok('license'):
  610. td_class.append("correct")
  611. else:
  612. td_class.append("wrong")
  613. f.write(" <td class=\"%s\">%s</td>\n" %
  614. (" ".join(td_class), boolean_str(pkg.is_status_ok('license'))))
  615. # License files
  616. td_class = ["centered"]
  617. if pkg.is_status_ok('license-files'):
  618. td_class.append("correct")
  619. else:
  620. td_class.append("wrong")
  621. f.write(" <td class=\"%s\">%s</td>\n" %
  622. (" ".join(td_class), boolean_str(pkg.is_status_ok('license-files'))))
  623. # Hash
  624. td_class = ["centered"]
  625. if pkg.is_status_ok('hash'):
  626. td_class.append("correct")
  627. else:
  628. td_class.append("wrong")
  629. f.write(" <td class=\"%s\">%s</td>\n" %
  630. (" ".join(td_class), boolean_str(pkg.is_status_ok('hash'))))
  631. # Current version
  632. if len(pkg.current_version) > 20:
  633. current_version = pkg.current_version[:20] + "..."
  634. else:
  635. current_version = pkg.current_version
  636. f.write(" <td class=\"centered\">%s</td>\n" % current_version)
  637. # Latest version
  638. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  639. td_class.append("version-error")
  640. if pkg.latest_version['version'] is None:
  641. td_class.append("version-unknown")
  642. elif pkg.latest_version['version'] != pkg.current_version:
  643. td_class.append("version-needs-update")
  644. else:
  645. td_class.append("version-good")
  646. if pkg.latest_version['status'] == RM_API_STATUS_ERROR:
  647. latest_version_text = "<b>Error</b>"
  648. elif pkg.latest_version['status'] == RM_API_STATUS_NOT_FOUND:
  649. latest_version_text = "<b>Not found</b>"
  650. else:
  651. if pkg.latest_version['version'] is None:
  652. latest_version_text = "<b>Found, but no version</b>"
  653. else:
  654. latest_version_text = "<a href=\"https://release-monitoring.org/project/%s\"><b>%s</b></a>" % \
  655. (pkg.latest_version['id'], str(pkg.latest_version['version']))
  656. latest_version_text += "<br/>"
  657. if pkg.latest_version['status'] == RM_API_STATUS_FOUND_BY_DISTRO:
  658. latest_version_text += "found by <a href=\"https://release-monitoring.org/distro/Buildroot/\">distro</a>"
  659. else:
  660. latest_version_text += "found by guess"
  661. f.write(" <td class=\"%s\">%s</td>\n" %
  662. (" ".join(td_class), latest_version_text))
  663. # Warnings
  664. td_class = ["centered"]
  665. if pkg.warnings == 0:
  666. td_class.append("correct")
  667. else:
  668. td_class.append("wrong")
  669. f.write(" <td class=\"%s\">%d</td>\n" %
  670. (" ".join(td_class), pkg.warnings))
  671. # URL status
  672. td_class = ["centered"]
  673. url_str = pkg.status['url'][1]
  674. if pkg.status['url'][0] in ("error", "warning"):
  675. td_class.append("missing_url")
  676. if pkg.status['url'][0] == "error":
  677. td_class.append("invalid_url")
  678. url_str = "<a href=%s>%s</a>" % (pkg.url, pkg.status['url'][1])
  679. else:
  680. td_class.append("good_url")
  681. url_str = "<a href=%s>Link</a>" % pkg.url
  682. f.write(" <td class=\"%s\">%s</td>\n" %
  683. (" ".join(td_class), url_str))
  684. # CVEs
  685. td_class = ["centered"]
  686. if len(pkg.cves) == 0:
  687. td_class.append("correct")
  688. else:
  689. td_class.append("wrong")
  690. f.write(" <td class=\"%s\">\n" % " ".join(td_class))
  691. for cve in pkg.cves:
  692. f.write(" <a href=\"https://security-tracker.debian.org/tracker/%s\">%s<br/>\n" % (cve, cve))
  693. f.write(" </td>\n")
  694. f.write(" </tr>\n")
  695. def dump_html_all_pkgs(f, packages):
  696. f.write("""
  697. <table class=\"sortable\">
  698. <tr>
  699. <td>Package</td>
  700. <td class=\"centered\">Patch count</td>
  701. <td class=\"centered\">Infrastructure</td>
  702. <td class=\"centered\">License</td>
  703. <td class=\"centered\">License files</td>
  704. <td class=\"centered\">Hash file</td>
  705. <td class=\"centered\">Current version</td>
  706. <td class=\"centered\">Latest version</td>
  707. <td class=\"centered\">Warnings</td>
  708. <td class=\"centered\">Upstream URL</td>
  709. <td class=\"centered\">CVEs</td>
  710. </tr>
  711. """)
  712. for pkg in sorted(packages):
  713. dump_html_pkg(f, pkg)
  714. f.write("</table>")
  715. def dump_html_stats(f, stats):
  716. f.write("<a id=\"results\"></a>\n")
  717. f.write("<table>\n")
  718. infras = [infra[6:] for infra in stats.keys() if infra.startswith("infra-")]
  719. for infra in infras:
  720. f.write(" <tr><td>Packages using the <i>%s</i> infrastructure</td><td>%s</td></tr>\n" %
  721. (infra, stats["infra-%s" % infra]))
  722. f.write(" <tr><td>Packages having license information</td><td>%s</td></tr>\n" %
  723. stats["license"])
  724. f.write(" <tr><td>Packages not having license information</td><td>%s</td></tr>\n" %
  725. stats["no-license"])
  726. f.write(" <tr><td>Packages having license files information</td><td>%s</td></tr>\n" %
  727. stats["license-files"])
  728. f.write(" <tr><td>Packages not having license files information</td><td>%s</td></tr>\n" %
  729. stats["no-license-files"])
  730. f.write(" <tr><td>Packages having a hash file</td><td>%s</td></tr>\n" %
  731. stats["hash"])
  732. f.write(" <tr><td>Packages not having a hash file</td><td>%s</td></tr>\n" %
  733. stats["no-hash"])
  734. f.write(" <tr><td>Total number of patches</td><td>%s</td></tr>\n" %
  735. stats["patches"])
  736. f.write("<tr><td>Packages having a mapping on <i>release-monitoring.org</i></td><td>%s</td></tr>\n" %
  737. stats["rmo-mapping"])
  738. f.write("<tr><td>Packages lacking a mapping on <i>release-monitoring.org</i></td><td>%s</td></tr>\n" %
  739. stats["rmo-no-mapping"])
  740. f.write("<tr><td>Packages that are up-to-date</td><td>%s</td></tr>\n" %
  741. stats["version-uptodate"])
  742. f.write("<tr><td>Packages that are not up-to-date</td><td>%s</td></tr>\n" %
  743. stats["version-not-uptodate"])
  744. f.write("<tr><td>Packages with no known upstream version</td><td>%s</td></tr>\n" %
  745. stats["version-unknown"])
  746. f.write("<tr><td>Packages affected by CVEs</td><td>%s</td></tr>\n" %
  747. stats["pkg-cves"])
  748. f.write("<tr><td>Total number of CVEs affecting all packages</td><td>%s</td></tr>\n" %
  749. stats["total-cves"])
  750. f.write("</table>\n")
  751. def dump_html_gen_info(f, date, commit):
  752. # Updated on Mon Feb 19 08:12:08 CET 2018, Git commit aa77030b8f5e41f1c53eb1c1ad664b8c814ba032
  753. f.write("<p><i>Updated on %s, git commit %s</i></p>\n" % (str(date), commit))
  754. def dump_html(packages, stats, date, commit, output):
  755. with open(output, 'w') as f:
  756. f.write(html_header)
  757. dump_html_all_pkgs(f, packages)
  758. dump_html_stats(f, stats)
  759. dump_html_gen_info(f, date, commit)
  760. f.write(html_footer)
  761. def dump_json(packages, defconfigs, stats, date, commit, output):
  762. # Format packages as a dictionnary instead of a list
  763. # Exclude local field that does not contains real date
  764. excluded_fields = ['url_worker', 'name']
  765. pkgs = {
  766. pkg.name: {
  767. k: v
  768. for k, v in pkg.__dict__.items()
  769. if k not in excluded_fields
  770. } for pkg in packages
  771. }
  772. defconfigs = {
  773. d.name: {
  774. k: v
  775. for k, v in d.__dict__.items()
  776. } for d in defconfigs
  777. }
  778. # Aggregate infrastructures into a single dict entry
  779. statistics = {
  780. k: v
  781. for k, v in stats.items()
  782. if not k.startswith('infra-')
  783. }
  784. statistics['infra'] = {k[6:]: v for k, v in stats.items() if k.startswith('infra-')}
  785. # The actual structure to dump, add commit and date to it
  786. final = {'packages': pkgs,
  787. 'stats': statistics,
  788. 'defconfigs': defconfigs,
  789. 'package_status_checks': Package.status_checks,
  790. 'commit': commit,
  791. 'date': str(date)}
  792. with open(output, 'w') as f:
  793. json.dump(final, f, indent=2, separators=(',', ': '))
  794. f.write('\n')
  795. def resolvepath(path):
  796. return os.path.abspath(os.path.expanduser(path))
  797. def parse_args():
  798. parser = argparse.ArgumentParser()
  799. output = parser.add_argument_group('output', 'Output file(s)')
  800. output.add_argument('--html', dest='html', type=resolvepath,
  801. help='HTML output file')
  802. output.add_argument('--json', dest='json', type=resolvepath,
  803. help='JSON output file')
  804. packages = parser.add_mutually_exclusive_group()
  805. packages.add_argument('-c', dest='configpackages', action='store_true',
  806. help='Apply to packages enabled in current configuration')
  807. packages.add_argument('-n', dest='npackages', type=int, action='store',
  808. help='Number of packages')
  809. packages.add_argument('-p', dest='packages', action='store',
  810. help='List of packages (comma separated)')
  811. parser.add_argument('--nvd-path', dest='nvd_path',
  812. help='Path to the local NVD database', type=resolvepath)
  813. args = parser.parse_args()
  814. if not args.html and not args.json:
  815. parser.error('at least one of --html or --json (or both) is required')
  816. return args
  817. def __main__():
  818. args = parse_args()
  819. if args.packages:
  820. package_list = args.packages.split(",")
  821. elif args.configpackages:
  822. package_list = get_config_packages()
  823. else:
  824. package_list = None
  825. date = datetime.datetime.utcnow()
  826. commit = subprocess.check_output(['git', '-C', brpath,
  827. 'rev-parse',
  828. 'HEAD']).splitlines()[0].decode()
  829. print("Build package list ...")
  830. packages = get_pkglist(args.npackages, package_list)
  831. print("Getting developers ...")
  832. developers = parse_developers(brpath)
  833. print("Build defconfig list ...")
  834. defconfigs = get_defconfig_list()
  835. for d in defconfigs:
  836. d.set_developers(developers)
  837. print("Getting package make info ...")
  838. package_init_make_info()
  839. print("Getting package details ...")
  840. for pkg in packages:
  841. pkg.set_infra()
  842. pkg.set_license()
  843. pkg.set_hash_info()
  844. pkg.set_patch_count()
  845. pkg.set_check_package_warnings()
  846. pkg.set_current_version()
  847. pkg.set_url()
  848. pkg.set_developers(developers)
  849. print("Checking URL status")
  850. loop = asyncio.get_event_loop()
  851. loop.run_until_complete(check_package_urls(packages))
  852. print("Getting latest versions ...")
  853. loop = asyncio.get_event_loop()
  854. loop.run_until_complete(check_package_latest_version(packages))
  855. if args.nvd_path:
  856. print("Checking packages CVEs")
  857. check_package_cves(args.nvd_path, {p.name: p for p in packages})
  858. print("Calculate stats")
  859. stats = calculate_stats(packages)
  860. if args.html:
  861. print("Write HTML")
  862. dump_html(packages, stats, date, commit, args.html)
  863. if args.json:
  864. print("Write JSON")
  865. dump_json(packages, defconfigs, stats, date, commit, args.json)
  866. __main__()