Devuan deployment of britney2
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1499 lines
70 KiB

  1. #!/usr/bin/python3 -u
  2. # -*- coding: utf-8 -*-
  3. # Copyright (C) 2001-2008 Anthony Towns <ajt@debian.org>
  4. # Andreas Barth <aba@debian.org>
  5. # Fabio Tranchitella <kobold@debian.org>
  6. # Copyright (C) 2010-2013 Adam D. Barratt <adsb@debian.org>
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. """
  16. = Introduction =
  17. This is the Debian testing updater script, also known as "Britney".
  18. Packages are usually installed into the `testing' distribution after
  19. they have undergone some degree of testing in unstable. The goal of
  20. this software is to do this task in a smart way, allowing testing
  21. to always be fully installable and close to being a release candidate.
  22. Britney's source code is split between two different but related tasks:
  23. the first one is the generation of the update excuses, while the
  24. second tries to update testing with the valid candidates; first
  25. each package alone, then larger and even larger sets of packages
  26. together. Each try is accepted if testing is not more uninstallable
  27. after the update than before.
  28. = Data Loading =
  29. In order to analyze the entire Debian distribution, Britney needs to
  30. load in memory the whole archive: this means more than 10.000 packages
  31. for twelve architectures, as well as the dependency interconnections
  32. between them. For this reason, the memory requirements for running this
  33. software are quite high and at least 1 gigabyte of RAM should be available.
  34. Britney loads the source packages from the `Sources' file and the binary
  35. packages from the `Packages_${arch}' files, where ${arch} is substituted
  36. with the supported architectures. While loading the data, the software
  37. analyzes the dependencies and builds a directed weighted graph in memory
  38. with all the interconnections between the packages (see Britney.read_sources
  39. and Britney.read_binaries).
  40. Other than source and binary packages, Britney loads the following data:
  41. * BugsV, which contains the list of release-critical bugs for a given
  42. version of a source or binary package (see RCBugPolicy.read_bugs).
  43. * Dates, which contains the date of the upload of a given version
  44. of a source package (see Britney.read_dates).
  45. * Urgencies, which contains the urgency of the upload of a given
  46. version of a source package (see AgePolicy._read_urgencies).
  47. * Hints, which contains lists of commands which modify the standard behaviour
  48. of Britney (see Britney.read_hints).
  49. For a more detailed explanation about the format of these files, please read
  50. the documentation of the related methods. The exact meaning of them will be
  51. instead explained in the chapter "Excuses Generation".
  52. = Excuses =
  53. An excuse is a detailed explanation of why a package can or cannot
  54. be updated in the testing distribution from a newer package in
  55. another distribution (like for example unstable). The main purpose
  56. of the excuses is to be written in an HTML file which will be
  57. published over HTTP. The maintainers will be able to parse it manually
  58. or automatically to find the explanation of why their packages have
  59. been updated or not.
  60. == Excuses generation ==
  61. These are the steps (with references to method names) that Britney
  62. does for the generation of the update excuses.
  63. * If a source package is available in testing but it is not
  64. present in unstable and no binary packages in unstable are
  65. built from it, then it is marked for removal.
  66. * Every source package in unstable and testing-proposed-updates,
  67. if already present in testing, is checked for binary-NMUs, new
  68. or dropped binary packages in all the supported architectures
  69. (see Britney.should_upgrade_srcarch). The steps to detect if an
  70. upgrade is needed are:
  71. 1. If there is a `remove' hint for the source package, the package
  72. is ignored: it will be removed and not updated.
  73. 2. For every binary package built from the new source, it checks
  74. for unsatisfied dependencies, new binary packages and updated
  75. binary packages (binNMU), excluding the architecture-independent
  76. ones, and packages not built from the same source.
  77. 3. For every binary package built from the old source, it checks
  78. if it is still built from the new source; if this is not true
  79. and the package is not architecture-independent, the script
  80. removes it from testing.
  81. 4. Finally, if there is something worth doing (eg. a new or updated
  82. binary package) and nothing wrong it marks the source package
  83. as "Valid candidate", or "Not considered" if there is something
  84. wrong which prevented the update.
  85. * Every source package in unstable and testing-proposed-updates is
  86. checked for upgrade (see Britney.should_upgrade_src). The steps
  87. to detect if an upgrade is needed are:
  88. 1. If the source package in testing is more recent the new one
  89. is ignored.
  90. 2. If the source package doesn't exist (is fake), which means that
  91. a binary package refers to it but it is not present in the
  92. `Sources' file, the new one is ignored.
  93. 3. If the package doesn't exist in testing, the urgency of the
  94. upload is ignored and set to the default (actually `low').
  95. 4. If there is a `remove' hint for the source package, the package
  96. is ignored: it will be removed and not updated.
  97. 5. If there is a `block' hint for the source package without an
  98. `unblock` hint or a `block-all source`, the package is ignored.
  99. 6. If there is a `block-udeb' hint for the source package, it will
  100. have the same effect as `block', but may only be cancelled by
  101. a subsequent `unblock-udeb' hint.
  102. 7. If the suite is unstable, the update can go ahead only if the
  103. upload happened more than the minimum days specified by the
  104. urgency of the upload; if this is not true, the package is
  105. ignored as `too-young'. Note that the urgency is sticky, meaning
  106. that the highest urgency uploaded since the previous testing
  107. transition is taken into account.
  108. 8. If the suite is unstable, all the architecture-dependent binary
  109. packages and the architecture-independent ones for the `nobreakall'
  110. architectures have to be built from the source we are considering.
  111. If this is not true, then these are called `out-of-date'
  112. architectures and the package is ignored.
  113. 9. The source package must have at least one binary package, otherwise
  114. it is ignored.
  115. 10. If the suite is unstable, the new source package must have no
  116. release critical bugs which do not also apply to the testing
  117. one. If this is not true, the package is ignored as `buggy'.
  118. 11. If there is a `force' hint for the source package, then it is
  119. updated even if it is marked as ignored from the previous steps.
  120. 12. If the suite is {testing-,}proposed-updates, the source package can
  121. be updated only if there is an explicit approval for it. Unless
  122. a `force' hint exists, the new package must also be available
  123. on all of the architectures for which it has binary packages in
  124. testing.
  125. 13. If the package will be ignored, mark it as "Valid candidate",
  126. otherwise mark it as "Not considered".
  127. * The list of `remove' hints is processed: if the requested source
  128. package is not already being updated or removed and the version
  129. actually in testing is the same specified with the `remove' hint,
  130. it is marked for removal.
  131. * The excuses are sorted by the number of days from the last upload
  132. (days-old) and by name.
  133. * A list of unconsidered excuses (for which the package is not upgraded)
  134. is built. Using this list, all of the excuses depending on them are
  135. marked as invalid "impossible dependencies".
  136. * The excuses are written in an HTML file.
  137. """
  138. import contextlib
  139. import logging
  140. import optparse
  141. import os
  142. import sys
  143. import time
  144. from collections import defaultdict
  145. from functools import reduce
  146. from itertools import chain
  147. from operator import attrgetter
  148. import apt_pkg
  149. from britney2 import SourcePackage, BinaryPackageId, BinaryPackage
  150. from britney2.excusefinder import ExcuseFinder
  151. from britney2.hints import HintParser
  152. from britney2.inputs.suiteloader import DebMirrorLikeSuiteContentLoader, MissingRequiredConfigurationError
  153. from britney2.installability.builder import build_installability_tester
  154. from britney2.installability.solver import InstallabilitySolver
  155. from britney2.migration import MigrationManager
  156. from britney2.migrationitem import MigrationItemFactory
  157. from britney2.policies.policy import (AgePolicy, RCBugPolicy, PiupartsPolicy, BuildDependsPolicy, PolicyEngine,
  158. BlockPolicy, BuiltUsingPolicy, BuiltOnBuilddPolicy)
  159. from britney2.policies.autopkgtest import AutopkgtestPolicy
  160. from britney2.utils import (log_and_format_old_libraries,
  161. read_nuninst, write_nuninst, write_heidi,
  162. format_and_log_uninst, newly_uninst,
  163. write_excuses, write_heidi_delta,
  164. old_libraries, is_nuninst_asgood_generous,
  165. clone_nuninst, compile_nuninst, parse_provides,
  166. MigrationConstraintException,
  167. )
  168. __author__ = 'Fabio Tranchitella and the Debian Release Team'
  169. __version__ = '2.0'
  170. class Britney(object):
  171. """Britney, the Debian testing updater script
  172. This is the script that updates the testing distribution. It is executed
  173. each day after the installation of the updated packages. It generates the
  174. `Packages' files for the testing distribution, but it does so in an
  175. intelligent manner; it tries to avoid any inconsistency and to use only
  176. non-buggy packages.
  177. For more documentation on this script, please read the Developers Reference.
  178. """
  179. HINTS_HELPERS = ("easy", "hint", "remove", "block", "block-udeb", "unblock", "unblock-udeb", "approve",
  180. "remark", "ignore-piuparts", "ignore-rc-bugs", "force-skiptest", "force-badtest")
  181. HINTS_STANDARD = ("urgent", "age-days") + HINTS_HELPERS
  182. # ALL = {"force", "force-hint", "block-all"} | HINTS_STANDARD | registered policy hints (not covered above)
  183. HINTS_ALL = ('ALL')
  184. def __init__(self):
  185. """Class constructor
  186. This method initializes and populates the data lists, which contain all
  187. the information needed by the other methods of the class.
  188. """
  189. # setup logging - provide the "short level name" (i.e. INFO -> I) that
  190. # we used to use prior to using the logging module.
  191. old_factory = logging.getLogRecordFactory()
  192. short_level_mapping = {
  193. 'CRITICAL': 'F',
  194. 'INFO': 'I',
  195. 'WARNING': 'W',
  196. 'ERROR': 'E',
  197. 'DEBUG': 'N',
  198. }
  199. def record_factory(*args, **kwargs): # pragma: no cover
  200. record = old_factory(*args, **kwargs)
  201. try:
  202. record.shortlevelname = short_level_mapping[record.levelname]
  203. except KeyError:
  204. record.shortlevelname = record.levelname
  205. return record
  206. logging.setLogRecordFactory(record_factory)
  207. logging.basicConfig(format='{shortlevelname}: [{asctime}] - {message}',
  208. style='{',
  209. datefmt="%Y-%m-%dT%H:%M:%S%z",
  210. stream=sys.stdout,
  211. )
  212. self.logger = logging.getLogger()
  213. # Logger for "upgrade_output"; the file handler will be attached later when
  214. # we are ready to open the file.
  215. self.output_logger = logging.getLogger('britney2.output.upgrade_output')
  216. self.output_logger.setLevel(logging.INFO)
  217. # initialize the apt_pkg back-end
  218. apt_pkg.init()
  219. # parse the command line arguments
  220. self._policy_engine = PolicyEngine()
  221. self.suite_info = None # Initialized during __parse_arguments
  222. self.__parse_arguments()
  223. self.all_selected = []
  224. self.excuses = {}
  225. self.upgrade_me = []
  226. if self.options.nuninst_cache:
  227. self.logger.info("Not building the list of non-installable packages, as requested")
  228. if self.options.print_uninst:
  229. nuninst = read_nuninst(self.options.noninst_status,
  230. self.options.architectures)
  231. print('* summary')
  232. print('\n'.join('%4d %s' % (len(nuninst[x]), x) for x in self.options.architectures))
  233. return
  234. try:
  235. constraints_file = os.path.join(self.options.static_input_dir, 'constraints')
  236. faux_packages = os.path.join(self.options.static_input_dir, 'faux-packages')
  237. except AttributeError:
  238. self.logger.info("The static_input_dir option is not set")
  239. constraints_file = None
  240. faux_packages = None
  241. if faux_packages is not None and os.path.exists(faux_packages):
  242. self.logger.info("Loading faux packages from %s", faux_packages)
  243. self._load_faux_packages(faux_packages)
  244. elif faux_packages is not None:
  245. self.logger.info("No Faux packages as %s does not exist", faux_packages)
  246. if constraints_file is not None and os.path.exists(constraints_file):
  247. self.logger.info("Loading constraints from %s", constraints_file)
  248. self.constraints = self._load_constraints(constraints_file)
  249. else:
  250. if constraints_file is not None:
  251. self.logger.info("No constraints as %s does not exist", constraints_file)
  252. self.constraints = {
  253. 'keep-installable': [],
  254. }
  255. self.logger.info("Compiling Installability tester")
  256. self.pkg_universe, self._inst_tester = build_installability_tester(self.suite_info, self.options.architectures)
  257. target_suite = self.suite_info.target_suite
  258. target_suite.inst_tester = self._inst_tester
  259. self._migration_item_factory = MigrationItemFactory(self.suite_info)
  260. self._hint_parser = HintParser(self._migration_item_factory)
  261. self._migration_manager = MigrationManager(self.options, self.suite_info, self.all_binaries, self.pkg_universe,
  262. self.constraints, self._migration_item_factory)
  263. if not self.options.nuninst_cache:
  264. self.logger.info("Building the list of non-installable packages for the full archive")
  265. self._inst_tester.compute_installability()
  266. nuninst = compile_nuninst(target_suite,
  267. self.options.architectures,
  268. self.options.nobreakall_arches)
  269. self.nuninst_orig = nuninst
  270. for arch in self.options.architectures:
  271. self.logger.info("> Found %d non-installable packages", len(nuninst[arch]))
  272. if self.options.print_uninst:
  273. self.nuninst_arch_report(nuninst, arch)
  274. if self.options.print_uninst:
  275. print('* summary')
  276. print('\n'.join(map(lambda x: '%4d %s' % (len(nuninst[x]), x), self.options.architectures)))
  277. return
  278. else:
  279. write_nuninst(self.options.noninst_status, nuninst)
  280. stats = self._inst_tester.compute_stats()
  281. self.logger.info("> Installability tester statistics (per architecture)")
  282. for arch in self.options.architectures:
  283. arch_stat = stats[arch]
  284. self.logger.info("> %s", arch)
  285. for stat in arch_stat.stat_summary():
  286. self.logger.info("> - %s", stat)
  287. else:
  288. self.logger.info("Loading uninstallability counters from cache")
  289. self.nuninst_orig = read_nuninst(self.options.noninst_status,
  290. self.options.architectures)
  291. # nuninst_orig may get updated during the upgrade process
  292. self.nuninst_orig_save = clone_nuninst(self.nuninst_orig, architectures=self.options.architectures)
  293. self._policy_engine.register_policy_hints(self._hint_parser)
  294. try:
  295. self.read_hints(self.options.hintsdir)
  296. except AttributeError:
  297. self.read_hints(os.path.join(self.suite_info['unstable'].path, 'Hints'))
  298. self._policy_engine.initialise(self, self.hints)
  299. def __parse_arguments(self):
  300. """Parse the command line arguments
  301. This method parses and initializes the command line arguments.
  302. While doing so, it preprocesses some of the options to be converted
  303. in a suitable form for the other methods of the class.
  304. """
  305. # initialize the parser
  306. parser = optparse.OptionParser(version="%prog")
  307. parser.add_option("-v", "", action="count", dest="verbose", help="enable verbose output")
  308. parser.add_option("-c", "--config", action="store", dest="config", default="/etc/britney.conf",
  309. help="path for the configuration file")
  310. parser.add_option("", "--architectures", action="store", dest="architectures", default=None,
  311. help="override architectures from configuration file")
  312. parser.add_option("", "--actions", action="store", dest="actions", default=None,
  313. help="override the list of actions to be performed")
  314. parser.add_option("", "--hints", action="store", dest="hints", default=None,
  315. help="additional hints, separated by semicolons")
  316. parser.add_option("", "--hint-tester", action="store_true", dest="hint_tester", default=None,
  317. help="provide a command line interface to test hints")
  318. parser.add_option("", "--dry-run", action="store_true", dest="dry_run", default=False,
  319. help="disable all outputs to the testing directory")
  320. parser.add_option("", "--nuninst-cache", action="store_true", dest="nuninst_cache", default=False,
  321. help="do not build the non-installability status, use the cache from file")
  322. parser.add_option("", "--print-uninst", action="store_true", dest="print_uninst", default=False,
  323. help="just print a summary of uninstallable packages")
  324. parser.add_option("", "--compute-migrations", action="store_true", dest="compute_migrations", default=True,
  325. help="Compute which packages can migrate (the default)")
  326. parser.add_option("", "--no-compute-migrations", action="store_false", dest="compute_migrations",
  327. help="Do not compute which packages can migrate.")
  328. parser.add_option("", "--series", action="store", dest="series", default='',
  329. help="set distribution series name")
  330. (self.options, self.args) = parser.parse_args()
  331. if self.options.verbose:
  332. self.logger.setLevel(logging.INFO)
  333. else:
  334. self.logger.setLevel(logging.WARNING)
  335. # TODO: Define a more obvious toggle for debug information
  336. try: # pragma: no cover
  337. if int(os.environ.get('BRITNEY_DEBUG', '0')):
  338. self.logger.setLevel(logging.DEBUG)
  339. except ValueError: # pragma: no cover
  340. pass
  341. # integrity checks
  342. if self.options.nuninst_cache and self.options.print_uninst: # pragma: no cover
  343. self.logger.error("nuninst_cache and print_uninst are mutually exclusive!")
  344. sys.exit(1)
  345. # if the configuration file exists, then read it and set the additional options
  346. elif not os.path.isfile(self.options.config): # pragma: no cover
  347. self.logger.error("Unable to read the configuration file (%s), exiting!", self.options.config)
  348. sys.exit(1)
  349. # minimum days for unstable-testing transition and the list of hints
  350. # are handled as an ad-hoc case
  351. MINDAYS = {}
  352. self.HINTS = {'command-line': self.HINTS_ALL}
  353. with open(self.options.config, encoding='utf-8') as config:
  354. for line in config:
  355. if '=' in line and not line.strip().startswith('#'):
  356. k, v = line.split('=', 1)
  357. k = k.strip()
  358. v = v.strip()
  359. if k.startswith("MINDAYS_"):
  360. MINDAYS[k.split("_")[1].lower()] = int(v)
  361. elif k.startswith("HINTS_"):
  362. self.HINTS[k.split("_")[1].lower()] = \
  363. reduce(lambda x,y: x+y, [hasattr(self, "HINTS_" + i) and getattr(self, "HINTS_" + i) or (i,) for i in v.split()])
  364. elif not hasattr(self.options, k.lower()) or \
  365. not getattr(self.options, k.lower()):
  366. setattr(self.options, k.lower(), v)
  367. if hasattr(self.options, 'components'): # pragma: no cover
  368. self.logger.error("The COMPONENTS configuration has been removed.")
  369. self.logger.error("Britney will read the value from the Release file automatically")
  370. sys.exit(1)
  371. suite_loader = DebMirrorLikeSuiteContentLoader(self.options)
  372. try:
  373. self.suite_info = suite_loader.load_suites()
  374. except MissingRequiredConfigurationError as e: # pragma: no cover
  375. self.logger.error("Could not load the suite content due to missing configuration: %s", str(e))
  376. sys.exit(1)
  377. self.all_binaries = suite_loader.all_binaries()
  378. self.options.components = suite_loader.components
  379. self.options.architectures = suite_loader.architectures
  380. self.options.nobreakall_arches = suite_loader.nobreakall_arches
  381. self.options.outofsync_arches = suite_loader.outofsync_arches
  382. self.options.break_arches = suite_loader.break_arches
  383. self.options.new_arches = suite_loader.new_arches
  384. if self.options.series == '':
  385. self.options.series = self.suite_info.target_suite.name
  386. if not hasattr(self.options, "heidi_delta_output"):
  387. self.options.heidi_delta_output = self.options.heidi_output + "Delta"
  388. self.options.smooth_updates = self.options.smooth_updates.split()
  389. if not hasattr(self.options, 'ignore_cruft') or \
  390. self.options.ignore_cruft == "0":
  391. self.options.ignore_cruft = False
  392. if not hasattr(self.options, 'check_consistency_level'):
  393. self.options.check_consistency_level = 2
  394. else:
  395. self.options.check_consistency_level = int(self.options.check_consistency_level)
  396. if not hasattr(self.options, 'adt_retry_url_mech'):
  397. self.options.adt_retry_url_mech = ''
  398. self._policy_engine.add_policy(RCBugPolicy(self.options, self.suite_info))
  399. self._policy_engine.add_policy(PiupartsPolicy(self.options, self.suite_info))
  400. if getattr(self.options, 'adt_enable') == 'yes':
  401. self._policy_engine.add_policy(AutopkgtestPolicy(self.options, self.suite_info))
  402. self._policy_engine.add_policy(AgePolicy(self.options, self.suite_info, MINDAYS))
  403. self._policy_engine.add_policy(BuildDependsPolicy(self.options, self.suite_info))
  404. self._policy_engine.add_policy(BlockPolicy(self.options, self.suite_info))
  405. self._policy_engine.add_policy(BuiltUsingPolicy(self.options, self.suite_info))
  406. if getattr(self.options, 'check_buildd', 'no') == 'yes':
  407. self._policy_engine.add_policy(BuiltOnBuilddPolicy(self.options, self.suite_info))
  408. @property
  409. def hints(self):
  410. return self._hint_parser.hints
  411. def _load_faux_packages(self, faux_packages_file):
  412. """Loads fake packages
  413. In rare cases, it is useful to create a "fake" package that can be used to satisfy
  414. dependencies. This is usually needed for packages that are not shipped directly
  415. on this mirror but is a prerequisite for using this mirror (e.g. some vendors provide
  416. non-distributable "setup" packages and contrib/non-free packages depend on these).
  417. :param faux_packages_file: Path to the file containing the fake package definitions
  418. """
  419. tag_file = apt_pkg.TagFile(faux_packages_file)
  420. get_field = tag_file.section.get
  421. step = tag_file.step
  422. no = 0
  423. pri_source_suite = self.suite_info.primary_source_suite
  424. target_suite = self.suite_info.target_suite
  425. while step():
  426. no += 1
  427. pkg_name = get_field('Package', None)
  428. if pkg_name is None: # pragma: no cover
  429. raise ValueError("Missing Package field in paragraph %d (file %s)" % (no, faux_packages_file))
  430. pkg_name = sys.intern(pkg_name)
  431. version = sys.intern(get_field('Version', '1.0-1'))
  432. provides_raw = get_field('Provides')
  433. archs_raw = get_field('Architecture', None)
  434. component = get_field('Component', 'non-free')
  435. if archs_raw:
  436. archs = archs_raw.split()
  437. else:
  438. archs = self.options.architectures
  439. faux_section = 'faux'
  440. if component != 'main':
  441. faux_section = "%s/faux" % component
  442. src_data = SourcePackage(version,
  443. sys.intern(faux_section),
  444. set(),
  445. None,
  446. True,
  447. None,
  448. None,
  449. [],
  450. [],
  451. )
  452. target_suite.sources[pkg_name] = src_data
  453. pri_source_suite.sources[pkg_name] = src_data
  454. for arch in archs:
  455. pkg_id = BinaryPackageId(pkg_name, version, arch)
  456. if provides_raw:
  457. provides = parse_provides(provides_raw, pkg_id=pkg_id, logger=self.logger)
  458. else:
  459. provides = []
  460. bin_data = BinaryPackage(version,
  461. faux_section,
  462. pkg_name,
  463. version,
  464. arch,
  465. get_field('Multi-Arch'),
  466. None,
  467. None,
  468. provides,
  469. False,
  470. pkg_id,
  471. [],
  472. )
  473. src_data.binaries.add(pkg_id)
  474. target_suite.binaries[arch][pkg_name] = bin_data
  475. pri_source_suite.binaries[arch][pkg_name] = bin_data
  476. self.all_binaries[pkg_id] = bin_data
  477. def _load_constraints(self, constraints_file):
  478. """Loads configurable constraints
  479. The constraints file can contain extra rules that Britney should attempt
  480. to satisfy. Examples can be "keep package X in testing and ensure it is
  481. installable".
  482. :param constraints_file: Path to the file containing the constraints
  483. """
  484. tag_file = apt_pkg.TagFile(constraints_file)
  485. get_field = tag_file.section.get
  486. step = tag_file.step
  487. no = 0
  488. faux_version = sys.intern('1')
  489. faux_section = sys.intern('faux')
  490. keep_installable = []
  491. constraints = {
  492. 'keep-installable': keep_installable
  493. }
  494. pri_source_suite = self.suite_info.primary_source_suite
  495. target_suite = self.suite_info.target_suite
  496. while step():
  497. no += 1
  498. pkg_name = get_field('Fake-Package-Name', None)
  499. if pkg_name is None: # pragma: no cover
  500. raise ValueError("Missing Fake-Package-Name field in paragraph %d (file %s)" % (no, constraints_file))
  501. pkg_name = sys.intern(pkg_name)
  502. def mandatory_field(x):
  503. v = get_field(x, None)
  504. if v is None: # pragma: no cover
  505. raise ValueError("Missing %s field for %s (file %s)" % (x, pkg_name, constraints_file))
  506. return v
  507. constraint = mandatory_field('Constraint')
  508. if constraint not in {'present-and-installable'}: # pragma: no cover
  509. raise ValueError("Unsupported constraint %s for %s (file %s)" % (constraint, pkg_name, constraints_file))
  510. self.logger.info(" - constraint %s", pkg_name)
  511. pkg_list = [x.strip() for x in mandatory_field('Package-List').split("\n") if x.strip() != '' and not x.strip().startswith("#")]
  512. src_data = SourcePackage(faux_version,
  513. faux_section,
  514. set(),
  515. None,
  516. True,
  517. None,
  518. None,
  519. [],
  520. [],
  521. )
  522. target_suite.sources[pkg_name] = src_data
  523. pri_source_suite.sources[pkg_name] = src_data
  524. keep_installable.append(pkg_name)
  525. for arch in self.options.architectures:
  526. deps = []
  527. for pkg_spec in pkg_list:
  528. s = pkg_spec.split(None, 1)
  529. if len(s) == 1:
  530. deps.append(s[0])
  531. else:
  532. pkg, arch_res = s
  533. if not (arch_res.startswith('[') and arch_res.endswith(']')): # pragma: no cover
  534. raise ValueError("Invalid arch-restriction on %s - should be [arch1 arch2] (for %s file %s)"
  535. % (pkg, pkg_name, constraints_file))
  536. arch_res = arch_res[1:-1].split()
  537. if not arch_res: # pragma: no cover
  538. msg = "Empty arch-restriction for %s: Uses comma or negation (for %s file %s)"
  539. raise ValueError(msg % (pkg, pkg_name, constraints_file))
  540. for a in arch_res:
  541. if a == arch:
  542. deps.append(pkg)
  543. elif ',' in a or '!' in a: # pragma: no cover
  544. msg = "Invalid arch-restriction for %s: Uses comma or negation (for %s file %s)"
  545. raise ValueError(msg % (pkg, pkg_name, constraints_file))
  546. pkg_id = BinaryPackageId(pkg_name, faux_version, arch)
  547. bin_data = BinaryPackage(faux_version,
  548. faux_section,
  549. pkg_name,
  550. faux_version,
  551. arch,
  552. 'no',
  553. ', '.join(deps),
  554. None,
  555. [],
  556. False,
  557. pkg_id,
  558. [],
  559. )
  560. src_data.binaries.add(pkg_id)
  561. target_suite.binaries[arch][pkg_name] = bin_data
  562. pri_source_suite.binaries[arch][pkg_name] = bin_data
  563. self.all_binaries[pkg_id] = bin_data
  564. return constraints
  565. # Data reading/writing methods
  566. # ----------------------------
  567. def read_hints(self, hintsdir):
  568. """Read the hint commands from the specified directory
  569. The hint commands are read from the files contained in the directory
  570. specified by the `hintsdir' parameter.
  571. The names of the files have to be the same as the authorized users
  572. for the hints.
  573. The file contains rows with the format:
  574. <command> <package-name>[/<version>]
  575. The method returns a dictionary where the key is the command, and
  576. the value is the list of affected packages.
  577. """
  578. for who in self.HINTS.keys():
  579. if who == 'command-line':
  580. lines = self.options.hints and self.options.hints.split(';') or ()
  581. filename = '<cmd-line>'
  582. self._hint_parser.parse_hints(who, self.HINTS[who], filename, lines)
  583. else:
  584. filename = os.path.join(hintsdir, who)
  585. if not os.path.isfile(filename):
  586. self.logger.error("Cannot read hints list from %s, no such file!", filename)
  587. continue
  588. self.logger.info("Loading hints list from %s", filename)
  589. with open(filename, encoding='utf-8') as f:
  590. self._hint_parser.parse_hints(who, self.HINTS[who], filename, f)
  591. hints = self._hint_parser.hints
  592. for x in ["block", "block-all", "block-udeb", "unblock", "unblock-udeb", "force", "urgent", "remove", "age-days"]:
  593. z = defaultdict(dict)
  594. for hint in hints[x]:
  595. package = hint.package
  596. architecture = hint.architecture
  597. key = (hint, hint.user)
  598. if package in z and architecture in z[package] and z[package][architecture] != key:
  599. hint2 = z[package][architecture][0]
  600. if x in ['unblock', 'unblock-udeb']:
  601. if apt_pkg.version_compare(hint2.version, hint.version) < 0:
  602. # This hint is for a newer version, so discard the old one
  603. self.logger.warning("Overriding %s[%s] = ('%s', '%s', '%s') with ('%s', '%s', '%s')",
  604. x, package, hint2.version, hint2.architecture, hint2.user, hint.version, hint.architecture, hint.user)
  605. hint2.set_active(False)
  606. else:
  607. # This hint is for an older version, so ignore it in favour of the new one
  608. self.logger.warning("Ignoring %s[%s] = ('%s', '%s', '%s'), ('%s', '%s', '%s') is higher or equal",
  609. x, package, hint.version, hint.architecture, hint.user, hint2.version, hint2.architecture, hint2.user)
  610. hint.set_active(False)
  611. else:
  612. self.logger.warning("Overriding %s[%s] = ('%s', '%s') with ('%s', '%s')",
  613. x, package, hint2.user, hint2, hint.user, hint)
  614. hint2.set_active(False)
  615. z[package][architecture] = key
  616. # Sanity check the hints hash
  617. if len(hints["block"]) == 0 and len(hints["block-udeb"]) == 0:
  618. self.logger.warning("WARNING: No block hints at all, not even udeb ones!")
  619. def write_excuses(self):
  620. """Produce and write the update excuses
  621. This method handles the update excuses generation: the packages are
  622. looked at to determine whether they are valid candidates. For the details
  623. of this procedure, please refer to the module docstring.
  624. """
  625. self.logger.info("Update Excuses generation started")
  626. mi_factory = self._migration_item_factory
  627. excusefinder = ExcuseFinder(self.options, self.suite_info, self.all_binaries,
  628. self.pkg_universe, self._policy_engine, mi_factory, self.hints)
  629. excuses, upgrade_me = excusefinder.find_actionable_excuses()
  630. self.excuses = excuses
  631. # sort the list of candidates
  632. self.upgrade_me = sorted(upgrade_me)
  633. self.upgrade_me.extend(old_libraries(mi_factory, self.suite_info, self.options.outofsync_arches))
  634. # write excuses to the output file
  635. if not self.options.dry_run:
  636. self.logger.info("> Writing Excuses to %s", self.options.excuses_output)
  637. sorted_excuses = sorted(excuses.values(), key=lambda x: x.sortkey())
  638. write_excuses(sorted_excuses, self.options.excuses_output,
  639. output_format="legacy-html")
  640. if hasattr(self.options, 'excuses_yaml_output'):
  641. self.logger.info("> Writing YAML Excuses to %s", self.options.excuses_yaml_output)
  642. write_excuses(sorted_excuses, self.options.excuses_yaml_output,
  643. output_format="yaml")
  644. self.logger.info("Update Excuses generation completed")
  645. # Upgrade run
  646. # -----------
  647. def eval_nuninst(self, nuninst, original=None):
  648. """Return a string which represents the uninstallability counters
  649. This method returns a string which represents the uninstallability
  650. counters reading the uninstallability statistics `nuninst` and, if
  651. present, merging the results with the `original` one.
  652. An example of the output string is:
  653. 1+2: i-0:a-0:a-0:h-0:i-1:m-0:m-0:p-0:a-0:m-0:s-2:s-0
  654. where the first part is the number of broken packages in non-break
  655. architectures + the total number of broken packages for all the
  656. architectures.
  657. """
  658. res = []
  659. total = 0
  660. totalbreak = 0
  661. for arch in self.options.architectures:
  662. if arch in nuninst:
  663. n = len(nuninst[arch])
  664. elif original and arch in original:
  665. n = len(original[arch])
  666. else: continue
  667. if arch in self.options.break_arches:
  668. totalbreak = totalbreak + n
  669. else:
  670. total = total + n
  671. res.append("%s-%d" % (arch[0], n))
  672. return "%d+%d: %s" % (total, totalbreak, ":".join(res))
  673. def iter_packages(self, packages, selected, nuninst=None):
  674. """Iter on the list of actions and apply them one-by-one
  675. This method applies the changes from `packages` to testing, checking the uninstallability
  676. counters for every action performed. If the action does not improve them, it is reverted.
  677. The method returns the new uninstallability counters and the remaining actions if the
  678. final result is successful, otherwise (None, []).
  679. """
  680. group_info = {}
  681. rescheduled_packages = packages
  682. maybe_rescheduled_packages = []
  683. output_logger = self.output_logger
  684. solver = InstallabilitySolver(self.pkg_universe, self._inst_tester)
  685. mm = self._migration_manager
  686. target_suite = self.suite_info.target_suite
  687. for y in sorted((y for y in packages), key=attrgetter('uvname')):
  688. try:
  689. _, updates, rms, _ = mm.compute_groups(y)
  690. result = (y, frozenset(updates), frozenset(rms))
  691. group_info[y] = result
  692. except MigrationConstraintException as e:
  693. rescheduled_packages.remove(y)
  694. output_logger.info("not adding package to list: %s",(y.package))
  695. output_logger.info(" got exception: %s"%(repr(e)))
  696. if nuninst:
  697. nuninst_orig = nuninst
  698. else:
  699. nuninst_orig = self.nuninst_orig
  700. nuninst_last_accepted = nuninst_orig
  701. output_logger.info("recur: [] %s %d/0", ",".join(x.uvname for x in selected), len(packages))
  702. while rescheduled_packages:
  703. groups = {group_info[x] for x in rescheduled_packages}
  704. worklist = solver.solve_groups(groups)
  705. rescheduled_packages = []
  706. worklist.reverse()
  707. while worklist:
  708. comp = worklist.pop()
  709. comp_name = ' '.join(item.uvname for item in comp)
  710. output_logger.info("trying: %s" % comp_name)
  711. with mm.start_transaction() as transaction:
  712. accepted = False
  713. try:
  714. accepted, nuninst_after, failed_arch, new_cruft = mm.migrate_items_to_target_suite(
  715. comp,
  716. nuninst_last_accepted
  717. )
  718. if accepted:
  719. selected.extend(comp)
  720. transaction.commit()
  721. output_logger.info("accepted: %s", comp_name)
  722. output_logger.info(" ori: %s", self.eval_nuninst(nuninst_orig))
  723. output_logger.info(" pre: %s", self.eval_nuninst(nuninst_last_accepted))
  724. output_logger.info(" now: %s", self.eval_nuninst(nuninst_after))
  725. if new_cruft:
  726. output_logger.info(" added new cruft items to list: %s",
  727. " ".join(x.uvname for x in new_cruft))
  728. if len(selected) <= 20:
  729. output_logger.info(" all: %s", " ".join(x.uvname for x in selected))
  730. else:
  731. output_logger.info(" most: (%d) .. %s",
  732. len(selected),
  733. " ".join(x.uvname for x in selected[-20:]))
  734. if self.options.check_consistency_level >= 3:
  735. target_suite.check_suite_source_pkg_consistency('iter_packages after commit')
  736. nuninst_last_accepted = nuninst_after
  737. for cruft_item in new_cruft:
  738. _, updates, rms, _ = mm.compute_groups(cruft_item)
  739. result = (cruft_item, frozenset(updates), frozenset(rms))
  740. group_info[cruft_item] = result
  741. worklist.extend([x] for x in new_cruft)
  742. rescheduled_packages.extend(maybe_rescheduled_packages)
  743. maybe_rescheduled_packages.clear()
  744. else:
  745. transaction.rollback()
  746. broken = sorted(b for b in nuninst_after[failed_arch]
  747. if b not in nuninst_last_accepted[failed_arch])
  748. compare_nuninst = None
  749. if any(item for item in comp if item.architecture != 'source'):
  750. compare_nuninst = nuninst_last_accepted
  751. # NB: try_migration already reverted this for us, so just print the results and move on
  752. output_logger.info("skipped: %s (%d, %d, %d)",
  753. comp_name,
  754. len(rescheduled_packages),
  755. len(maybe_rescheduled_packages),
  756. len(worklist)
  757. )
  758. output_logger.info(" got: %s", self.eval_nuninst(nuninst_after, compare_nuninst))
  759. output_logger.info(" * %s: %s", failed_arch, ", ".join(broken))
  760. if self.options.check_consistency_level >= 3:
  761. target_suite.check_suite_source_pkg_consistency('iter_package after rollback (not accepted)')
  762. except MigrationConstraintException as e:
  763. transaction.rollback()
  764. output_logger.info("skipped: %s (%d, %d, %d)",
  765. comp_name,
  766. len(rescheduled_packages),
  767. len(maybe_rescheduled_packages),
  768. len(worklist)
  769. )
  770. output_logger.info(" got exception: %s"%(repr(e)))
  771. if self.options.check_consistency_level >= 3:
  772. target_suite.check_suite_source_pkg_consistency('iter_package after rollback (MigrationConstraintException)')
  773. if not accepted:
  774. if len(comp) > 1:
  775. output_logger.info(" - splitting the component into single items and retrying them")
  776. worklist.extend([item] for item in comp)
  777. else:
  778. maybe_rescheduled_packages.append(comp[0])
  779. output_logger.info(" finish: [%s]", ",".join(x.uvname for x in selected))
  780. output_logger.info("endloop: %s", self.eval_nuninst(self.nuninst_orig))
  781. output_logger.info(" now: %s", self.eval_nuninst(nuninst_last_accepted))
  782. format_and_log_uninst(output_logger,
  783. self.options.architectures,
  784. newly_uninst(self.nuninst_orig, nuninst_last_accepted)
  785. )
  786. output_logger.info("")
  787. return (nuninst_last_accepted, maybe_rescheduled_packages)
  788. def do_all(self, hinttype=None, init=None, actions=None):
  789. """Testing update runner
  790. This method tries to update testing checking the uninstallability
  791. counters before and after the actions to decide if the update was
  792. successful or not.
  793. """
  794. selected = []
  795. if actions:
  796. upgrade_me = actions[:]
  797. else:
  798. upgrade_me = self.upgrade_me[:]
  799. nuninst_start = self.nuninst_orig
  800. output_logger = self.output_logger
  801. target_suite = self.suite_info.target_suite
  802. # these are special parameters for hints processing
  803. force = False
  804. recurse = True
  805. nuninst_end = None
  806. extra = []
  807. mm = self._migration_manager
  808. if hinttype == "easy" or hinttype == "force-hint":
  809. force = hinttype == "force-hint"
  810. recurse = False
  811. # if we have a list of initial packages, check them
  812. if init:
  813. for x in init:
  814. if x not in upgrade_me:
  815. output_logger.warning("failed: %s is not a valid candidate (or it already migrated)", x.uvname)
  816. return None
  817. selected.append(x)
  818. upgrade_me.remove(x)
  819. output_logger.info("start: %s", self.eval_nuninst(nuninst_start))
  820. output_logger.info("orig: %s", self.eval_nuninst(nuninst_start))
  821. if init and not force:
  822. # We will need to be able to roll back (e.g. easy or a "hint"-hint)
  823. _start_transaction = mm.start_transaction
  824. else:
  825. # No "outer" transaction needed as we will never need to rollback
  826. # (e.g. "force-hint" or a regular "main run"). Emulate the start_transaction
  827. # call from the MigrationManager, so the rest of the code follows the
  828. # same flow regardless of whether we need the transaction or not.
  829. @contextlib.contextmanager
  830. def _start_transaction():
  831. yield None
  832. with _start_transaction() as transaction:
  833. if init:
  834. # init => a hint (e.g. "easy") - so do the hint run
  835. (_, nuninst_end, _, new_cruft) = mm.migrate_items_to_target_suite(selected,
  836. self.nuninst_orig,
  837. stop_on_first_regression=False)
  838. if recurse:
  839. # Ensure upgrade_me and selected do not overlap, if we
  840. # follow-up with a recurse ("hint"-hint).
  841. upgrade_me = [x for x in upgrade_me if x not in set(selected)]
  842. else:
  843. # On non-recursive hints check for cruft and purge it proactively in case it "fixes" the hint.
  844. cruft = [x for x in upgrade_me if x.is_cruft_removal]
  845. if new_cruft:
  846. output_logger.info("Change added new cruft items to list: %s",
  847. " ".join(x.uvname for x in new_cruft))
  848. cruft.extend(new_cruft)
  849. if cruft:
  850. output_logger.info("Checking if changes enables cruft removal")
  851. (nuninst_end, remaining_cruft) = self.iter_packages(cruft,
  852. selected,
  853. nuninst=nuninst_end)
  854. output_logger.info("Removed %d of %d cruft item(s) after the changes",
  855. len(cruft) - len(remaining_cruft), len(cruft))
  856. new_cruft.difference_update(remaining_cruft)
  857. # Add new cruft items regardless of whether we recurse. A future run might clean
  858. # them for us.
  859. upgrade_me.extend(new_cruft)
  860. if recurse:
  861. # Either the main run or the recursive run of a "hint"-hint.
  862. (nuninst_end, extra) = self.iter_packages(upgrade_me,
  863. selected,
  864. nuninst=nuninst_end)
  865. nuninst_end_str = self.eval_nuninst(nuninst_end)
  866. if not recurse:
  867. # easy or force-hint
  868. output_logger.info("easy: %s", nuninst_end_str)
  869. if not force:
  870. format_and_log_uninst(self.output_logger,
  871. self.options.architectures,
  872. newly_uninst(nuninst_start, nuninst_end)
  873. )
  874. if force:
  875. # Force implies "unconditionally better"
  876. better = True
  877. else:
  878. break_arches = set(self.options.break_arches)
  879. if all(x.architecture in break_arches for x in selected):
  880. # If we only migrated items from break-arches, then we
  881. # do not allow any regressions on these architectures.
  882. # This usually only happens with hints
  883. break_arches = set()
  884. better = is_nuninst_asgood_generous(self.constraints,
  885. self.options.architectures,
  886. self.nuninst_orig,
  887. nuninst_end,
  888. break_arches)
  889. if better:
  890. # Result accepted either by force or by being better than the original result.
  891. output_logger.info("final: %s", ",".join(sorted(x.uvname for x in selected)))
  892. output_logger.info("start: %s", self.eval_nuninst(nuninst_start))
  893. output_logger.info(" orig: %s", self.eval_nuninst(self.nuninst_orig))
  894. output_logger.info(" end: %s", nuninst_end_str)
  895. if force:
  896. broken = newly_uninst(nuninst_start, nuninst_end)
  897. if broken:
  898. output_logger.warning("force breaks:")
  899. format_and_log_uninst(self.output_logger,
  900. self.options.architectures,
  901. broken,
  902. loglevel=logging.WARNING,
  903. )
  904. else:
  905. output_logger.info("force did not break any packages")
  906. output_logger.info("SUCCESS (%d/%d)", len(actions or self.upgrade_me), len(extra))
  907. self.nuninst_orig = nuninst_end
  908. self.all_selected += selected
  909. if transaction:
  910. transaction.commit()
  911. if self.options.check_consistency_level >= 2:
  912. target_suite.check_suite_source_pkg_consistency('do_all after commit')
  913. if not actions:
  914. if recurse:
  915. self.upgrade_me = extra
  916. else:
  917. self.upgrade_me = [x for x in self.upgrade_me if x not in set(selected)]
  918. else:
  919. output_logger.info("FAILED\n")
  920. if not transaction:
  921. return
  922. transaction.rollback()
  923. if self.options.check_consistency_level >= 2:
  924. target_suite.check_suite_source_pkg_consistency('do_all after rollback')
  925. output_logger.info("")
  926. def assert_nuninst_is_correct(self):
  927. self.logger.info("> Update complete - Verifying non-installability counters")
  928. cached_nuninst = self.nuninst_orig
  929. self._inst_tester.compute_installability()
  930. computed_nuninst = compile_nuninst(self.suite_info.target_suite,
  931. self.options.architectures,
  932. self.options.nobreakall_arches)
  933. if cached_nuninst != computed_nuninst: # pragma: no cover
  934. only_on_break_archs = True
  935. self.logger.error("==================== NUNINST OUT OF SYNC =========================")
  936. for arch in self.options.architectures:
  937. expected_nuninst = set(cached_nuninst[arch])
  938. actual_nuninst = set(computed_nuninst[arch])
  939. false_negatives = actual_nuninst - expected_nuninst
  940. false_positives = expected_nuninst - actual_nuninst
  941. # Britney does not quite work correctly with
  942. # break/fucked arches, so ignore issues there for now.
  943. if (false_negatives or false_positives) and arch not in self.options.break_arches:
  944. only_on_break_archs = False
  945. if false_negatives:
  946. self.logger.error(" %s - unnoticed nuninst: %s", arch, str(false_negatives))
  947. if false_positives:
  948. self.logger.error(" %s - invalid nuninst: %s", arch, str(false_positives))
  949. self.logger.info(" %s - actual nuninst: %s", arch, str(actual_nuninst))
  950. self.logger.error("==================== NUNINST OUT OF SYNC =========================")
  951. if not only_on_break_archs:
  952. raise AssertionError("NUNINST OUT OF SYNC")
  953. else:
  954. self.logger.warning("Nuninst is out of sync on some break arches")
  955. self.logger.info("> All non-installability counters are ok")
  956. def upgrade_testing(self):
  957. """Upgrade testing using the packages from the source suites
  958. This method tries to upgrade testing using the packages from the
  959. source suites.
  960. Before running the do_all method, it tries the easy and force-hint
  961. commands.
  962. """
  963. output_logger = self.output_logger
  964. self.logger.info("Starting the upgrade test")
  965. output_logger.info("Generated on: %s", time.strftime("%Y.%m.%d %H:%M:%S %z", time.gmtime(time.time())))
  966. output_logger.info("Arch order is: %s", ", ".join(self.options.architectures))
  967. if not self.options.actions:
  968. # process `easy' hints
  969. for x in self.hints['easy']:
  970. self.do_hint("easy", x.user, x.packages)
  971. # process `force-hint' hints
  972. for x in self.hints["force-hint"]:
  973. self.do_hint("force-hint", x.user, x.packages)
  974. # run the first round of the upgrade
  975. # - do separate runs for break arches
  976. allpackages = []
  977. normpackages = self.upgrade_me[:]
  978. archpackages = {}
  979. for a in self.options.break_arches:
  980. archpackages[a] = [p for p in normpackages if p.architecture == a]
  981. normpackages = [p for p in normpackages if p not in archpackages[a]]
  982. self.upgrade_me = normpackages
  983. output_logger.info("info: main run")
  984. self.do_all()
  985. allpackages += self.upgrade_me
  986. for a in self.options.break_arches:
  987. backup = self.options.break_arches
  988. self.options.break_arches = " ".join(x for x in self.options.break_arches if x != a)
  989. self.upgrade_me = archpackages[a]
  990. output_logger.info("info: broken arch run for %s", a)
  991. self.do_all()
  992. allpackages += self.upgrade_me
  993. self.options.break_arches = backup
  994. self.upgrade_me = allpackages
  995. if self.options.actions:
  996. self.printuninstchange()
  997. return
  998. # process `hint' hints
  999. hintcnt = 0
  1000. for x in self.hints["hint"][:50]:
  1001. if hintcnt > 50:
  1002. output_logger.info("Skipping remaining hints...")
  1003. break
  1004. if self.do_hint("hint", x.user, x.packages):
  1005. hintcnt += 1
  1006. # run the auto hinter
  1007. self.run_auto_hinter()
  1008. if getattr(self.options, "remove_obsolete", "yes") == "yes":
  1009. # obsolete source packages
  1010. # a package is obsolete if none of the binary packages in testing
  1011. # are built by it
  1012. self.logger.info("> Removing obsolete source packages from the target suite")
  1013. # local copies for performance
  1014. target_suite = self.suite_info.target_suite
  1015. sources_t = target_suite.sources
  1016. binaries_t = target_suite.binaries
  1017. mi_factory = self._migration_item_factory
  1018. used = set(binaries_t[arch][binary].source
  1019. for arch in binaries_t
  1020. for binary in binaries_t[arch]
  1021. )
  1022. removals = [mi_factory.parse_item("-%s/%s" % (source, sources_t[source].version), auto_correct=False)
  1023. for source in sources_t if source not in used
  1024. ]
  1025. if removals:
  1026. output_logger.info("Removing obsolete source packages from the target suite (%d):", len(removals))
  1027. self.do_all(actions=removals)
  1028. # smooth updates
  1029. removals = old_libraries(self._migration_item_factory, self.suite_info, self.options.outofsync_arches)
  1030. if removals:
  1031. output_logger.info("Removing packages left in the target suite (e.g. smooth updates or cruft)")
  1032. log_and_format_old_libraries(self.output_logger, removals)
  1033. self.do_all(actions=removals)
  1034. removals = old_libraries(self._migration_item_factory, self.suite_info, self.options.outofsync_arches)
  1035. output_logger.info("List of old libraries in the target suite (%d):", len(removals))
  1036. log_and_format_old_libraries(self.output_logger, removals)
  1037. self.printuninstchange()
  1038. if self.options.check_consistency_level >= 1:
  1039. target_suite = self.suite_info.target_suite
  1040. self.assert_nuninst_is_correct()
  1041. target_suite.check_suite_source_pkg_consistency('end')
  1042. # output files
  1043. if not self.options.dry_run:
  1044. target_suite = self.suite_info.target_suite
  1045. # write HeidiResult
  1046. self.logger.info("Writing Heidi results to %s", self.options.heidi_output)
  1047. write_heidi(self.options.heidi_output,
  1048. target_suite,
  1049. outofsync_arches=self.options.outofsync_arches)
  1050. self.logger.info("Writing delta to %s", self.options.heidi_delta_output)
  1051. write_heidi_delta(self.options.heidi_delta_output,
  1052. self.all_selected)
  1053. self.logger.info("Test completed!")
  1054. def printuninstchange(self):
  1055. self.logger.info("Checking for newly uninstallable packages")
  1056. uninst = newly_uninst(self.nuninst_orig_save, self.nuninst_orig)
  1057. if uninst:
  1058. self.output_logger.warning("")
  1059. self.output_logger.warning("Newly uninstallable packages in the target suite:")
  1060. format_and_log_uninst(self.output_logger,
  1061. self.options.architectures,
  1062. uninst,
  1063. loglevel=logging.WARNING,
  1064. )
  1065. def hint_tester(self):
  1066. """Run a command line interface to test hints
  1067. This method provides a command line interface for the release team to
  1068. try hints and evaluate the results.
  1069. """
  1070. import readline
  1071. from britney2.completer import Completer
  1072. histfile = os.path.expanduser('~/.britney2_history')
  1073. if os.path.exists(histfile):
  1074. readline.read_history_file(histfile)
  1075. readline.parse_and_bind('tab: complete')
  1076. readline.set_completer(Completer(self).completer)
  1077. # Package names can contain "-" and we use "/" in our presentation of them as well,
  1078. # so ensure readline does not split on these characters.
  1079. readline.set_completer_delims(readline.get_completer_delims().replace('-', '').replace('/', ''))
  1080. known_hints = self._hint_parser.registered_hints
  1081. while True:
  1082. # read the command from the command line
  1083. try:
  1084. user_input = input('britney> ').split()
  1085. except EOFError:
  1086. print("")
  1087. break
  1088. except KeyboardInterrupt:
  1089. print("")
  1090. continue
  1091. # quit the hint tester
  1092. if user_input and user_input[0] in ('quit', 'exit'):
  1093. break
  1094. # run a hint
  1095. elif user_input and user_input[0] in ('easy', 'hint', 'force-hint'):
  1096. mi_factory = self._migration_item_factory
  1097. try:
  1098. self.do_hint(user_input[0], 'hint-tester', mi_factory.parse_items(user_input[1:]))
  1099. self.printuninstchange()
  1100. except KeyboardInterrupt:
  1101. continue
  1102. elif user_input and user_input[0] in known_hints:
  1103. self._hint_parser.parse_hints('hint-tester', self.HINTS_ALL, '<stdin>', [' '.join(user_input)])
  1104. self.write_excuses()
  1105. try:
  1106. readline.write_history_file(histfile)
  1107. except IOError as e:
  1108. self.logger.warning("Could not write %s: %s", histfile, e)
  1109. def do_hint(self, hinttype, who, pkgvers):
  1110. """Process hints
  1111. This method process `easy`, `hint` and `force-hint` hints. If the
  1112. requested version is not in the relevant source suite, then the hint
  1113. is skipped.
  1114. """
  1115. output_logger = self.output_logger
  1116. suites = self.suite_info
  1117. self.logger.info("> Processing '%s' hint from %s", hinttype, who)
  1118. output_logger.info("Trying %s from %s: %s", hinttype, who,
  1119. " ".join("%s/%s" % (x.uvname, x.version) for x in pkgvers)
  1120. )
  1121. issues = []
  1122. # loop on the requested packages and versions
  1123. for idx in range(len(pkgvers)):
  1124. pkg = pkgvers[idx]
  1125. # skip removal requests
  1126. if pkg.is_removal:
  1127. continue
  1128. suite = pkg.suite
  1129. if pkg.package not in suite.sources:
  1130. issues.append("Source %s has no version in %s" % (pkg.package, suite.name))
  1131. elif apt_pkg.version_compare(suite.sources[pkg.package].version, pkg.version) != 0:
  1132. issues.append("Version mismatch, %s %s != %s" % (pkg.package, pkg.version,
  1133. suite.sources[pkg.package].version))
  1134. if issues:
  1135. output_logger.warning("%s: Not using hint", ", ".join(issues))
  1136. return False
  1137. self.do_all(hinttype, pkgvers)
  1138. return True
  1139. def get_auto_hinter_hints(self, upgrade_me):
  1140. """Auto-generate "easy" hints.
  1141. This method attempts to generate "easy" hints for sets of packages which
  1142. must migrate together. Beginning with a package which does not depend on
  1143. any other package (in terms of excuses), a list of dependencies and
  1144. reverse dependencies is recursively created.
  1145. Once all such lists have been generated, any which are subsets of other
  1146. lists are ignored in favour of the larger lists. The remaining lists are
  1147. then attempted in turn as "easy" hints.
  1148. We also try to auto hint circular dependencies analyzing the update
  1149. excuses relationships. If they build a circular dependency, which we already
  1150. know as not-working with the standard do_all algorithm, try to `easy` them.
  1151. """
  1152. self.logger.info("> Processing hints from the auto hinter")
  1153. sources_t = self.suite_info.target_suite.sources
  1154. excuses = self.excuses
  1155. # consider only excuses which are valid candidates and still relevant.
  1156. valid_excuses = frozenset(y.uvname for y in upgrade_me
  1157. if not y.is_cruft_removal and
  1158. (y not in sources_t or sources_t[y].version != excuses[y].ver[1]))
  1159. excuses_deps = {name: valid_excuses.intersection(excuse.get_deps())
  1160. for name, excuse in excuses.items() if name in valid_excuses}
  1161. excuses_rdeps = defaultdict(set)
  1162. for name, deps in excuses_deps.items():
  1163. for dep in deps:
  1164. excuses_rdeps[dep].add(name)
  1165. def find_related(e, hint, circular_first=False):
  1166. excuse = excuses[e]
  1167. if not circular_first:
  1168. hint[e] = excuse.ver[1]
  1169. if not excuse.get_deps():
  1170. return hint
  1171. for p in excuses_deps[e]:
  1172. if p in hint or p not in valid_excuses:
  1173. continue
  1174. if not find_related(p, hint):
  1175. return False
  1176. return hint
  1177. # loop on them
  1178. candidates = []
  1179. mincands = []
  1180. seen_hints = set()
  1181. for e in valid_excuses:
  1182. excuse = excuses[e]
  1183. if excuse.get_deps():
  1184. hint = find_related(e, {}, True)
  1185. if isinstance(hint, dict) and e in hint:
  1186. h = frozenset(hint.items())
  1187. if h not in seen_hints:
  1188. candidates.append(h)
  1189. seen_hints.add(h)
  1190. else:
  1191. items = [(e, excuse.ver[1])]
  1192. orig_size = 1
  1193. looped = False
  1194. seen_items = set()
  1195. seen_items.update(items)
  1196. for item, ver in items:
  1197. # excuses which depend on "item" or are depended on by it
  1198. new_items = {(x, excuses[x].ver[1]) for x in chain(excuses_deps[item], excuses_rdeps[item])}
  1199. new_items -= seen_items
  1200. items.extend(new_items)
  1201. seen_items.update(new_items)
  1202. if not looped and len(items) > 1:
  1203. orig_size = len(items)
  1204. h = frozenset(seen_items)
  1205. if h not in seen_hints:
  1206. mincands.append(h)
  1207. seen_hints.add(h)
  1208. looped = True
  1209. if len(items) != orig_size:
  1210. h = frozenset(seen_items)
  1211. if h != mincands[-1] and h not in seen_hints:
  1212. candidates.append(h)
  1213. seen_hints.add(h)
  1214. return [ candidates, mincands ]
  1215. def run_auto_hinter(self):
  1216. mi_factory = self._migration_item_factory
  1217. for l in self.get_auto_hinter_hints(self.upgrade_me):
  1218. for hint in l:
  1219. self.do_hint("easy", "autohinter", [mi_factory.parse_item("%s/%s" % (x[0], x[1]), auto_correct=False)
  1220. for x in sorted(hint)])
  1221. def nuninst_arch_report(self, nuninst, arch):
  1222. """Print a report of uninstallable packages for one architecture."""
  1223. all = defaultdict(set)
  1224. binaries_t = self.suite_info.target_suite.binaries
  1225. for p in nuninst[arch]:
  1226. pkg = binaries_t[arch][p]
  1227. all[(pkg.source, pkg.source_version)].add(p)
  1228. print('* %s' % arch)
  1229. for (src, ver), pkgs in sorted(all.items()):
  1230. print(' %s (%s): %s' % (src, ver, ' '.join(sorted(pkgs))))
  1231. print()
  1232. def main(self):
  1233. """Main method
  1234. This is the entry point for the class: it includes the list of calls
  1235. for the member methods which will produce the output files.
  1236. """
  1237. # if running in --print-uninst mode, quit
  1238. if self.options.print_uninst:
  1239. return
  1240. # if no actions are provided, build the excuses and sort them
  1241. elif not self.options.actions:
  1242. self.write_excuses()
  1243. # otherwise, use the actions provided by the command line
  1244. else:
  1245. self.upgrade_me = self.options.actions.split()
  1246. if self.options.compute_migrations or self.options.hint_tester:
  1247. if self.options.dry_run:
  1248. self.logger.info("Upgrade output not (also) written to a separate file"
  1249. " as this is a dry-run.")
  1250. elif hasattr(self.options, 'upgrade_output'):
  1251. upgrade_output = getattr(self.options, 'upgrade_output')
  1252. file_handler = logging.FileHandler(upgrade_output, mode='w', encoding='utf-8')
  1253. output_formatter = logging.Formatter('%(message)s')
  1254. file_handler.setFormatter(output_formatter)
  1255. self.output_logger.addHandler(file_handler)
  1256. self.logger.info("Logging upgrade output to %s", upgrade_output)
  1257. else:
  1258. self.logger.info("Upgrade output not (also) written to a separate file"
  1259. " as the UPGRADE_OUTPUT configuration is not provided.")
  1260. # run the hint tester
  1261. if self.options.hint_tester:
  1262. self.hint_tester()
  1263. # run the upgrade test
  1264. else:
  1265. self.upgrade_testing()
  1266. self.logger.info('> Stats from the installability tester')
  1267. for stat in self._inst_tester.stats.stats():
  1268. self.logger.info('> %s', stat)
  1269. else:
  1270. self.logger.info('Migration computation skipped as requested.')
  1271. if not self.options.dry_run:
  1272. self._policy_engine.save_state(self)
  1273. logging.shutdown()
  1274. if __name__ == '__main__':
  1275. Britney().main()