pkg-stats 34 KB

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