~launchpad-pqm/launchpad/devel

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
# Copyright 2009-2011 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

# pylint: disable-msg=E0211,E0213

"""Archive interfaces."""

__metaclass__ = type

__all__ = [
    'ALLOW_RELEASE_BUILDS',
    'AlreadySubscribed',
    'ArchiveDependencyError',
    'ArchiveDisabled',
    'ArchiveNotPrivate',
    'CannotCopy',
    'CannotSwitchPrivacy',
    'ComponentNotFound',
    'CannotRestrictArchitectures',
    'CannotUploadToArchive',
    'CannotUploadToPPA',
    'CannotUploadToPocket',
    'ForbiddenByFeatureFlag',
    'FULL_COMPONENT_SUPPORT',
    'IArchive',
    'IArchiveAppend',
    'IArchiveCommercial',
    'IArchiveEdit',
    'IArchiveView',
    'IArchiveEditDependenciesForm',
    'IArchivePublic',
    'IArchiveSet',
    'IDistributionArchive',
    'InsufficientUploadRights',
    'InvalidComponent',
    'InvalidExternalDependencies',
    'InvalidPocketForPartnerArchive',
    'InvalidPocketForPPA',
    'IPPA',
    'MAIN_ARCHIVE_PURPOSES',
    'NoRightsForArchive',
    'NoRightsForComponent',
    'NoSuchPPA',
    'NoTokensForTeams',
    'PocketNotFound',
    'VersionRequiresName',
    'default_name_by_purpose',
    'validate_external_dependencies',
    ]

import httplib
from urlparse import urlparse

from lazr.enum import DBEnumeratedType
from lazr.restful.declarations import (
    call_with,
    error_status,
    export_as_webservice_entry,
    export_factory_operation,
    export_operation_as,
    export_read_operation,
    export_write_operation,
    exported,
    operation_for_version,
    operation_parameters,
    operation_returns_collection_of,
    operation_returns_entry,
    rename_parameters_as,
    REQUEST_USER,
    )
from lazr.restful.fields import (
    CollectionField,
    Reference,
    )
from zope.interface import (
    Attribute,
    Interface,
    )
from zope.schema import (
    Bool,
    Choice,
    Datetime,
    Int,
    List,
    Object,
    Text,
    TextLine,
    )

from canonical.launchpad import _
from canonical.launchpad.interfaces.launchpad import IPrivacy
from lp.app.errors import NameLookupFailed
from lp.app.validators.name import name_validator
from lp.registry.interfaces.gpg import IGPGKey
from lp.registry.interfaces.person import IPerson
from lp.registry.interfaces.role import IHasOwner
from lp.services.fields import (
    PersonChoice,
    PublicPersonChoice,
    StrippedTextLine,
    )
from lp.soyuz.enums import ArchivePurpose
from lp.soyuz.interfaces.buildrecords import IHasBuildRecords
from lp.soyuz.interfaces.component import IComponent


@error_status(httplib.BAD_REQUEST)
class ArchiveDependencyError(Exception):
    """Raised when an `IArchiveDependency` does not fit the context archive.

    A given dependency is considered inappropriate when:

     * It is the archive itself,
     * It is not a PPA,
     * It is already recorded.
    """


# Exceptions used in the webservice that need to be in this file to get
# picked up therein.
@error_status(httplib.BAD_REQUEST)
class CannotCopy(Exception):
    """Exception raised when a copy cannot be performed."""


@error_status(httplib.FORBIDDEN)
class ForbiddenByFeatureFlag(Exception):
    """Exception raised when using a method protected by a feature flag.
    """


@error_status(httplib.BAD_REQUEST)
class CannotSwitchPrivacy(Exception):
    """Raised when switching the privacy of an archive that has
    publishing records."""


class PocketNotFound(NameLookupFailed):
    """Invalid pocket."""
    _message_prefix = "No such pocket"


@error_status(httplib.BAD_REQUEST)
class AlreadySubscribed(Exception):
    """Raised when creating a subscription for a subscribed person."""


@error_status(httplib.BAD_REQUEST)
class ArchiveNotPrivate(Exception):
    """Raised when creating an archive subscription for a public archive."""


@error_status(httplib.BAD_REQUEST)
class NoTokensForTeams(Exception):
    """Raised when creating a token for a team, rather than a person."""


class ComponentNotFound(NameLookupFailed):
    """Invalid source name."""
    _message_prefix = 'No such component'


@error_status(httplib.BAD_REQUEST)
class InvalidComponent(Exception):
    """Invalid component name."""


class NoSuchPPA(NameLookupFailed):
    """Raised when we try to look up an PPA that doesn't exist."""
    _message_prefix = "No such ppa"


@error_status(httplib.BAD_REQUEST)
class VersionRequiresName(Exception):
    """Raised on some queries when version is specified but name is not."""


class CannotRestrictArchitectures(Exception):
    """The architectures for this archive can not be restricted."""


@error_status(httplib.FORBIDDEN)
class CannotUploadToArchive(Exception):
    """A reason for not being able to upload to an archive."""

    _fmt = '%(person)s has no upload rights to %(archive)s.'

    def __init__(self, **args):
        """Construct a `CannotUploadToArchive`."""
        Exception.__init__(self, self._fmt % args)


class InvalidPocketForPartnerArchive(CannotUploadToArchive):
    """Partner archives only support some pockets."""

    _fmt = "Partner uploads must be for the RELEASE or PROPOSED pocket."


@error_status(httplib.FORBIDDEN)
class CannotUploadToPocket(Exception):
    """Returned when a pocket is closed for uploads."""

    def __init__(self, distroseries, pocket):
        Exception.__init__(self,
            "Not permitted to upload to the %s pocket in a series in the "
            "'%s' state." % (pocket.name, distroseries.status.name))


class CannotUploadToPPA(CannotUploadToArchive):
    """Raised when a person cannot upload to a PPA."""

    _fmt = 'Signer has no upload rights to this PPA.'


class NoRightsForArchive(CannotUploadToArchive):
    """Raised when a person has absolutely no upload rights to an archive."""

    _fmt = (
        "The signer of this package has no upload rights to this "
        "distribution's primary archive.  Did you mean to upload to "
        "a PPA?")


class InsufficientUploadRights(CannotUploadToArchive):
    """Raised when a person has insufficient upload rights."""
    _fmt = (
        "The signer of this package is lacking the upload rights for "
        "the source package, component or package set in question.")


class NoRightsForComponent(CannotUploadToArchive):
    """Raised when a person tries to upload to a component without permission.
    """

    _fmt = (
        "Signer is not permitted to upload to the component '%(component)s'.")

    def __init__(self, component):
        CannotUploadToArchive.__init__(self, component=component.name)


class InvalidPocketForPPA(CannotUploadToArchive):
    """PPAs only support some pockets."""

    _fmt = "PPA uploads must be for the RELEASE pocket."


class ArchiveDisabled(CannotUploadToArchive):
    """Uploading to a disabled archive is not allowed."""

    _fmt = ("%(archive_name)s is disabled.")

    def __init__(self, archive_name):
        CannotUploadToArchive.__init__(self, archive_name=archive_name)


@error_status(httplib.BAD_REQUEST)
class InvalidExternalDependencies(Exception):
    """Tried to set external dependencies to an invalid value."""

    def __init__(self, errors):
        error_msg = 'Invalid external dependencies:\n%s\n' % '\n'.join(errors)
        super(Exception, self).__init__(self, error_msg)
        self.errors = errors


class IArchivePublic(IHasOwner, IPrivacy):
    """An Archive interface for publicly available operations."""
    id = Attribute("The archive ID.")

    owner = exported(
        PersonChoice(
            title=_('Owner'), required=True, vocabulary='ValidOwner',
            description=_("""The archive owner.""")))

    name = exported(
        TextLine(
            title=_("Name"), required=True,
            constraint=name_validator,
            description=_(
                "At least one lowercase letter or number, followed by "
                "letters, numbers, dots, hyphens or pluses. "
                "Keep this name short; it is used in URLs.")))

    displayname = exported(
        StrippedTextLine(
            title=_("Display name"), required=True,
            description=_("A short title for the archive.")))

    title = TextLine(title=_("Name"), required=False, readonly=True)

    enabled = Bool(
        title=_("Enabled"), required=False,
        description=_(
            "Accept and build packages uploaded to the archive."))

    publish = Bool(
        title=_("Publish"), required=False,
        description=_("Whether or not to update the APT repository.  If "
            "disabled, nothing will be published.  If the archive is "
            "private then additionally no builds will be dispatched."))

    # This is redefined from IPrivacy.private because the attribute is
    # read-only. The value is guarded by a validator.
    private = exported(
        Bool(
            title=_("Private"), required=False,
            description=_(
                "Restrict access to the archive to its owner and "
                "subscribers. This can only be changed if the archive has "
                "never had any sources published.")))

    require_virtualized = exported(
        Bool(
            title=_("Require virtualized builders"), required=False,
            readonly=False, description=_(
                "Only build the archive's packages on virtual builders.")))

    build_debug_symbols = Bool(
        title=_("Build debug symbols"), required=False,
        description=_(
            "Create debug symbol packages for builds in the archive."))

    authorized_size = Int(
        title=_("Authorized size"), required=False,
        max=2 ** 31 - 1,
        description=_("Maximum size, in MiB, allowed for the archive."))

    purpose = Int(
        title=_("Purpose of archive."), required=True, readonly=True,
        )

    status = Int(
        title=_("Status of archive."), required=True, readonly=True,
        )

    sources_cached = Int(
        title=_("Number of sources cached"), required=False,
        description=_("Number of source packages cached in this PPA."))

    binaries_cached = Int(
        title=_("Number of binaries cached"), required=False,
        description=_("Number of binary packages cached in this PPA."))

    package_description_cache = Attribute(
        "Concatenation of the source and binary packages published in this "
        "archive. Its content is used for indexed searches across archives.")

    distribution = exported(
        Reference(
            Interface,  # Redefined to IDistribution later.
            title=_("The distribution that uses or is used by this "
                    "archive.")))

    signing_key = Object(
        title=_('Repository sigining key.'), required=False, schema=IGPGKey)

    debug_archive = Attribute(
        "The archive into which debug binaries should be uploaded.")

    default_component = Reference(
        IComponent,
        title=_(
            "The default component for this archive. Publications without a "
            "valid component will be assigned this one."))

    archive_url = Attribute("External archive URL.")

    is_ppa = Attribute("True if this archive is a PPA.")

    is_partner = Attribute("True if this archive is a partner archive.")

    is_copy = Attribute("True if this archive is a copy archive.")

    is_main = Bool(
        title=_("True if archive is a main archive type"), required=False)

    is_active = Bool(
        title=_("True if the archive is in the active state"),
        required=False, readonly=True)

    series_with_sources = Attribute(
        "DistroSeries to which this archive has published sources")
    number_of_sources = Attribute(
        'The number of sources published in the context archive.')
    number_of_binaries = Attribute(
        'The number of binaries published in the context archive.')
    sources_size = Attribute(
        'The size of sources published in the context archive.')
    binaries_size = Attribute(
        'The size of binaries published in the context archive.')
    estimated_size = Attribute('Estimated archive size.')

    total_count = Int(
        title=_("Total number of builds in archive"), required=True,
        default=0,
        description=_("The total number of builds in this archive. "
                      "This counter does not include discontinued "
                      "(superseded, cancelled, obsoleted) builds"))

    pending_count = Int(
        title=_("Number of pending builds in archive"), required=True,
        default=0,
        description=_("The number of pending builds in this archive."))

    succeeded_count = Int(
        title=_("Number of successful builds in archive"), required=True,
        default=0,
        description=_("The number of successful builds in this archive."))

    building_count = Int(
        title=_("Number of active builds in archive"), required=True,
        default=0,
        description=_("The number of active builds in this archive."))

    failed_count = Int(
        title=_("Number of failed builds in archive"), required=True,
        default=0,
        description=_("The number of failed builds in this archive."))

    date_created = Datetime(
        title=_('Date created'), required=False, readonly=True,
        description=_("The time when the archive was created."))

    relative_build_score = Int(
        title=_("Relative build score"), required=True, readonly=False,
        description=_(
            "A delta to apply to all build scores for the archive. Builds "
            "with a higher score will build sooner."))

    external_dependencies = exported(
        Text(title=_("External dependencies"), required=False,
        readonly=False, description=_(
            "Newline-separated list of repositories to be used to retrieve "
            "any external build dependencies when building packages in the "
            "archive, in the format:\n"
            "deb http[s]://[user:pass@]<host>[/path] %(series)s[-pocket] "
                "[components]\n"
            "The series variable is replaced with the series name of the "
            "context build.\n"
            "NOTE: This is for migration of OEM PPAs only!")))

    enabled_restricted_families = exported(
        CollectionField(
            title=_("Enabled restricted families"),
            description=_(
                "The restricted architecture families on which the archive "
                "can build."),
            value_type=Reference(schema=Interface),
            # Really IProcessorFamily.
            readonly=True),
        as_of='devel')

    commercial = exported(
        Bool(
            title=_("Commercial"),
            required=True,
            description=_(
                "Display the archive in Software Center's commercial "
                "listings. Only private archives can be commercial.")))

    def getSourcesForDeletion(name=None, status=None, distroseries=None):
        """All `ISourcePackagePublishingHistory` available for deletion.

        :param: name: optional source name filter (SQL LIKE)
        :param: status: `PackagePublishingStatus` filter, can be a sequence.
        :param: distroseries: `IDistroSeries` filter.

        :return: SelectResults containing `ISourcePackagePublishingHistory`.
        """

    def getPublishedOnDiskBinaries(name=None, version=None, status=None,
                                   distroarchseries=None, exact_match=False):
        """Unique `IBinaryPackagePublishingHistory` target to this archive.

        In spite of getAllPublishedBinaries method, this method only returns
        distinct binary publications inside this Archive, i.e, it excludes
        architecture-independent publication for other architetures than the
        nominatedarchindep. In few words it represents the binary files
        published in the archive disk pool.

        :param: name: binary name filter (exact match or SQL LIKE controlled
                      by 'exact_match' argument).
        :param: version: binary version filter (always exact match).
        :param: status: `PackagePublishingStatus` filter, can be a list.
        :param: distroarchseries: `IDistroArchSeries` filter, can be a list.
        :param: pocket: `PackagePublishingPocket` filter.
        :param: exact_match: either or not filter source names by exact
                             matching.

        :return: SelectResults containing `IBinaryPackagePublishingHistory`.
        """

    def allowUpdatesToReleasePocket():
        """Return whether the archive allows publishing to the release pocket.

        If a distroseries is stable, normally release pocket publishings are
        not allowed.  However some archive types allow this.

        :return: True or False
        """

    def getComponentsForSeries(distroseries):
        """Calculate the components available for use in this archive.

        :return: An `IResultSet` of `IComponent` objects.
        """

    def updateArchiveCache():
        """Concentrate cached information about the archive contents.

        Group the relevant package information (source name, binary names,
        binary summaries and distroseries with binaries) strings in the
        IArchive.package_description_cache search indexes (fti).

        Updates 'sources_cached' and 'binaries_cached' counters.

        Also include owner 'name' and 'displayname' to avoid inpecting the
        Person table indexes while searching.
        """

    def findDepCandidates(distro_arch_series, pocket, component,
                          source_package_name, dep_name):
        """Return matching binaries in this archive and its dependencies.

        Return all published `IBinaryPackagePublishingHistory` records with
        the given name, in this archive and dependencies as specified by the
        given build context, using the usual archive dependency rules.

        We can't just use the first, since there may be other versions
        published in other dependency archives.

        :param distro_arch_series: the context `IDistroArchSeries`.
        :param pocket: the context `PackagePublishingPocket`.
        :param component: the context `IComponent`.
        :param source_package_name: the context source package name (as text).
        :param dep_name: the name of the binary package to look up.
        :return: a sequence of matching `IBinaryPackagePublishingHistory`
            records.
        """

    def getPermissions(person, item, perm_type):
        """Get the `IArchivePermission` record with the supplied details.

        :param person: An `IPerson`
        :param item: An `IComponent`, `ISourcePackageName`
        :param perm_type: An ArchivePermissionType enum,
        :return: A list of `IArchivePermission` records.
        """

    def checkArchivePermission(person, component_or_package=None):
        """Check to see if person is allowed to upload to component.

        :param person: An `IPerson` whom should be checked for authentication.
        :param component_or_package: The context `IComponent` or an
            `ISourcePackageName` for the check.  This parameter is
            not required if the archive is a PPA.

        :return: True if 'person' is allowed to upload to the specified
            component or package name.
        :raise TypeError: If component_or_package is not one of
            `IComponent` or `ISourcePackageName`.

        """

    def canUploadSuiteSourcePackage(person, suitesourcepackage):
        """Check if 'person' upload 'suitesourcepackage' to 'archive'.

        :param person: An `IPerson` who might be uploading.
        :param suitesourcepackage: An `ISuiteSourcePackage` to be uploaded.
        :return: True if they can, False if they cannot.
        """

    def checkUploadToPocket(distroseries, pocket):
        """Check if an upload to a particular archive and pocket is possible.

        :param distroseries: A `IDistroSeries`
        :param pocket: A `PackagePublishingPocket`
        :return: Reason why uploading is not possible or None
        """

    @operation_parameters(
        person=Reference(schema=IPerson),
        distroseries=Reference(
            # Really IDistroSeries, avoiding a circular import here.
            Interface,
            title=_("The distro series"), required=True),
        sourcepackagename=TextLine(
            title=_("Source package name"), required=True),
        component=TextLine(
            title=_("Component"), required=True),
        pocket=Choice(
            title=_("Pocket"),
            description=_("The pocket into which this entry is published"),
            # Really PackagePublishingPocket, circular import fixed below.
            vocabulary=DBEnumeratedType,
            required=True),
        strict_component=Bool(
            title=_("Strict component"), required=False),
        )
    @export_operation_as("checkUpload")
    @export_read_operation()
    def _checkUpload(person, distroseries, sourcepackagename, component,
            pocket, strict_component=True):
        """Wrapper around checkUpload for the web service API."""

    def checkUpload(person, distroseries, sourcepackagename, component,
                    pocket, strict_component=True):
        """Check if 'person' upload 'suitesourcepackage' to 'archive'.

        :param person: An `IPerson` who might be uploading.
        :param distroseries: The `IDistroSeries` being uploaded to.
        :param sourcepackagename: The `ISourcePackageName` being uploaded.
        :param component: The `Component` being uploaded to.
        :param pocket: The `PackagePublishingPocket` of 'distroseries' being
            uploaded to.
        :param strict_component: True if access to the specific component for
            the package is needed to upload to it. If False, then access to
            any component will do.
        :return: The reason for not being able to upload, None otherwise.
        """

    def verifyUpload(person, sourcepackagename, component,
                      distroseries, strict_component=True):
        """Can 'person' upload 'sourcepackagename' to this archive ?

        :param person: The `IPerson` trying to upload to the package. Referred
            to as 'the signer' in upload code.
        :param sourcepackagename: The source package being uploaded. None if
            the package is new.
        :param archive: The `IArchive` being uploaded to.
        :param component: The `IComponent` that the source package belongs to.
        :param distroseries: The upload's target distro series.
        :param strict_component: True if access to the specific component for
            the package is needed to upload to it. If False, then access to
            any component will do.
        :return: CannotUploadToArchive if 'person' cannot upload to the
            archive,
            None otherwise.
        """

    def canAdministerQueue(person, component):
        """Check to see if person is allowed to administer queue items.

        :param person: An `IPerson` whom should be checked for authenticate.
        :param component: The context `IComponent` for the check.

        :return: True if 'person' is allowed to administer the package upload
        queue for items with 'component'.
        """

    def getFileByName(filename):
        """Return the corresponding `ILibraryFileAlias` in this context.

        The following file types (and extension) can be looked up in the
        archive context:

         * Source files: '.orig.tar.gz', 'tar.gz', '.diff.gz' and '.dsc';
         * Binary files: '.deb' and '.udeb';
         * Source changesfile: '_source.changes';
         * Package diffs: '.diff.gz';

        :param filename: exactly filename to be looked up.

        :raises AssertionError if the given filename contains a unsupported
            filename and/or extension, see the list above.
        :raises NotFoundError if no file could not be found.

        :return the corresponding `ILibraryFileAlias` is the file was found.
        """

    def getBinaryPackageRelease(name, version, archtag):
        """Find the specified `IBinaryPackageRelease` in the archive.

        :param name: The `IBinaryPackageName` of the package.
        :param version: The version of the package.
        :param archtag: The architecture tag of the package's build. 'all'
            will not work here -- 'i386' (the build DAS) must be used instead.

        :return The binary package release with the given name and version,
            or None if one does not exist or there is more than one.
        """

    def getBinaryPackageReleaseByFileName(filename):
        """Return the corresponding `IBinaryPackageRelease` in this context.

        :param filename: The filename to look up.
        :return: The `IBinaryPackageRelease` with the specified filename,
            or None if it was not found.
        """

    def requestPackageCopy(target_location, requestor, suite=None,
                           copy_binaries=False, reason=None):
        """Return a new `PackageCopyRequest` for this archive.

        :param target_location: the archive location to which the packages
            are to be copied.
        :param requestor: The `IPerson` who is requesting the package copy
            operation.
        :param suite: The `IDistroSeries` name with optional pocket, for
            example, 'hoary-security'. If this is not provided it will
            default to the current series' release pocket.
        :param copy_binaries: Whether or not binary packages should be copied
            as well.
        :param reason: The reason for this package copy request.

        :raises NotFoundError: if the provided suite is not found for this
            archive's distribution.

        :return The new `IPackageCopyRequest`
        """

    @operation_parameters(
        # Really IPackageset, corrected in _schema_circular_imports to avoid
        # circular import.
        packageset=Reference(
            Interface, title=_("Package set"), required=True),
        direct_permissions=Bool(
            title=_("Ignore package set hierarchy"), required=False))
    # Really IArchivePermission, set in _schema_circular_imports to avoid
    # circular import.
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getUploadersForPackageset(packageset, direct_permissions=True):
        """The `ArchivePermission` records for uploaders to the package set.

        :param packageset: An `IPackageset`.
        :param direct_permissions: If True, only consider permissions granted
            directly for the package set at hand. Otherwise, include any
            uploaders for package sets that include this one.

        :return: `ArchivePermission` records for all the uploaders who are
            authorized to upload to the named source package set.
        """

    @operation_parameters(
        person=Reference(schema=IPerson))
    # Really IArchivePermission, set in _schema_circular_imports to avoid
    # circular import.
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getPackagesetsForUploader(person):
        """The `ArchivePermission` records for the person's package sets.

        :param person: An `IPerson` for whom you want to find out which
            package sets he has access to.

        :return: `ArchivePermission` records for all the package sets that
            'person' is allowed to upload to.
        """

    def getComponentsForUploader(person):
        """Return the components that 'person' can upload to this archive.

        :param person: An `IPerson` wishing to upload to an archive.
        :return: A `set` of `IComponent`s that 'person' can upload to.
        """

    @operation_parameters(
        sourcepackagename=TextLine(
            title=_("Source package name"), required=True),
        person=Reference(schema=IPerson))
    # Really IArchivePermission, set in _schema_circular_imports to avoid
    # circular import.
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getPackagesetsForSourceUploader(sourcepackagename, person):
        """The package set based permissions for a given source and uploader.

        Return the `IArchivePermission` records that
            * apply to this archive
            * relate to
                - package sets that include the given source package name
                - the given `person`

        :param sourcepackagename: the source package name; can be
            either a string or a `ISourcePackageName`.
        :param person: An `IPerson` for whom you want to find out which
            package sets he has access to.

        :raises NoSuchSourcePackageName: if a source package with the
            given name could not be found.
        :return: `ArchivePermission` records for the package sets that
            include the given source package name and to which the given
            person may upload.
        """

    @operation_parameters(
        sourcepackagename=TextLine(
            title=_("Source package name"), required=True),
        direct_permissions=Bool(
            title=_("Ignore package set hierarchy"), required=False))
    # Really IArchivePermission, set in _schema_circular_imports to avoid
    # circular import.
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getPackagesetsForSource(
        sourcepackagename, direct_permissions=True):
        """All package set based permissions for the given source.

        This method is meant to aid the process of "debugging" package set
        based archive permission since It allows the listing of permissions
        for the given source package in this archive (irrespective of the
        principal).

        :param sourcepackagename: the source package name; can be
            either a string or a `ISourcePackageName`.
        :param direct_permissions: If set only package sets that directly
            include the given source will be considered.

        :raises NoSuchSourcePackageName: if a source package with the
            given name could not be found.
        :return: `ArchivePermission` records for the package sets that
            include the given source package name and apply to the
            archive in question.
        """

    @operation_parameters(
        sourcepackagename=TextLine(
            title=_("Source package name"), required=True),
        person=Reference(schema=IPerson),
        distroseries=Reference(
            # Really IDistroSeries, avoiding a circular import here.
            Interface,
            title=_("The distro series"), required=False))
    @export_read_operation()
    def isSourceUploadAllowed(sourcepackagename, person, distroseries=None):
        """True if the person is allowed to upload the given source package.

        Return True if there exists a permission that combines
            * this archive
            * a package set that includes the given source package name
            * the given person or a team he is a member of

        If the source package name is included by *any* package set with
        an explicit permission then only such explicit permissions will
        be considered.

        :param sourcepackagename: the source package name; can be
            either a string or a `ISourcePackageName`.
        :param person: An `IPerson` for whom you want to find out which
            package sets he has access to.
        :param distroseries: The `IDistroSeries` for which to check
            permissions. If none is supplied then `currentseries` in
            Ubuntu is assumed.

        :raises NoSuchSourcePackageName: if a source package with the
            given name could not be found.
        :return: True if the person is allowed to upload the source package.
        """

    num_pkgs_building = Attribute(
        "Tuple of packages building and waiting to build")

    def getSourcePackageReleases(build_status=None):
        """Return the releases for this archive.

        :param build_status: If specified, only the distinct releases with
            builds in the specified build status will be returned.
        :return: A `ResultSet` of distinct `SourcePackageReleases` for this
            archive.
        """

    def updatePackageDownloadCount(bpr, day, country, count):
        """Update the daily download count for a given package.

        :param bpr: The `IBinaryPackageRelease` to update the count for.
        :param day: The date to update the count for.
        :param country: The `ICountry` to update the count for.
        :param count: The new download count.

        If there's no matching `IBinaryPackageReleaseDownloadCount` entry,
        we create one with the given count.  Otherwise we just increase the
        count of the existing one by the given amount.
        """

    def getPackageDownloadTotal(bpr):
        """Get the total download count for a given package."""

    def validatePPA(person, proposed_name):
        """Check if a proposed name for a PPA is valid.

        :param person: A Person identifying the requestor.
        :param proposed_name: A String identifying the proposed PPA name.
        """

    def getPockets():
        """Return iterable containing valid pocket names for this archive."""

    def getOverridePolicy():
        """Returns an instantiated `IOverridePolicy` for the archive."""


class IArchiveView(IHasBuildRecords):
    """Archive interface for operations restricted by view privilege."""

    buildd_secret = TextLine(
        title=_("Build farm secret"), required=False,
        description=_(
            "The password used by the build farm to access the archive."))

    dependencies = exported(
        CollectionField(
            title=_("Archive dependencies recorded for this archive."),
            value_type=Reference(schema=Interface),
            # Really IArchiveDependency
            readonly=True))

    description = exported(
        Text(
            title=_("Description"), required=False,
            description=_(
                "A short description of the archive. URLs are allowed and "
                "will be rendered as links.")))

    signing_key_fingerprint = exported(
        Text(
            title=_("Archive signing key fingerprint"), required=False,
            description=_("A OpenPGP signing key fingerprint (40 chars) "
                          "for this PPA or None if there is no signing "
                          "key available.")))

    @rename_parameters_as(name="source_name", distroseries="distro_series")
    @operation_parameters(
        name=TextLine(title=_("Source package name"), required=False),
        version=TextLine(title=_("Version"), required=False),
        status=Choice(
            title=_('Package Publishing Status'),
            description=_('The status of this publishing record'),
            # Really PackagePublishingStatus, circular import fixed below.
            vocabulary=DBEnumeratedType,
            required=False),
        distroseries=Reference(
            # Really IDistroSeries, fixed below to avoid circular import.
            Interface,
            title=_("Distroseries name"), required=False),
        pocket=Choice(
            title=_("Pocket"),
            description=_("The pocket into which this entry is published"),
            # Really PackagePublishingPocket, circular import fixed below.
            vocabulary=DBEnumeratedType,
            required=False, readonly=True),
        exact_match=Bool(
            title=_("Exact Match"),
            description=_("Whether or not to filter source names by exact"
                          " matching."),
            required=False),
        created_since_date=Datetime(
            title=_("Created Since Date"),
            description=_("Return entries whose `date_created` is greater "
                          "than or equal to this date."),
            required=False),
        component_name=TextLine(title=_("Component name"), required=False),
        )
    # Really returns ISourcePackagePublishingHistory, see below for
    # patch to avoid circular import.
    @call_with(eager_load=True)
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getPublishedSources(name=None, version=None, status=None,
                            distroseries=None, pocket=None,
                            exact_match=False, created_since_date=None,
                            eager_load=False, component_name=None):
        """All `ISourcePackagePublishingHistory` target to this archive.

        :param name: source name filter (exact match or SQL LIKE controlled
                     by 'exact_match' argument).
                     Name can be a single string or a list of strings.
        :param version: source version filter (always exact match).
        :param status: `PackagePublishingStatus` filter, can be a sequence.
        :param distroseries: `IDistroSeries` filter.
        :param pocket: `PackagePublishingPocket` filter.  This may be an
            iterable of more than one pocket or a single pocket.
        :param exact_match: either or not filter source names by exact
                             matching.
        :param created_since_date: Only return results whose `date_created`
            is greater than or equal to this date.
        :param component_name: component filter. Only return source packages
            that are in this component.

        :return: SelectResults containing `ISourcePackagePublishingHistory`,
            ordered by name. If there are multiple results for the same
            name then they are sub-ordered newest first.
        """

    @rename_parameters_as(
        name="binary_name", distroarchseries="distro_arch_series")
    @operation_parameters(
        name=TextLine(title=_("Binary Package Name"), required=False),
        version=TextLine(title=_("Version"), required=False),
        status=Choice(
            title=_("Package Publishing Status"),
            description=_("The status of this publishing record"),
            # Really PackagePublishingStatus, circular import fixed below.
            vocabulary=DBEnumeratedType,
            required=False),
        distroarchseries=Reference(
            # Really IDistroArchSeries, circular import fixed below.
            Interface,
            title=_("Distro Arch Series"), required=False),
        pocket=Choice(
            title=_("Pocket"),
            description=_("The pocket into which this entry is published"),
            # Really PackagePublishingPocket, circular import fixed below.
            vocabulary=DBEnumeratedType,
            required=False, readonly=True),
        exact_match=Bool(
            description=_("Whether or not to filter binary names by exact "
                          "matching."),
            required=False))
    # Really returns ISourcePackagePublishingHistory, see below for
    # patch to avoid circular import.
    @operation_returns_collection_of(Interface)
    @export_operation_as("getPublishedBinaries")
    @export_read_operation()
    def getAllPublishedBinaries(name=None, version=None, status=None,
                                distroarchseries=None, pocket=None,
                                exact_match=False):
        """All `IBinaryPackagePublishingHistory` target to this archive.

        :param: name: binary name filter (exact match or SQL LIKE controlled
                      by 'exact_match' argument).
        :param: version: binary version filter (always exact match).
        :param: status: `PackagePublishingStatus` filter, can be a list.
        :param: distroarchseries: `IDistroArchSeries` filter, can be a list.
        :param: pocket: `PackagePublishingPocket` filter.
        :param: exact_match: either or not filter source names by exact
                             matching.

        :return: A collection containing `BinaryPackagePublishingHistory`.
        """

    @operation_parameters(
        include_needsbuild=Bool(
            title=_("Include builds with state NEEDSBUILD"), required=False))
    @export_read_operation()
    def getBuildCounters(include_needsbuild=True):
        """Return a dictionary containing the build counters for an archive.

        This is necessary currently because the IArchive.failed_builds etc.
        counters are not in use.

        The returned dictionary contains the follwoing keys and values:

         * 'total': total number of builds (includes SUPERSEDED);
         * 'pending': number of builds in BUILDING or NEEDSBUILD state;
         * 'failed': number of builds in FAILEDTOBUILD, MANUALDEPWAIT,
           CHROOTWAIT and FAILEDTOUPLOAD state;
         * 'succeeded': number of SUCCESSFULLYBUILT builds.
         * 'superseded': number of SUPERSEDED builds.

        :param include_needsbuild: Indicates whether to include builds with
            the status NEEDSBUILD in the pending and total counts. This is
            useful in situations where a build that hasn't started isn't
            considered a build by the user.
        :type include_needsbuild: ``bool``
        :return: a dictionary with the 4 keys specified above.
        :rtype: ``dict``.
        """

    @operation_parameters(
        source_ids=List(
            title=_("A list of source publishing history record ids."),
            value_type=Int()))
    @export_read_operation()
    def getBuildSummariesForSourceIds(source_ids):
        """Return a dictionary containing a summary of the build statuses.

        Only information for sources belonging to the current archive will
        be returned. See
        `IPublishingSet`.getBuildStatusSummariesForSourceIdsAndArchive() for
        details.

        :param source_ids: A list of source publishing history record ids.
        :type source_ids: ``list``
        :return: A dict consisting of the overall status summaries for the
            given ids that belong in the archive.
        """

    @operation_parameters(
        dependency=Reference(schema=Interface))  # Really IArchive. See below.
    @operation_returns_entry(schema=Interface)  # Really IArchiveDependency.
    @export_read_operation()
    def getArchiveDependency(dependency):
        """Return the `IArchiveDependency` object for the given dependency.

        :param dependency: is an `IArchive` object.

        :return: `IArchiveDependency` or None if a corresponding object
            could not be found.
        """

    @operation_parameters(person=Reference(schema=IPerson))
    # Really IArchivePermission, set below to avoid circular import.
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getPermissionsForPerson(person):
        """Return the `IArchivePermission` records applicable to the person.

        :param person: An `IPerson`
        :return: A list of `IArchivePermission` records.
        """

    @operation_parameters(
        source_package_name=TextLine(
            title=_("Source Package Name"), required=True))
    # Really IArchivePermission, set below to avoid circular import.
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getUploadersForPackage(source_package_name):
        """Return `IArchivePermission` records for the package's uploaders.

        :param source_package_name: An `ISourcePackageName` or textual name
            for the source package.
        :return: A list of `IArchivePermission` records.
        """

    @operation_parameters(
        component_name=TextLine(title=_("Component Name"), required=False))
    # Really IArchivePermission, set below to avoid circular import.
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getUploadersForComponent(component_name=None):
        """Return `IArchivePermission` records for the component's uploaders.

        :param component_name: An `IComponent` or textual name for the
            component.
        :return: A list of `IArchivePermission` records.
        """

    @operation_parameters(
        component_name=TextLine(title=_("Component Name"), required=True))
    # Really IArchivePermission, set below to avoid circular import.
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getQueueAdminsForComponent(component_name):
        """Return `IArchivePermission` records for authorised queue admins.

        :param component_name: An `IComponent` or textual name for the
            component.
        :return: A list of `IArchivePermission` records.
        """

    @operation_parameters(person=Reference(schema=IPerson))
    # Really IArchivePermission, set below to avoid circular import.
    @operation_returns_collection_of(Interface)
    @export_read_operation()
    def getComponentsForQueueAdmin(person):
        """Return `IArchivePermission` for the person's queue admin
        components.

        :param person: An `IPerson`.
        :return: A list of `IArchivePermission` records.
        """

    def hasAnyPermission(person):
        """Whether or not this person has any permission at all on this
        archive.

        :param person: The `IPerson` for whom the check is performed.
        :return: A boolean indicating if the person has any permission on this
            archive at all.
        """

    def getPackageDownloadCount(bpr, day, country):
        """Get the `IBinaryPackageDownloadCount` with the given key."""

    def getFilesAndSha1s(source_files):
        """Return a dictionary with the filenames and the SHA1s for each
        source file.

        :param source_files: A list of filenames to return SHA1s of
        :return: A dictionary of filenames and SHA1s.
        """

    def getAuthToken(person):
        """Returns an IArchiveAuthToken for the archive in question for
        IPerson provided.

        :return: A IArchiveAuthToken, or None if the user has none.
        """

    def newAuthToken(person, token=None, date_created=None):
        """Create a new authorisation token.

        :param person: An IPerson whom this token is for
        :param token: Optional unicode text to use as the token. One will be
            generated if not given
        :param date_created: Optional, defaults to now

        :return: A new IArchiveAuthToken
        """

    @call_with(person=REQUEST_USER)
    @operation_parameters(
        source_name=TextLine(title=_("Source package name")),
        version=TextLine(title=_("Version")),
        from_archive=Reference(schema=Interface),
        # Really IArchive, see below
        to_pocket=TextLine(title=_("Pocket name")),
        to_series=TextLine(title=_("Distroseries name"), required=False),
        include_binaries=Bool(
            title=_("Include Binaries"),
            description=_("Whether or not to copy binaries already built for"
                          " this source"),
            required=False),
        sponsored=Reference(
            schema=IPerson,
            title=_("Sponsored Person"),
            description=_("The person who is being sponsored for this copy."))
        )
    @export_write_operation()
    @operation_for_version('devel')
    def copyPackage(source_name, version, from_archive, to_pocket,
                    person, to_series=None, include_binaries=False,
                    sponsored=None):
        """Copy a single named source into this archive.

        Asynchronously copy a specific version of a named source to the
        destination archive if necessary.  Calls to this method will return
        immediately if the copy passes basic security checks and the copy
        will happen sometime later with full checking.

        :param source_name: a string name of the package to copy.
        :param version: the version of the package to copy.
        :param from_archive: the source archive from which to copy.
        :param to_pocket: the target pocket (as a string).
        :param to_series: the target distroseries (as a string).
        :param include_binaries: optional boolean, controls whether or not
            the published binaries for each given source should also be
            copied along with the source.
        :param person: the `IPerson` who requests the sync.
        :param sponsored: the `IPerson` who is being sponsored. Specifying
            this will ensure that the person's email address is used as the
            "From:" on the announcement email and will also be recorded as
            the creator of the new source publication.

        :raises NoSuchSourcePackageName: if the source name is invalid
        :raises PocketNotFound: if the pocket name is invalid
        :raises NoSuchDistroSeries: if the distro series name is invalid
        :raises CannotCopy: if there is a problem copying.
        """

    @call_with(person=REQUEST_USER)
    @operation_parameters(
        source_names=List(
            title=_("Source package names"),
            value_type=TextLine()),
        from_archive=Reference(schema=Interface),
        #Really IArchive, see below
        to_pocket=TextLine(title=_("Pocket name")),
        to_series=TextLine(title=_("Distroseries name"), required=False),
        include_binaries=Bool(
            title=_("Include Binaries"),
            description=_("Whether or not to copy binaries already built for"
                          " this source"),
            required=False),
        sponsored=Reference(
            schema=IPerson,
            title=_("Sponsored Person"),
            description=_("The person who is being sponsored for this copy."))
        )
    @export_write_operation()
    @operation_for_version('devel')
    def copyPackages(source_names, from_archive, to_pocket, person,
                     to_series=None, include_binaries=False,
                     sponsored=None):
        """Copy multiple named sources into this archive from another.

        Asynchronously copy the most recent PUBLISHED versions of the named
        sources to the destination archive if necessary.  Calls to this
        method will return immediately if the copy passes basic security
        checks and the copy will happen sometime later with full checking.

        Partial changes of the destination archive can happen because each
        source is copied in its own transaction.

        :param source_names: a list of string names of packages to copy.
        :param from_archive: the source archive from which to copy.
        :param to_pocket: the target pocket (as a string).
        :param to_series: the target distroseries (as a string).
        :param include_binaries: optional boolean, controls whether or not
            the published binaries for each given source should also be
            copied along with the source.
        :param person: the `IPerson` who requests the sync.
        :param sponsored: the `IPerson` who is being sponsored. Specifying
            this will ensure that the person's email address is used as the
            "From:" on the announcement email and will also be recorded as
            the creator of the new source publication.

        :raises NoSuchSourcePackageName: if the source name is invalid
        :raises PocketNotFound: if the pocket name is invalid
        :raises NoSuchDistroSeries: if the distro series name is invalid
        :raises CannotCopy: if there is a problem copying.
        """


class IArchiveAppend(Interface):
    """Archive interface for operations restricted by append privilege."""

    @call_with(person=REQUEST_USER)
    @operation_parameters(
        source_names=List(
            title=_("Source package names"),
            value_type=TextLine()),
        from_archive=Reference(schema=Interface),
        #Really IArchive, see below
        to_pocket=TextLine(title=_("Pocket name")),
        to_series=TextLine(title=_("Distroseries name"), required=False),
        include_binaries=Bool(
            title=_("Include Binaries"),
            description=_("Whether or not to copy binaries already built for"
                          " this source"),
            required=False))
    @export_write_operation()
    # Source_names is a string because exporting a SourcePackageName is
    # rather nonsensical as it only has id and name columns.
    def syncSources(source_names, from_archive, to_pocket, to_series=None,
                    include_binaries=False, person=None):
        """Synchronise (copy) named sources into this archive from another.

        It will copy the most recent PUBLISHED versions of the named
        sources to the destination archive if necessary.

        This operation will only succeeds when all requested packages
        are synchronised between the archives. If any of the requested
        copies cannot be performed, the whole operation will fail. There
        will be no partial changes of the destination archive.

        :param source_names: a list of string names of packages to copy.
        :param from_archive: the source archive from which to copy.
        :param to_pocket: the target pocket (as a string).
        :param to_series: the target distroseries (as a string).
        :param include_binaries: optional boolean, controls whether or not
            the published binaries for each given source should also be
            copied along with the source.
        :param person: the `IPerson` who requests the sync.

        :raises NoSuchSourcePackageName: if the source name is invalid
        :raises PocketNotFound: if the pocket name is invalid
        :raises NoSuchDistroSeries: if the distro series name is invalid
        :raises CannotCopy: if there is a problem copying.
        """

    @call_with(person=REQUEST_USER)
    @operation_parameters(
        source_name=TextLine(title=_("Source package name")),
        version=TextLine(title=_("Version")),
        from_archive=Reference(schema=Interface),
        # Really IArchive, see below
        to_pocket=TextLine(title=_("Pocket name")),
        to_series=TextLine(title=_("Distroseries name"), required=False),
        include_binaries=Bool(
            title=_("Include Binaries"),
            description=_("Whether or not to copy binaries already built for"
                          " this source"),
            required=False))
    @export_write_operation()
    # XXX Julian 2008-11-05
    # This method takes source_name and version as strings because
    # SourcePackageRelease is not exported on the API yet.  When it is,
    # we should consider either changing this method or adding a new one
    # that takes that object instead.
    def syncSource(source_name, version, from_archive, to_pocket,
                   to_series=None, include_binaries=False, person=None):
        """Synchronise (copy) a single named source into this archive.

        Copy a specific version of a named source to the destination
        archive if necessary.

        :param source_name: a string name of the package to copy.
        :param version: the version of the package to copy.
        :param from_archive: the source archive from which to copy.
        :param to_pocket: the target pocket (as a string).
        :param to_series: the target distroseries (as a string).
        :param include_binaries: optional boolean, controls whether or not
            the published binaries for each given source should also be
            copied along with the source.
        :param person: the `IPerson` who requests the sync.

        :raises NoSuchSourcePackageName: if the source name is invalid
        :raises PocketNotFound: if the pocket name is invalid
        :raises NoSuchDistroSeries: if the distro series name is invalid
        :raises CannotCopy: if there is a problem copying.
        """

    @call_with(registrant=REQUEST_USER)
    @operation_parameters(
        subscriber=PublicPersonChoice(
            title=_("Subscriber"),
            required=True,
            vocabulary='ValidPersonOrTeam',
            description=_("The person who is subscribed.")),
        date_expires=Datetime(title=_("Date of Expiration"), required=False,
            description=_("The timestamp when the subscription will "
                "expire.")),
        description=Text(title=_("Description"), required=False,
            description=_("Free text describing this subscription.")))
    # Really IArchiveSubscriber, set below to avoid circular import.
    @export_factory_operation(Interface, [])
    def newSubscription(subscriber, registrant, date_expires=None,
                        description=None):
        """Create a new subscribtion to this archive.

        Create an `ArchiveSubscriber` record which allows an `IPerson` to
        access a private repository.

        :param subscriber: An `IPerson` who is allowed to access the
            repository for this archive.
        :param registrant: An `IPerson` who created this subscription.
        :param date_expires: When the subscription should expire; None if
            it should not expire (default).
        :param description: An option textual description of the subscription
            being created.

        :return: The `IArchiveSubscriber` that was created.
        """


class IArchiveEdit(Interface):
    """Archive interface for operations restricted by edit privilege."""

    @operation_parameters(
        person=Reference(schema=IPerson),
        source_package_name=TextLine(
            title=_("Source Package Name"), required=True))
    # Really IArchivePermission, set below to avoid circular import.
    @export_factory_operation(Interface, [])
    def newPackageUploader(person, source_package_name):
        """Add permisson for a person to upload a package to this archive.

        :param person: An `IPerson` whom should be given permission.
        :param source_package_name: An `ISourcePackageName` or textual package
            name.
        :return: An `IArchivePermission` which is the newly-created
            permission.
        """

    @operation_parameters(
        person=Reference(schema=IPerson),
        component_name=TextLine(
            title=_("Component Name"), required=True))
    # Really IArchivePermission, set below to avoid circular import.
    @export_factory_operation(Interface, [])
    def newComponentUploader(person, component_name):
        """Add permission for a person to upload to a component.

        :param person: An `IPerson` whom should be given permission.
        :param component: An `IComponent` or textual component name.
        :return: An `IArchivePermission` which is the newly-created
            permission.
        :raises InvalidComponent: if this archive is a PPA and the component
            is not 'main'.
        """

    @operation_parameters(
        person=Reference(schema=IPerson),
        component_name=TextLine(
            title=_("Component Name"), required=True))
    # Really IArchivePermission, set below to avoid circular import.
    @export_factory_operation(Interface, [])
    def newQueueAdmin(person, component_name):
        """Add permission for a person to administer a distroseries queue.

        The supplied person will gain permission to administer the
        distroseries queue for packages in the supplied component.

        :param person: An `IPerson` whom should be given permission.
        :param component: An `IComponent` or textual component name.
        :return: An `IArchivePermission` which is the newly-created
            permission.
        """

    @operation_parameters(
        person=Reference(schema=IPerson),
        # Really IPackageset, corrected in _schema_circular_imports to avoid
        # circular import.
        packageset=Reference(
            Interface, title=_("Package set"), required=True),
        explicit=Bool(
            title=_("Explicit"), required=False))
    # Really IArchivePermission, set in _schema_circular_imports to avoid
    # circular import.
    @export_factory_operation(Interface, [])
    def newPackagesetUploader(person, packageset, explicit=False):
        """Add a package set based permission for a person.

        :param person: An `IPerson` for whom you want to add permission.
        :param packageset: An `IPackageset`.
        :param explicit: True if the package set in question requires
            specialist skills for proper handling.

        :return: The new `ArchivePermission`, or the existing one if it
            already exists.
        """

    @operation_parameters(
        person=Reference(schema=IPerson),
        source_package_name=TextLine(
            title=_("Source Package Name"), required=True))
    @export_write_operation()
    def deletePackageUploader(person, source_package_name):
        """Revoke permission for the person to upload the package.

        :param person: An `IPerson` whose permission should be revoked.
        :param source_package_name: An `ISourcePackageName` or textual package
            name.
        """

    @operation_parameters(
        person=Reference(schema=IPerson),
        component_name=TextLine(
            title=_("Component Name"), required=True))
    @export_write_operation()
    def deleteComponentUploader(person, component_name):
        """Revoke permission for the person to upload to the component.

        :param person: An `IPerson` whose permission should be revoked.
        :param component: An `IComponent` or textual component name.
        """

    @operation_parameters(
        person=Reference(schema=IPerson),
        component_name=TextLine(
            title=_("Component Name"), required=True))
    @export_write_operation()
    def deleteQueueAdmin(person, component_name):
        """Revoke permission for the person to administer distroseries queues.

        The supplied person will lose permission to administer the
        distroseries queue for packages in the supplied component.

        :param person: An `IPerson` whose permission should be revoked.
        :param component: An `IComponent` or textual component name.
        """

    @operation_parameters(
        person=Reference(schema=IPerson),
        # Really IPackageset, corrected in _schema_circular_imports to avoid
        # circular import.
        packageset=Reference(
            Interface, title=_("Package set"), required=True),
        explicit=Bool(
            title=_("Explicit"), required=False))
    @export_write_operation()
    def deletePackagesetUploader(person, packageset, explicit=False):
        """Revoke upload permissions for a person.

        :param person: An `IPerson` for whom you want to revoke permission.
        :param packageset: An `IPackageset`.
        :param explicit: The value of the 'explicit' flag for the permission
            to be revoked.
        """

    def enable():
        """Enable the archive."""

    def disable():
        """Disable the archive."""

    def delete(deleted_by):
        """Delete this archive.

        :param deleted_by: The `IPerson` requesting the deletion.

        The ArchiveStatus will be set to DELETING and any published
        packages will be marked as DELETED by deleted_by.

        The publisher is responsible for deleting the repository area
        when it sees the status change and sets it to DELETED once
        processed.
        """

    def addArchiveDependency(dependency, pocket, component=None):
        """Record an archive dependency record for the context archive.

        :param dependency: is an `IArchive` object.
        :param pocket: is an `PackagePublishingPocket` enum.
        :param component: is an optional `IComponent` object, if not given
            the archive dependency will be tied to the component used
            for a corresponding source in primary archive.

        :raise: `ArchiveDependencyError` if given 'dependency' does not fit
            the context archive.
        :return: a `IArchiveDependency` object targeted to the context
            `IArchive` requiring 'dependency' `IArchive`.
        """

    @operation_parameters(
        dependency=Reference(schema=Interface, required=True),
        #  Really IArchive
        pocket=Choice(
            title=_("Pocket"),
            description=_("The pocket into which this entry is published"),
            # Really PackagePublishingPocket.
            vocabulary=DBEnumeratedType,
            required=True),
        component=TextLine(title=_("Component"), required=False),
        )
    @export_operation_as('addArchiveDependency')
    @export_factory_operation(Interface, [])  # Really IArchiveDependency
    @operation_for_version('devel')
    def _addArchiveDependency(dependency, pocket, component=None):
        """Record an archive dependency record for the context archive.

        :param dependency: is an `IArchive` object.
        :param pocket: is an `PackagePublishingPocket` enum.
        :param component: is the name of a component.  If not given,
            the archive dependency will be tied to the component used
            for a corresponding source in primary archive.

        :raise: `ArchiveDependencyError` if given 'dependency' does not fit
            the context archive.
        :return: a `IArchiveDependency` object targeted to the context
            `IArchive` requiring 'dependency' `IArchive`.
        """
    @operation_parameters(
        dependency=Reference(schema=Interface, required=True),
        # Really IArchive
    )
    @export_write_operation()
    @operation_for_version('devel')
    def removeArchiveDependency(dependency):
        """Remove the `IArchiveDependency` record for the given dependency.

        :param dependency: is an `IArchive` object.
        """


class IArchiveCommercial(Interface):
    """Archive interface for operations restricted by commercial."""

    @operation_parameters(
        family=Reference(schema=Interface, required=True),
        # Really IProcessorFamily.
    )
    @export_write_operation()
    @operation_for_version('devel')
    def enableRestrictedFamily(family):
        """Add the processor family to the set of enabled restricted families.

        :param family: is an `IProcessorFamily` object.
        """


class IArchive(IArchivePublic, IArchiveAppend, IArchiveEdit, IArchiveView,
               IArchiveCommercial):
    """Main Archive interface."""
    export_as_webservice_entry()


class IPPA(IArchive):
    """Marker interface so traversal works differently for PPAs."""


class IDistributionArchive(IArchive):
    """Marker interface so traversal works differently for distro archives."""


class IArchiveEditDependenciesForm(Interface):
    """Schema used to edit dependencies settings within a archive."""

    dependency_candidate = Choice(
        title=_('Add PPA dependency'), required=False, vocabulary='PPA')


class IArchiveSet(Interface):
    """Interface for ArchiveSet"""

    title = Attribute('Title')

    def getNumberOfPPASourcesForDistribution(distribution):
        """Return the number of sources for PPAs in a given distribution.

        Only public and published sources are considered.
        """

    def getNumberOfPPABinariesForDistribution(distribution):
        """Return the number of binaries for PPAs in a given distribution.

        Only public and published sources are considered.
        """

    def new(purpose, owner, name=None, displayname=None, distribution=None,
            description=None, enabled=True, require_virtualized=True,
            private=False):
        """Create a new archive.

        On named-ppa creation, the signing key for the default PPA for the
        given owner will be used if it is present.

        :param purpose: `ArchivePurpose`;
        :param owner: `IPerson` owning the Archive;
        :param name: optional text to be used as the archive name, if not
            given it uses the names defined in
            `IArchiveSet._getDefaultArchiveNameForPurpose`;
        :param displayname: optional text that will be used as a reference
            to this archive in the UI. If not provided a default text
            (including the archive name and the owner displayname)  will be
            used.
        :param distribution: optional `IDistribution` to which the archive
            will be attached;
        :param description: optional text to be set as the archive
            description;
        :param enabled: whether the archive shall be enabled post creation
        :param require_virtualized: whether builds for the new archive shall
            be carried out on virtual builders
        :param private: whether or not to make the PPA private

        :return: an `IArchive` object.
        :raises AssertionError if name is already taken within distribution.
        """

    def get(archive_id):
        """Return the IArchive with the given archive_id."""

    def getPPAByDistributionAndOwnerName(distribution, person_name, ppa_name):
        """Return a single PPA.

        :param distribution: The context IDistribution.
        :param person_name: The context IPerson.
        :param ppa_name: The name of the archive (PPA)
        """

    def getByDistroPurpose(distribution, purpose, name=None):
        """Return the IArchive with the given distribution and purpose.

        It uses the default names defined in
        `IArchiveSet._getDefaultArchiveNameForPurpose`.

        :raises AssertionError if used for with ArchivePurpose.PPA.
        """

    def getByDistroAndName(distribution, name):
        """Return the `IArchive` with the given distribution and name."""

    def __iter__():
        """Iterates over existent archives, including the main_archives."""

    def getPPAOwnedByPerson(person, name=None, statuses=None,
                            has_packages=False):
        """Return the named PPA owned by person.

        :param person: An `IPerson`.  Required.
        :param name: The PPA name.  Optional.
        :param statuses: A list of statuses the PPAs must match.  Optional.
        :param has_packages: If True will only select PPAs that have published
            source packages.

        If the name is not supplied it will default to the
        first PPA that the person created.

        :raises NoSuchPPA: if the named PPA does not exist.
        """

    def getPPAsForUser(user):
        """Return all PPAs the given user can participate.

        The result is ordered by PPA displayname.
        """

    def getPPAsPendingSigningKey():
        """Return all PPAs pending signing key generation.

        The result is ordered by archive creation date.
        """

    def getLatestPPASourcePublicationsForDistribution(distribution):
        """The latest 5 PPA source publications for a given distribution.

        Private PPAs are excluded from the result.
        """

    def getMostActivePPAsForDistribution(distribution):
        """Return the 5 most active PPAs.

        The activity is currently measured by number of uploaded (published)
        sources for each PPA during the last 7 days.

        Private PPAs are excluded from the result.

        :return A list with up to 5 dictionaries containing the ppa 'title'
            and the number of 'uploads' keys and corresponding values.
        """

    def getBuildCountersForArchitecture(archive, distroarchseries):
        """Return a dictionary containing the build counters per status.

        The result is restricted to the given archive and distroarchseries.

        The returned dictionary contains the follwoing keys and values:

         * 'total': total number of builds (includes SUPERSEDED);
         * 'pending': number of builds in NEEDSBUILD or BUILDING state;
         * 'failed': number of builds in FAILEDTOBUILD, MANUALDEPWAIT,
           CHROOTWAIT and FAILEDTOUPLOAD state;
         * 'succeeded': number of SUCCESSFULLYBUILT builds.

        :param archive: target `IArchive`;
        :param distroarchseries: target `IDistroArchSeries`.

        :return a dictionary with the 4 keys specified above.
        """

    def getArchivesForDistribution(distribution, name=None, purposes=None,
        user=None, exclude_disabled=True):
        """Return a list of all the archives for a distribution.

        This will return all the archives for the given distribution, with
        the following parameters:

        :param distribution: target `IDistribution`
        :param name: An optional archive name which will further restrict
            the results to only those archives with this name.
        :param purposes: An optional archive purpose or list of purposes with
            which to filter the results.
        :param user: An optional `IPerson` who is requesting the archives,
            which is used to include private archives for which the user
            has permission. If it is not supplied, only public archives
            will be returned.
        :param exclude_disabled: Whether to exclude disabled archives.

        :return: A queryset of all the archives for the given
            distribution matching the given params.
        """

    def getPrivatePPAs():
        """Return a result set containing all private PPAs."""

    def getCommercialPPAs():
        """Return a result set containing all commercial PPAs.

        Commercial PPAs are private, but explicitly flagged up as commercial
        so that they are discoverable by people who wish to buy items
        from them.
        """

    def getPublicationsInArchives(source_package_name, archive_list,
                                  distribution):
        """Return a result set of publishing records for the source package.

        :param source_package_name: an `ISourcePackageName` identifying the
            source package for which the publishings will be returned.
        :param archive_list: a list of at least one archive with which to
            restrict the search.
        :param distribution: the distribution by which the results will
            be limited.
        :return: a resultset of the `ISourcePackagePublishingHistory` objects
            that are currently published in the given archives.
        """


default_name_by_purpose = {
    ArchivePurpose.PRIMARY: 'primary',
    ArchivePurpose.PPA: 'ppa',
    ArchivePurpose.PARTNER: 'partner',
    ArchivePurpose.DEBUG: 'debug',
    }


MAIN_ARCHIVE_PURPOSES = (
    ArchivePurpose.PRIMARY,
    ArchivePurpose.PARTNER,
    ArchivePurpose.DEBUG,
    )

ALLOW_RELEASE_BUILDS = (
    ArchivePurpose.PARTNER,
    ArchivePurpose.PPA,
    ArchivePurpose.COPY,
    )

FULL_COMPONENT_SUPPORT = (
    ArchivePurpose.PRIMARY,
    ArchivePurpose.DEBUG,
    ArchivePurpose.COPY,
    )

# Circular dependency issues fixed in _schema_circular_imports.py


def validate_external_dependencies(ext_deps):
    """Validate the external_dependencies field.

    :param ext_deps: The dependencies form field to check.
    """
    errors = []
    # The field can consist of multiple entries separated by
    # newlines, so process each in turn.
    for dep in ext_deps.splitlines():
        try:
            deb, url, suite, components = dep.split(" ", 3)
        except ValueError:
            errors.append(
                "'%s' is not a complete and valid sources.list entry"
                    % dep)
            continue

        if deb != "deb":
            errors.append("%s: Must start with 'deb'" % dep)
        url_components = urlparse(url)
        if not url_components[0] or not url_components[1]:
            errors.append("%s: Invalid URL" % dep)

    return errors