-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbritney.py
executable file
·3014 lines (2562 loc) · 138 KB
/
britney.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-
# Copyright (C) 2001-2008 Anthony Towns <[email protected]>
# Andreas Barth <[email protected]>
# Fabio Tranchitella <[email protected]>
# Copyright (C) 2010-2013 Adam D. Barratt <[email protected]>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
"""
= Introduction =
This is the Debian testing updater script, also known as "Britney".
Packages are usually installed into the `testing' distribution after
they have undergone some degree of testing in unstable. The goal of
this software is to do this task in a smart way, allowing testing
to always be fully installable and close to being a release candidate.
Britney's source code is split between two different but related tasks:
the first one is the generation of the update excuses, while the
second tries to update testing with the valid candidates; first
each package alone, then larger and even larger sets of packages
together. Each try is accepted if testing is not more uninstallable
after the update than before.
= Data Loading =
In order to analyze the entire Debian distribution, Britney needs to
load in memory the whole archive: this means more than 10.000 packages
for twelve architectures, as well as the dependency interconnections
between them. For this reason, the memory requirements for running this
software are quite high and at least 1 gigabyte of RAM should be available.
Britney loads the source packages from the `Sources' file and the binary
packages from the `Packages_${arch}' files, where ${arch} is substituted
with the supported architectures. While loading the data, the software
analyzes the dependencies and builds a directed weighted graph in memory
with all the interconnections between the packages (see Britney.read_sources
and Britney.read_binaries).
Other than source and binary packages, Britney loads the following data:
* BugsV, which contains the list of release-critical bugs for a given
version of a source or binary package (see RCBugPolicy.read_bugs).
* Dates, which contains the date of the upload of a given version
of a source package (see Britney.read_dates).
* Urgencies, which contains the urgency of the upload of a given
version of a source package (see AgePolicy._read_urgencies).
* Hints, which contains lists of commands which modify the standard behaviour
of Britney (see Britney.read_hints).
For a more detailed explanation about the format of these files, please read
the documentation of the related methods. The exact meaning of them will be
instead explained in the chapter "Excuses Generation".
= Excuses =
An excuse is a detailed explanation of why a package can or cannot
be updated in the testing distribution from a newer package in
another distribution (like for example unstable). The main purpose
of the excuses is to be written in an HTML file which will be
published over HTTP. The maintainers will be able to parse it manually
or automatically to find the explanation of why their packages have
been updated or not.
== Excuses generation ==
These are the steps (with references to method names) that Britney
does for the generation of the update excuses.
* If a source package is available in testing but it is not
present in unstable and no binary packages in unstable are
built from it, then it is marked for removal.
* Every source package in unstable and testing-proposed-updates,
if already present in testing, is checked for binary-NMUs, new
or dropped binary packages in all the supported architectures
(see Britney.should_upgrade_srcarch). The steps to detect if an
upgrade is needed are:
1. If there is a `remove' hint for the source package, the package
is ignored: it will be removed and not updated.
2. For every binary package built from the new source, it checks
for unsatisfied dependencies, new binary packages and updated
binary packages (binNMU), excluding the architecture-independent
ones, and packages not built from the same source.
3. For every binary package built from the old source, it checks
if it is still built from the new source; if this is not true
and the package is not architecture-independent, the script
removes it from testing.
4. Finally, if there is something worth doing (eg. a new or updated
binary package) and nothing wrong it marks the source package
as "Valid candidate", or "Not considered" if there is something
wrong which prevented the update.
* Every source package in unstable and testing-proposed-updates is
checked for upgrade (see Britney.should_upgrade_src). The steps
to detect if an upgrade is needed are:
1. If the source package in testing is more recent the new one
is ignored.
2. If the source package doesn't exist (is fake), which means that
a binary package refers to it but it is not present in the
`Sources' file, the new one is ignored.
3. If the package doesn't exist in testing, the urgency of the
upload is ignored and set to the default (actually `low').
4. If there is a `remove' hint for the source package, the package
is ignored: it will be removed and not updated.
5. If there is a `block' hint for the source package without an
`unblock` hint or a `block-all source`, the package is ignored.
6. If there is a `block-udeb' hint for the source package, it will
have the same effect as `block', but may only be cancelled by
a subsequent `unblock-udeb' hint.
7. If the suite is unstable, the update can go ahead only if the
upload happened more than the minimum days specified by the
urgency of the upload; if this is not true, the package is
ignored as `too-young'. Note that the urgency is sticky, meaning
that the highest urgency uploaded since the previous testing
transition is taken into account.
8. If the suite is unstable, all the architecture-dependent binary
packages and the architecture-independent ones for the `nobreakall'
architectures have to be built from the source we are considering.
If this is not true, then these are called `out-of-date'
architectures and the package is ignored.
9. The source package must have at least one binary package, otherwise
it is ignored.
10. If the suite is unstable, the new source package must have no
release critical bugs which do not also apply to the testing
one. If this is not true, the package is ignored as `buggy'.
11. If there is a `force' hint for the source package, then it is
updated even if it is marked as ignored from the previous steps.
12. If the suite is {testing-,}proposed-updates, the source package can
be updated only if there is an explicit approval for it. Unless
a `force' hint exists, the new package must also be available
on all of the architectures for which it has binary packages in
testing.
13. If the package will be ignored, mark it as "Valid candidate",
otherwise mark it as "Not considered".
* The list of `remove' hints is processed: if the requested source
package is not already being updated or removed and the version
actually in testing is the same specified with the `remove' hint,
it is marked for removal.
* The excuses are sorted by the number of days from the last upload
(days-old) and by name.
* A list of unconsidered excuses (for which the package is not upgraded)
is built. Using this list, all of the excuses depending on them are
marked as invalid "impossible dependencies".
* The excuses are written in an HTML file.
"""
from __future__ import print_function
import os
import sys
import time
import optparse
import apt_pkg
from collections import defaultdict, namedtuple
from functools import reduce
from itertools import product
from operator import attrgetter
from urllib.parse import quote
from installability.builder import InstallabilityTesterBuilder
from excuse import Excuse
from migrationitem import MigrationItem
from hints import HintParser
from britney_util import (old_libraries_format, undo_changes,
compute_reverse_tree, possibly_compressed,
read_nuninst, write_nuninst, write_heidi,
eval_uninst, newly_uninst, make_migrationitem,
write_excuses, write_heidi_delta, write_controlfiles,
old_libraries, is_nuninst_asgood_generous,
clone_nuninst, check_installability)
from policies.policy import AgePolicy, RCBugPolicy, PolicyVerdict
from consts import (VERSION, SECTION, BINARIES, MAINTAINER, FAKESRC,
SOURCE, SOURCEVER, ARCHITECTURE, CONFLICTS, DEPENDS,
PROVIDES, MULTIARCH)
__author__ = 'Fabio Tranchitella and the Debian Release Team'
__version__ = '2.0'
# NB: ESSENTIAL deliberately skipped as the 2011 and 2012
# parts of the live-data tests require it (britney merges
# this field correctly from the unstable version where
# available)
check_field_name = dict((globals()[fn], fn) for fn in
(
"SOURCE SOURCEVER ARCHITECTURE MULTIARCH" +
" DEPENDS CONFLICTS PROVIDES"
).split()
)
check_fields = sorted(check_field_name)
BinaryPackageId = namedtuple('BinaryPackageId', [
'package_name',
'version',
'architecture',
])
BinaryPackage = namedtuple('BinaryPackage', [
'version',
'section',
'source',
'source_version',
'architecture',
'multi_arch',
'depends',
'conflicts',
'provides',
'is_essential',
'pkg_id',
])
class Britney(object):
"""Britney, the Debian testing updater script
This is the script that updates the testing distribution. It is executed
each day after the installation of the updated packages. It generates the
`Packages' files for the testing distribution, but it does so in an
intelligent manner; it tries to avoid any inconsistency and to use only
non-buggy packages.
For more documentation on this script, please read the Developers Reference.
"""
HINTS_HELPERS = ("easy", "hint", "remove", "block", "block-udeb", "unblock", "unblock-udeb", "approve")
HINTS_STANDARD = ("urgent", "age-days") + HINTS_HELPERS
HINTS_ALL = ("force", "force-hint", "block-all") + HINTS_STANDARD
def __init__(self):
"""Class constructor
This method initializes and populates the data lists, which contain all
the information needed by the other methods of the class.
"""
# parse the command line arguments
self.policies = []
self.__parse_arguments()
MigrationItem.set_architectures(self.options.architectures)
# initialize the apt_pkg back-end
apt_pkg.init()
self.sources = {}
self.binaries = {}
self.all_selected = []
self.excuses = {}
try:
self.hints = self.read_hints(self.options.hintsdir)
except AttributeError:
self.hints = self.read_hints(os.path.join(self.options.unstable, 'Hints'))
if self.options.nuninst_cache:
self.log("Not building the list of non-installable packages, as requested", type="I")
if self.options.print_uninst:
print('* summary')
print('\n'.join('%4d %s' % (len(nuninst[x]), x) for x in self.options.architectures))
return
self.all_binaries = {}
# read the source and binary packages for the involved distributions
self.sources['testing'] = self.read_sources(self.options.testing)
self.sources['unstable'] = self.read_sources(self.options.unstable)
for suite in ('tpu', 'pu'):
if hasattr(self.options, suite):
self.sources[suite] = self.read_sources(getattr(self.options, suite))
else:
self.sources[suite] = {}
self.binaries['testing'] = {}
self.binaries['unstable'] = {}
self.binaries['tpu'] = {}
self.binaries['pu'] = {}
for arch in self.options.architectures:
self.binaries['unstable'][arch] = self.read_binaries(self.options.unstable, "unstable", arch)
for suite in ('tpu', 'pu'):
if hasattr(self.options, suite):
self.binaries[suite][arch] = self.read_binaries(getattr(self.options, suite), suite, arch)
else:
# _build_installability_tester relies on this being
# properly initialised, so insert two empty dicts
# here.
self.binaries[suite][arch] = ({}, {})
# Load testing last as some live-data tests have more complete information in
# unstable
self.binaries['testing'][arch] = self.read_binaries(self.options.testing, "testing", arch)
try:
constraints_file = os.path.join(self.options.static_input_dir, 'constraints')
faux_packages = os.path.join(self.options.static_input_dir, 'faux-packages')
except AttributeError:
self.log("The static_input_dir option is not set", type='I')
constraints_file = None
faux_packages = None
if faux_packages is not None and os.path.exists(faux_packages):
self.log("Loading faux packages from %s" % faux_packages, type='I')
self._load_faux_packages(faux_packages)
elif faux_packages is not None:
self.log("No Faux packages as %s does not exist" % faux_packages, type='I')
if constraints_file is not None and os.path.exists(constraints_file):
self.log("Loading constraints from %s" % constraints_file, type='I')
self.constraints = self._load_constraints(constraints_file)
else:
if constraints_file is not None:
self.log("No constraints as %s does not exist" % constraints_file, type='I')
self.constraints = {
'keep-installable': [],
}
self.log("Compiling Installability tester", type="I")
self._build_installability_tester(self.options.architectures)
if not self.options.nuninst_cache:
self.log("Building the list of non-installable packages for the full archive", type="I")
nuninst = {}
self._inst_tester.compute_testing_installability()
for arch in self.options.architectures:
self.log("> Checking for non-installable packages for architecture %s" % arch, type="I")
result = self.get_nuninst(arch, build=True)
nuninst.update(result)
self.log("> Found %d non-installable packages" % len(nuninst[arch]), type="I")
if self.options.print_uninst:
self.nuninst_arch_report(nuninst, arch)
if self.options.print_uninst:
print('* summary')
print('\n'.join(map(lambda x: '%4d %s' % (len(nuninst[x]), x), self.options.architectures)))
return
else:
write_nuninst(self.options.noninst_status, nuninst)
stats = self._inst_tester.compute_stats()
self.log("> Installability tester statistics (per architecture)", type="I")
for arch in self.options.architectures:
arch_stat = stats[arch]
self.log("> %s" % arch, type="I")
for stat in arch_stat.stat_summary():
self.log("> - %s" % stat, type="I")
for policy in self.policies:
policy.hints = self.hints
policy.initialise(self)
def merge_pkg_entries(self, package, parch, pkg_entry1, pkg_entry2,
check_fields=check_fields, check_field_name=check_field_name):
bad = []
for f in check_fields:
if pkg_entry1[f] != pkg_entry2[f]:
bad.append((f, pkg_entry1[f], pkg_entry2[f]))
if bad:
self.log("Mismatch found %s %s %s differs" % (
package, pkg_entry1.version, parch), type="E")
for f, v1, v2 in bad:
self.log(" ... %s %s != %s" % (check_field_name[f], v1, v2))
raise ValueError("Invalid data set")
# Merge ESSENTIAL if necessary
assert pkg_entry1.is_essential or not pkg_entry2.is_essential
def __parse_arguments(self):
"""Parse the command line arguments
This method parses and initializes the command line arguments.
While doing so, it preprocesses some of the options to be converted
in a suitable form for the other methods of the class.
"""
# initialize the parser
parser = optparse.OptionParser(version="%prog")
parser.add_option("-v", "", action="count", dest="verbose", help="enable verbose output")
parser.add_option("-c", "--config", action="store", dest="config", default="/etc/britney.conf",
help="path for the configuration file")
parser.add_option("", "--architectures", action="store", dest="architectures", default=None,
help="override architectures from configuration file")
parser.add_option("", "--actions", action="store", dest="actions", default=None,
help="override the list of actions to be performed")
parser.add_option("", "--hints", action="store", dest="hints", default=None,
help="additional hints, separated by semicolons")
parser.add_option("", "--hint-tester", action="store_true", dest="hint_tester", default=None,
help="provide a command line interface to test hints")
parser.add_option("", "--dry-run", action="store_true", dest="dry_run", default=False,
help="disable all outputs to the testing directory")
parser.add_option("", "--control-files", action="store_true", dest="control_files", default=False,
help="enable control files generation")
parser.add_option("", "--nuninst-cache", action="store_true", dest="nuninst_cache", default=False,
help="do not build the non-installability status, use the cache from file")
parser.add_option("", "--print-uninst", action="store_true", dest="print_uninst", default=False,
help="just print a summary of uninstallable packages")
parser.add_option("", "--components", action="store", dest="components",
help="Sources/Packages are laid out by components listed (, sep)")
(self.options, self.args) = parser.parse_args()
# integrity checks
if self.options.nuninst_cache and self.options.print_uninst:
self.log("nuninst_cache and print_uninst are mutually exclusive!", type="E")
sys.exit(1)
# if the configuration file exists, then read it and set the additional options
elif not os.path.isfile(self.options.config):
self.log("Unable to read the configuration file (%s), exiting!" % self.options.config, type="E")
sys.exit(1)
# minimum days for unstable-testing transition and the list of hints
# are handled as an ad-hoc case
MINDAYS = {}
self.HINTS = {'command-line': self.HINTS_ALL}
with open(self.options.config, encoding='utf-8') as config:
for line in config:
if '=' in line and not line.strip().startswith('#'):
k, v = line.split('=', 1)
k = k.strip()
v = v.strip()
if k.startswith("MINDAYS_"):
MINDAYS[k.split("_")[1].lower()] = int(v)
elif k.startswith("HINTS_"):
self.HINTS[k.split("_")[1].lower()] = \
reduce(lambda x,y: x+y, [hasattr(self, "HINTS_" + i) and getattr(self, "HINTS_" + i) or (i,) for i in v.split()])
elif not hasattr(self.options, k.lower()) or \
not getattr(self.options, k.lower()):
setattr(self.options, k.lower(), v)
if getattr(self.options, "components", None):
self.options.components = [s.strip() for s in self.options.components.split(",")]
else:
self.options.components = None
if self.options.control_files and self.options.components:
# We cannot regenerate the control files correctly when reading from an
# actual mirror (we don't which package goes in what component etc.).
self.log("Cannot use --control-files with mirror-layout (components)!", type="E")
sys.exit(1)
if not hasattr(self.options, "heidi_delta_output"):
self.options.heidi_delta_output = self.options.heidi_output + "Delta"
self.options.nobreakall_arches = self.options.nobreakall_arches.split()
self.options.fucked_arches = self.options.fucked_arches.split()
self.options.break_arches = self.options.break_arches.split()
self.options.new_arches = self.options.new_arches.split()
# Sort the architecture list
allarches = sorted(self.options.architectures.split())
arches = [x for x in allarches if x in self.options.nobreakall_arches]
arches += [x for x in allarches if x not in arches and x not in self.options.fucked_arches]
arches += [x for x in allarches if x not in arches and x not in self.options.break_arches]
arches += [x for x in allarches if x not in arches and x not in self.options.new_arches]
arches += [x for x in allarches if x not in arches]
self.options.architectures = [sys.intern(arch) for arch in arches]
self.options.smooth_updates = self.options.smooth_updates.split()
if not hasattr(self.options, 'ignore_cruft') or \
self.options.ignore_cruft == "0":
self.options.ignore_cruft = False
self.policies.append(AgePolicy(self.options, MINDAYS))
self.policies.append(RCBugPolicy(self.options))
def log(self, msg, type="I"):
"""Print info messages according to verbosity level
An easy-and-simple log method which prints messages to the standard
output. The type parameter controls the urgency of the message, and
can be equal to `I' for `Information', `W' for `Warning' and `E' for
`Error'. Warnings and errors are always printed, and information is
printed only if verbose logging is enabled.
"""
if self.options.verbose or type in ("E", "W"):
print("%s: [%s] - %s" % (type, time.asctime(), msg))
def _load_faux_packages(self, faux_packages_file):
"""Loads fake packages
In rare cases, it is useful to create a "fake" package that can be used to satisfy
dependencies. This is usually needed for packages that are not shipped directly
on this mirror but is a prerequisite for using this mirror (e.g. some vendors provide
non-distributable "setup" packages and contrib/non-free packages depend on these).
:param faux_packages_file: Path to the file containing the fake package definitions
"""
tag_file = apt_pkg.TagFile(faux_packages_file)
get_field = tag_file.section.get
step = tag_file.step
no = 0
while step():
no += 1
pkg_name = get_field('Package', None)
if pkg_name is None:
raise ValueError("Missing Package field in paragraph %d (file %s)" % (no, faux_packages_file))
pkg_name = sys.intern(pkg_name)
version = sys.intern(get_field('Version', '1.0-1'))
provides_raw = get_field('Provides')
archs_raw = get_field('Architecture', None)
component = get_field('Component', 'non-free')
if archs_raw:
archs = archs_raw.split()
else:
archs = self.options.architectures
faux_section = 'faux'
if component != 'main':
faux_section = "%s/faux" % component
src_data = [version,
sys.intern(faux_section),
[],
None,
True,
]
self.sources['testing'][pkg_name] = src_data
self.sources['unstable'][pkg_name] = src_data
for arch in archs:
pkg_id = BinaryPackageId(pkg_name, version, arch)
if provides_raw:
provides = self._parse_provides(pkg_id, provides_raw)
else:
provides = []
bin_data = BinaryPackage(version,
faux_section,
pkg_name,
version,
arch,
get_field('Multi-Arch'),
None,
None,
provides,
False,
pkg_id,
)
src_data[BINARIES].append(pkg_id)
self.binaries['testing'][arch][0][pkg_name] = bin_data
self.binaries['unstable'][arch][0][pkg_name] = bin_data
self.all_binaries[pkg_id] = bin_data
def _load_constraints(self, constraints_file):
"""Loads configurable constraints
The constraints file can contain extra rules that Britney should attempt
to satisfy. Examples can be "keep package X in testing and ensure it is
installable".
:param constraints_file: Path to the file containing the constraints
"""
tag_file = apt_pkg.TagFile(constraints_file)
get_field = tag_file.section.get
step = tag_file.step
no = 0
faux_version = sys.intern('1')
faux_section = sys.intern('faux')
keep_installable = []
constraints = {
'keep-installable': keep_installable
}
while step():
no += 1
pkg_name = get_field('Fake-Package-Name', None)
if pkg_name is None:
raise ValueError("Missing Fake-Package-Name field in paragraph %d (file %s)" % (no, constraints_file))
pkg_name = sys.intern(pkg_name)
def mandatory_field(x):
v = get_field(x, None)
if v is None:
raise ValueError("Missing %s field for %s (file %s)" % (x, pkg_name, constraints_file))
return v
constraint = mandatory_field('Constraint')
if constraint not in {'present-and-installable'}:
raise ValueError("Unsupported constraint %s for %s (file %s)" % (constraint, pkg_name, constraints_file))
self.log(" - constraint %s" % pkg_name, type='I')
pkg_list = [x.strip() for x in mandatory_field('Package-List').split("\n") if x.strip() != '' and not x.strip().startswith("#")]
src_data = [faux_version,
faux_section,
[],
None,
True,
]
self.sources['testing'][pkg_name] = src_data
self.sources['unstable'][pkg_name] = src_data
keep_installable.append(pkg_name)
for arch in self.options.architectures:
deps = []
for pkg_spec in pkg_list:
s = pkg_spec.split(None, 1)
if len(s) == 1:
deps.append(s[0])
else:
pkg, arch_res = s
if not (arch_res.startswith('[') and arch_res.endswith(']')):
raise ValueError("Invalid arch-restriction on %s - should be [arch1 arch2] (for %s file %s)"
% (pkg, pkg_name, constraints_file))
arch_res = arch_res[1:-1].split()
if not arch_res:
msg = "Empty arch-restriction for %s: Uses comma or negation (for %s file %s)"
raise ValueError(msg % (pkg, pkg_name, constraints_file))
for a in arch_res:
if a == arch:
deps.append(pkg)
elif ',' in a or '!' in a:
msg = "Invalid arch-restriction for %s: Uses comma or negation (for %s file %s)"
raise ValueError(msg % (pkg, pkg_name, constraints_file))
pkg_id = BinaryPackageId(pkg_name, faux_version, arch)
bin_data = BinaryPackage(faux_version,
faux_section,
pkg_name,
faux_version,
arch,
'no',
', '.join(deps),
None,
[],
False,
pkg_id,
)
src_data[BINARIES].append(pkg_id)
self.binaries['testing'][arch][0][pkg_name] = bin_data
self.binaries['unstable'][arch][0][pkg_name] = bin_data
self.all_binaries[pkg_id] = bin_data
return constraints
def _build_installability_tester(self, archs):
"""Create the installability tester"""
solvers = self.get_dependency_solvers
binaries = self.binaries
builder = InstallabilityTesterBuilder()
for (dist, arch) in product(binaries, archs):
testing = (dist == 'testing')
for pkgname in binaries[dist][arch][0]:
pkgdata = binaries[dist][arch][0][pkgname]
pkg_id = pkgdata.pkg_id
if not builder.add_binary(pkg_id, essential=pkgdata.is_essential,
in_testing=testing):
continue
depends = []
conflicts = []
possible_dep_ranges = {}
# We do not differentiate between depends and pre-depends
if pkgdata.depends:
depends.extend(apt_pkg.parse_depends(pkgdata.depends, False))
if pkgdata.conflicts:
conflicts = apt_pkg.parse_depends(pkgdata.conflicts, False)
with builder.relation_builder(pkg_id) as relations:
for (al, dep) in [(depends, True), \
(conflicts, False)]:
for block in al:
sat = set()
for dep_dist in binaries:
dep_packages_s_a = binaries[dep_dist][arch]
pkgs = solvers(block, dep_packages_s_a)
for p in pkgs:
# version and arch is already interned, but solvers use
# the package name extracted from the field and it is therefore
# not interned.
pdata = dep_packages_s_a[0][p]
dep_pkg_id = pdata.pkg_id
if dep:
sat.add(dep_pkg_id)
elif pkg_id != dep_pkg_id:
# if t satisfies its own
# conflicts relation, then it
# is using §7.6.2
relations.add_breaks(dep_pkg_id)
if dep:
if len(block) != 1:
relations.add_dependency_clause(sat)
else:
# This dependency might be a part
# of a version-range a la:
#
# Depends: pkg-a (>= 1),
# pkg-a (<< 2~)
#
# In such a case we want to reduce
# that to a single clause for
# efficiency.
#
# In theory, it could also happen
# with "non-minimal" dependencies
# a la:
#
# Depends: pkg-a, pkg-a (>= 1)
#
# But dpkg is known to fix that up
# at build time, so we will
# probably only see "ranges" here.
key = block[0][0]
if key in possible_dep_ranges:
possible_dep_ranges[key] &= sat
else:
possible_dep_ranges[key] = sat
if dep:
for clause in possible_dep_ranges.values():
relations.add_dependency_clause(clause)
self._inst_tester = builder.build()
# Data reading/writing methods
# ----------------------------
def _read_sources_file(self, filename, sources=None, intern=sys.intern):
if sources is None:
sources = {}
self.log("Loading source packages from %s" % filename)
Packages = apt_pkg.TagFile(filename)
get_field = Packages.section.get
step = Packages.step
while step():
if get_field('Extra-Source-Only', 'no') == 'yes':
# Ignore sources only referenced by Built-Using
continue
pkg = get_field('Package')
ver = get_field('Version')
# There may be multiple versions of the source package
# (in unstable) if some architectures have out-of-date
# binaries. We only ever consider the source with the
# largest version for migration.
if pkg in sources and apt_pkg.version_compare(sources[pkg][0], ver) > 0:
continue
sources[intern(pkg)] = [intern(ver),
intern(get_field('Section')),
[],
get_field('Maintainer'),
False,
]
return sources
def read_sources(self, basedir):
"""Read the list of source packages from the specified directory
The source packages are read from the `Sources' file within the
directory specified as `basedir' parameter. Considering the
large amount of memory needed, not all the fields are loaded
in memory. The available fields are Version, Maintainer and Section.
The method returns a list where every item represents a source
package as a dictionary.
"""
if self.options.components:
sources = {}
for component in self.options.components:
filename = os.path.join(basedir, component, "source", "Sources")
filename = possibly_compressed(filename)
self._read_sources_file(filename, sources)
else:
filename = os.path.join(basedir, "Sources")
sources = self._read_sources_file(filename)
return sources
def _parse_provides(self, pkg_id, provides_raw):
parts = apt_pkg.parse_depends(provides_raw, False)
nprov = []
for or_clause in parts:
if len(or_clause) != 1:
msg = "Ignoring invalid provides in %s: Alternatives [%s]" % (str(pkg_id), str(or_clause))
self.log(msg, type='W')
continue
for part in or_clause:
provided, provided_version, op = part
if op != '' and op != '=':
msg = "Ignoring invalid provides in %s: %s (%s %s)" % (str(pkg_id), provided, op, provided_version)
self.log(msg, type='W')
continue
provided = sys.intern(provided)
provided_version = sys.intern(provided_version)
part = (provided, provided_version, sys.intern(op))
nprov.append(part)
return nprov
def _read_packages_file(self, filename, arch, srcdist, packages=None, intern=sys.intern):
self.log("Loading binary packages from %s" % filename)
if packages is None:
packages = {}
all_binaries = self.all_binaries
Packages = apt_pkg.TagFile(filename)
get_field = Packages.section.get
step = Packages.step
while step():
pkg = get_field('Package')
version = get_field('Version')
# There may be multiple versions of any arch:all packages
# (in unstable) if some architectures have out-of-date
# binaries. We only ever consider the package with the
# largest version for migration.
pkg = intern(pkg)
version = intern(version)
pkg_id = BinaryPackageId(pkg, version, arch)
if pkg in packages:
old_pkg_data = packages[pkg]
if apt_pkg.version_compare(old_pkg_data.version, version) > 0:
continue
old_pkg_id = old_pkg_data.pkg_id
old_src_binaries = srcdist[old_pkg_data[SOURCE]][BINARIES]
old_src_binaries.remove(old_pkg_id)
# This may seem weird at first glance, but the current code rely
# on this behaviour to avoid issues like #709460. Admittedly it
# is a special case, but Britney will attempt to remove the
# arch:all packages without this. Even then, this particular
# stop-gap relies on the packages files being sorted by name
# and the version, so it is not particularly resilient.
if pkg_id not in old_src_binaries:
old_src_binaries.append(pkg_id)
# Merge Pre-Depends with Depends and Conflicts with
# Breaks. Britney is not interested in the "finer
# semantic differences" of these fields anyway.
pdeps = get_field('Pre-Depends')
deps = get_field('Depends')
if deps and pdeps:
deps = pdeps + ', ' + deps
elif pdeps:
deps = pdeps
ess = False
if get_field('Essential', 'no') == 'yes':
ess = True
final_conflicts_list = []
conflicts = get_field('Conflicts')
if conflicts:
final_conflicts_list.append(conflicts)
breaks = get_field('Breaks')
if breaks:
final_conflicts_list.append(breaks)
source = pkg
source_version = version
# retrieve the name and the version of the source package
source_raw = get_field('Source')
if source_raw:
source = intern(source_raw.split(" ")[0])
if "(" in source_raw:
source_version = intern(source_raw[source_raw.find("(")+1:source_raw.find(")")])
provides_raw = get_field('Provides')
if provides_raw:
provides = self._parse_provides(pkg_id, provides_raw)
else:
provides = []
dpkg = BinaryPackage(version,
intern(get_field('Section')),
source,
source_version,
intern(get_field('Architecture')),
get_field('Multi-Arch'),
deps,
', '.join(final_conflicts_list) or None,
provides,
ess,
pkg_id,
)
# if the source package is available in the distribution, then register this binary package
if source in srcdist:
# There may be multiple versions of any arch:all packages
# (in unstable) if some architectures have out-of-date
# binaries. We only want to include the package in the
# source -> binary mapping once. It doesn't matter which
# of the versions we include as only the package name and
# architecture are recorded.
if pkg_id not in srcdist[source][BINARIES]:
srcdist[source][BINARIES].append(pkg_id)
# if the source package doesn't exist, create a fake one
else:
srcdist[source] = [source_version, 'faux', [pkg_id], None, True]
# add the resulting dictionary to the package list
packages[pkg] = dpkg
if pkg_id in all_binaries:
self.merge_pkg_entries(pkg, arch, all_binaries[pkg_id], dpkg)
else:
all_binaries[pkg_id] = dpkg
# add the resulting dictionary to the package list
packages[pkg] = dpkg
return packages
def read_binaries(self, basedir, distribution, arch):
"""Read the list of binary packages from the specified directory
The binary packages are read from the `Packages' files for `arch'.
If components are specified, the files
for each component are loaded according to the usual Debian mirror
layout.
If no components are specified, a single file named
`Packages_${arch}' is expected to be within the directory
specified as `basedir' parameter, replacing ${arch} with the
value of the arch parameter.
Considering the
large amount of memory needed, not all the fields are loaded
in memory. The available fields are Version, Source, Multi-Arch,
Depends, Conflicts, Provides and Architecture.
After reading the packages, reverse dependencies are computed
and saved in the `rdepends' keys, and the `Provides' field is
used to populate the virtual packages list.
The dependencies are parsed with the apt_pkg.parse_depends method,
and they are stored both as the format of its return value and
text.
The method returns a tuple. The first element is a list where
every item represents a binary package as a dictionary; the second
element is a dictionary which maps virtual packages to real
packages that provide them.
"""
if self.options.components:
packages = {}
for component in self.options.components:
binary_dir = "binary-%s" % arch
filename = os.path.join(basedir,
component, binary_dir, 'Packages')
try:
filename = possibly_compressed(filename)
except FileNotFoundError as e:
if arch not in self.options.new_arches:
raise
self.log("Ignoring missing file for new arch %s: %s" % (arch, filename))
continue
udeb_filename = os.path.join(basedir,
component, "debian-installer",
binary_dir, "Packages")
# We assume the udeb Packages file is present if the
# regular one is present
udeb_filename = possibly_compressed(udeb_filename)
self._read_packages_file(filename, arch,
self.sources[distribution], packages)
self._read_packages_file(udeb_filename, arch,
self.sources[distribution], packages)